idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
28,400
private void parseSchemasElement ( Element element , BeanDefinitionBuilder builder , ParserContext parserContext ) { Element schemasElement = DomUtils . getChildElementByTagName ( element , SCHEMAS ) ; if ( schemasElement != null ) { List < Element > schemaElements = DomUtils . getChildElements ( schemasElement ) ; ManagedList < RuntimeBeanReference > beanReferences = constructRuntimeBeanReferences ( parserContext , schemaElements ) ; if ( ! beanReferences . isEmpty ( ) ) { builder . addPropertyValue ( SCHEMAS , beanReferences ) ; } } }
Parses the given schema element to RuntimeBeanReference in consideration of the given context and adds them to the builder
131
24
28,401
private ManagedList < RuntimeBeanReference > constructRuntimeBeanReferences ( ParserContext parserContext , List < Element > schemaElements ) { ManagedList < RuntimeBeanReference > runtimeBeanReferences = new ManagedList <> ( ) ; for ( Element schemaElement : schemaElements ) { if ( schemaElement . hasAttribute ( SCHEMA ) ) { runtimeBeanReferences . add ( new RuntimeBeanReference ( schemaElement . getAttribute ( SCHEMA ) ) ) ; } else { schemaParser . parse ( schemaElement , parserContext ) ; runtimeBeanReferences . add ( new RuntimeBeanReference ( schemaElement . getAttribute ( ID ) ) ) ; } } return runtimeBeanReferences ; }
Construct a List of RuntimeBeanReferences from the given list of schema elements under consideration of the given parser context
151
22
28,402
private PublicKey readKey ( InputStream is ) { InputStreamReader isr = new InputStreamReader ( is ) ; PEMParser r = new PEMParser ( isr ) ; try { Object o = r . readObject ( ) ; if ( o instanceof PEMKeyPair ) { PEMKeyPair keyPair = ( PEMKeyPair ) o ; if ( keyPair . getPublicKeyInfo ( ) != null && keyPair . getPublicKeyInfo ( ) . getEncoded ( ) . length > 0 ) { return provider . getPublicKey ( keyPair . getPublicKeyInfo ( ) ) ; } } else if ( o instanceof SubjectPublicKeyInfo ) { return provider . getPublicKey ( ( SubjectPublicKeyInfo ) o ) ; } } catch ( IOException e ) { // Ignoring, returning null log . warn ( "Failed to get key from PEM file" , e ) ; } finally { IoUtils . closeQuietly ( isr , r ) ; } return null ; }
Read the key with bouncycastle s PEM tools
224
11
28,403
public boolean sendMessage ( WebSocketMessage < ? > message ) { boolean sentSuccessfully = false ; if ( sessions . isEmpty ( ) ) { LOG . warn ( "No Web Socket session exists - message cannot be sent" ) ; } for ( WebSocketSession session : sessions . values ( ) ) { if ( session != null && session . isOpen ( ) ) { try { session . sendMessage ( message ) ; sentSuccessfully = true ; } catch ( IOException e ) { LOG . error ( String . format ( "(%s) error sending message" , session . getId ( ) ) , e ) ; } } } return sentSuccessfully ; }
Publish message to all sessions known to this handler .
139
11
28,404
public ValidationMatcherLibrary getLibraryForPrefix ( String validationMatcherPrefix ) { if ( validationMatcherLibraries != null ) { for ( ValidationMatcherLibrary validationMatcherLibrary : validationMatcherLibraries ) { if ( validationMatcherLibrary . getPrefix ( ) . equals ( validationMatcherPrefix ) ) { return validationMatcherLibrary ; } } } throw new NoSuchValidationMatcherLibraryException ( "Can not find validationMatcher library for prefix " + validationMatcherPrefix ) ; }
Get library for validationMatcher prefix .
113
8
28,405
public S ms ( Long milliseconds ) { builder . milliseconds ( String . valueOf ( milliseconds ) ) ; return self ; }
The total length of milliseconds to wait on the condition to be satisfied
25
13
28,406
public S interval ( Long interval ) { builder . interval ( String . valueOf ( interval ) ) ; return self ; }
The interval in seconds to use between each test of the condition
25
12
28,407
public static String makeIECachingSafeUrl ( String url , long unique ) { if ( url . contains ( "timestamp=" ) ) { return url . replaceFirst ( "(.*)(timestamp=)(.*)([&#].*)" , "$1$2" + unique + "$4" ) . replaceFirst ( "(.*)(timestamp=)(.*)$" , "$1$2" + unique ) ; } else { return url . contains ( "?" ) ? url + "&timestamp=" + unique : url + "?timestamp=" + unique ; } }
Makes new unique URL to avoid IE caching .
123
10
28,408
public String getStackMessage ( ) { if ( lineNumberEnd . longValue ( ) > 0 && ! lineNumberStart . equals ( lineNumberEnd ) ) { return "at " + testFilePath + "(" + actionName + ":" + lineNumberStart + "-" + lineNumberEnd + ")" ; } else { return "at " + testFilePath + "(" + actionName + ":" + lineNumberStart + ")" ; } }
Constructs the stack trace message .
96
7
28,409
protected ResponseItem success ( ) { ResponseItem response = new ResponseItem ( ) ; Field statusField = ReflectionUtils . findField ( ResponseItem . class , "status" ) ; ReflectionUtils . makeAccessible ( statusField ) ; ReflectionUtils . setField ( statusField , response , "success" ) ; return response ; }
Construct default success response for commands without return value .
74
10
28,410
protected String getParameter ( String parameterName , TestContext context ) { if ( getParameters ( ) . containsKey ( parameterName ) ) { return context . replaceDynamicContentInString ( getParameters ( ) . get ( parameterName ) . toString ( ) ) ; } else { throw new CitrusRuntimeException ( String . format ( "Missing docker command parameter '%s'" , parameterName ) ) ; } }
Gets the docker command parameter .
86
7
28,411
public KafkaEndpointBuilder producerProperties ( Map < String , Object > producerProperties ) { endpoint . getEndpointConfiguration ( ) . setProducerProperties ( producerProperties ) ; return this ; }
Sets the producer properties .
44
6
28,412
public KafkaEndpointBuilder consumerProperties ( Map < String , Object > consumerProperties ) { endpoint . getEndpointConfiguration ( ) . setConsumerProperties ( consumerProperties ) ; return this ; }
Sets the consumer properties .
43
6
28,413
private void validateText ( String receivedMessagePayload , String controlMessagePayload ) { if ( ! StringUtils . hasText ( controlMessagePayload ) ) { log . debug ( "Skip message payload validation as no control message was defined" ) ; return ; } else { Assert . isTrue ( StringUtils . hasText ( receivedMessagePayload ) , "Validation failed - " + "expected message contents, but received empty message!" ) ; } if ( ! receivedMessagePayload . equals ( controlMessagePayload ) ) { if ( StringUtils . trimAllWhitespace ( receivedMessagePayload ) . equals ( StringUtils . trimAllWhitespace ( controlMessagePayload ) ) ) { throw new ValidationException ( "Text values not equal (only whitespaces!), expected '" + controlMessagePayload + "' " + "but was '" + receivedMessagePayload + "'" ) ; } else { throw new ValidationException ( "Text values not equal, expected '" + controlMessagePayload + "' " + "but was '" + receivedMessagePayload + "'" ) ; } } }
Compares two string with each other in order to validate plain text .
240
14
28,414
private String normalizeWhitespace ( String payload ) { if ( ignoreWhitespace ) { StringBuilder result = new StringBuilder ( ) ; boolean lastWasSpace = true ; for ( int i = 0 ; i < payload . length ( ) ; i ++ ) { char c = payload . charAt ( i ) ; if ( Character . isWhitespace ( c ) ) { if ( ! lastWasSpace ) { result . append ( ' ' ) ; } lastWasSpace = true ; } else { result . append ( c ) ; lastWasSpace = false ; } } return result . toString ( ) . trim ( ) ; } if ( ignoreNewLineType ) { return payload . replaceAll ( "\\r(\\n)?" , "\n" ) ; } return payload ; }
Normalize whitespace characters if appropriate . Based on system property settings this method normalizes new line characters exclusively or filters all whitespaces such as double whitespaces and new lines .
167
35
28,415
public HttpClientBuilder interceptor ( ClientHttpRequestInterceptor interceptor ) { if ( endpoint . getEndpointConfiguration ( ) . getClientInterceptors ( ) == null ) { endpoint . getEndpointConfiguration ( ) . setClientInterceptors ( new ArrayList < ClientHttpRequestInterceptor > ( ) ) ; } endpoint . getEndpointConfiguration ( ) . getClientInterceptors ( ) . add ( interceptor ) ; return this ; }
Sets a client single interceptor .
96
8
28,416
private FormData createFormData ( Message message ) { FormData formData = new ObjectFactory ( ) . createFormData ( ) ; formData . setContentType ( getFormContentType ( message ) ) ; formData . setAction ( getFormAction ( message ) ) ; if ( message . getPayload ( ) instanceof MultiValueMap ) { MultiValueMap < String , Object > formValueMap = message . getPayload ( MultiValueMap . class ) ; for ( Map . Entry < String , List < Object > > entry : formValueMap . entrySet ( ) ) { Control control = new ObjectFactory ( ) . createControl ( ) ; control . setName ( entry . getKey ( ) ) ; control . setValue ( StringUtils . arrayToCommaDelimitedString ( entry . getValue ( ) . toArray ( ) ) ) ; formData . addControl ( control ) ; } } else { String rawFormData = message . getPayload ( String . class ) ; if ( StringUtils . hasText ( rawFormData ) ) { StringTokenizer tokenizer = new StringTokenizer ( rawFormData , "&" ) ; while ( tokenizer . hasMoreTokens ( ) ) { Control control = new ObjectFactory ( ) . createControl ( ) ; String [ ] nameValuePair = tokenizer . nextToken ( ) . split ( "=" ) ; if ( autoDecode ) { try { control . setName ( URLDecoder . decode ( nameValuePair [ 0 ] , getEncoding ( ) ) ) ; control . setValue ( URLDecoder . decode ( nameValuePair [ 1 ] , getEncoding ( ) ) ) ; } catch ( UnsupportedEncodingException e ) { throw new CitrusRuntimeException ( String . format ( "Failed to decode form control value '%s=%s'" , nameValuePair [ 0 ] , nameValuePair [ 1 ] ) , e ) ; } } else { control . setName ( nameValuePair [ 0 ] ) ; control . setValue ( nameValuePair [ 1 ] ) ; } formData . addControl ( control ) ; } } } return formData ; }
Create form data model object from url encoded message payload .
466
11
28,417
private String getFormAction ( Message message ) { return message . getHeader ( HttpMessageHeaders . HTTP_REQUEST_URI ) != null ? message . getHeader ( HttpMessageHeaders . HTTP_REQUEST_URI ) . toString ( ) : null ; }
Reads form action target from message headers .
59
9
28,418
private String getFormContentType ( Message message ) { return message . getHeader ( HttpMessageHeaders . HTTP_CONTENT_TYPE ) != null ? message . getHeader ( HttpMessageHeaders . HTTP_CONTENT_TYPE ) . toString ( ) : null ; }
Reads form content type from message headers .
60
9
28,419
protected < T > T convertIfNecessary ( String value , T originalValue ) { if ( originalValue == null ) { return ( T ) value ; } return TypeConversionUtils . convertIfNecessary ( value , ( Class < T > ) originalValue . getClass ( ) ) ; }
Convert to original value type if necessary .
67
9
28,420
private Map < String , String > convertToMap ( Object expression ) { if ( expression instanceof Map ) { return ( Map < String , String > ) expression ; } return Stream . of ( Optional . ofNullable ( expression ) . map ( Object :: toString ) . orElse ( "" ) . split ( "," ) ) . map ( keyValue -> Optional . ofNullable ( StringUtils . split ( keyValue , "=" ) ) . orElse ( new String [ ] { keyValue , "" } ) ) . collect ( Collectors . toMap ( keyValue -> keyValue [ 0 ] , keyValue -> keyValue [ 1 ] ) ) ; }
Convert query string key - value expression to map .
140
11
28,421
public String buildMessagePayload ( TestContext context , String messageType ) { try { //construct control message payload String messagePayload = "" ; if ( scriptResourcePath != null ) { messagePayload = buildMarkupBuilderScript ( context . replaceDynamicContentInString ( FileUtils . readToString ( FileUtils . getFileResource ( scriptResourcePath , context ) , Charset . forName ( context . resolveDynamicValue ( scriptResourceCharset ) ) ) ) ) ; } else if ( scriptData != null ) { messagePayload = buildMarkupBuilderScript ( context . replaceDynamicContentInString ( scriptData ) ) ; } return messagePayload ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to build control message payload" , e ) ; } }
Build the control message from script code .
173
8
28,422
private String buildMarkupBuilderScript ( String scriptData ) { try { ClassLoader parent = GroovyScriptMessageBuilder . class . getClassLoader ( ) ; GroovyClassLoader loader = new GroovyClassLoader ( parent ) ; Class < ? > groovyClass = loader . parseClass ( TemplateBasedScriptBuilder . fromTemplateResource ( scriptTemplateResource ) . withCode ( scriptData ) . build ( ) ) ; if ( groovyClass == null ) { throw new CitrusRuntimeException ( "Could not load groovy script!" ) ; } GroovyObject groovyObject = ( GroovyObject ) groovyClass . newInstance ( ) ; return ( String ) groovyObject . invokeMethod ( "run" , new Object [ ] { } ) ; } catch ( CompilationFailedException e ) { throw new CitrusRuntimeException ( e ) ; } catch ( InstantiationException e ) { throw new CitrusRuntimeException ( e ) ; } catch ( IllegalAccessException e ) { throw new CitrusRuntimeException ( e ) ; } }
Builds an automatic Groovy MarkupBuilder script with given script body .
219
15
28,423
protected InputStream getTemplateAsStream ( TestContext context ) { Resource resource ; if ( templateResource != null ) { resource = templateResource ; } else { resource = FileUtils . getFileResource ( template , context ) ; } String templateYml ; try { templateYml = context . replaceDynamicContentInString ( FileUtils . readToString ( resource ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read template resource" , e ) ; } return new ByteArrayInputStream ( templateYml . getBytes ( ) ) ; }
Create input stream from template resource and add test variable support .
125
12
28,424
public static String resolveFunction ( String functionString , TestContext context ) { String functionExpression = VariableUtils . cutOffVariablesPrefix ( functionString ) ; if ( ! functionExpression . contains ( "(" ) || ! functionExpression . endsWith ( ")" ) || ! functionExpression . contains ( ":" ) ) { throw new InvalidFunctionUsageException ( "Unable to resolve function: " + functionExpression ) ; } String functionPrefix = functionExpression . substring ( 0 , functionExpression . indexOf ( ' ' ) + 1 ) ; String parameterString = functionExpression . substring ( functionExpression . indexOf ( ' ' ) + 1 , functionExpression . length ( ) - 1 ) ; String function = functionExpression . substring ( functionPrefix . length ( ) , functionExpression . indexOf ( ' ' ) ) ; FunctionLibrary library = context . getFunctionRegistry ( ) . getLibraryForPrefix ( functionPrefix ) ; parameterString = VariableUtils . replaceVariablesInString ( parameterString , context , false ) ; parameterString = replaceFunctionsInString ( parameterString , context ) ; String value = library . getFunction ( function ) . execute ( FunctionParameterHelper . getParameterList ( parameterString ) , context ) ; if ( value == null ) { return "" ; } else { return value ; } }
This method resolves a custom function to its respective result .
293
11
28,425
public AssertSoapFaultBuilder faultDetailResource ( Resource resource , Charset charset ) { try { action . getFaultDetails ( ) . add ( FileUtils . readToString ( resource , charset ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read fault detail resource" , e ) ; } return this ; }
Expect fault detail from file resource .
84
8
28,426
public AssertSoapFaultBuilder validator ( String validatorName , ApplicationContext applicationContext ) { action . setValidator ( applicationContext . getBean ( validatorName , SoapFaultValidator . class ) ) ; return this ; }
Set explicit SOAP fault validator implementation by bean name .
54
12
28,427
public Integer getPartition ( ) { Object partition = getHeader ( KafkaMessageHeaders . PARTITION ) ; if ( partition != null ) { return TypeConversionUtils . convertIfNecessary ( partition , Integer . class ) ; } return null ; }
Gets the Kafka partition header .
56
7
28,428
public Long getTimestamp ( ) { Object timestamp = getHeader ( KafkaMessageHeaders . TIMESTAMP ) ; if ( timestamp != null ) { return Long . valueOf ( timestamp . toString ( ) ) ; } return null ; }
Gets the Kafka timestamp header .
50
7
28,429
public Long getOffset ( ) { Object offset = getHeader ( KafkaMessageHeaders . OFFSET ) ; if ( offset != null ) { return TypeConversionUtils . convertIfNecessary ( offset , Long . class ) ; } return 0L ; }
Gets the Kafka offset header .
57
7
28,430
public Object getMessageKey ( ) { Object key = getHeader ( KafkaMessageHeaders . MESSAGE_KEY ) ; if ( key != null ) { return key ; } return null ; }
Gets the Kafka message key header .
42
8
28,431
public String getTopic ( ) { Object topic = getHeader ( KafkaMessageHeaders . TOPIC ) ; if ( topic != null ) { return topic . toString ( ) ; } return null ; }
Gets the Kafka topic header .
42
7
28,432
public Wait action ( TestAction action ) { if ( action instanceof TestActionBuilder ) { getCondition ( ) . setAction ( ( ( TestActionBuilder ) action ) . build ( ) ) ; this . action . setAction ( ( ( TestActionBuilder ) action ) . build ( ) ) ; getBuilder ( ) . actions ( ( ( TestActionBuilder ) action ) . build ( ) ) ; } else { getCondition ( ) . setAction ( action ) ; this . action . setAction ( action ) ; getBuilder ( ) . actions ( action ) ; } return getBuilder ( ) . build ( ) ; }
Sets the test action to execute and wait for .
129
11
28,433
private String getRequestContent ( HttpRequest request , String body ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( request . getMethod ( ) ) ; builder . append ( " " ) ; builder . append ( request . getURI ( ) ) ; builder . append ( NEWLINE ) ; appendHeaders ( request . getHeaders ( ) , builder ) ; builder . append ( NEWLINE ) ; builder . append ( body ) ; return builder . toString ( ) ; }
Builds request content string from request and body .
104
10
28,434
private String getResponseContent ( CachingClientHttpResponseWrapper response ) throws IOException { if ( response != null ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "HTTP/1.1 " ) ; // TODO get Http version from message builder . append ( response . getStatusCode ( ) ) ; builder . append ( " " ) ; builder . append ( response . getStatusText ( ) ) ; builder . append ( NEWLINE ) ; appendHeaders ( response . getHeaders ( ) , builder ) ; builder . append ( NEWLINE ) ; builder . append ( response . getBodyContent ( ) ) ; return builder . toString ( ) ; } else { return "" ; } }
Builds response content string from response object .
152
9
28,435
private void appendHeaders ( HttpHeaders headers , StringBuilder builder ) { for ( Entry < String , List < String > > headerEntry : headers . entrySet ( ) ) { builder . append ( headerEntry . getKey ( ) ) ; builder . append ( ":" ) ; builder . append ( StringUtils . arrayToCommaDelimitedString ( headerEntry . getValue ( ) . toArray ( ) ) ) ; builder . append ( NEWLINE ) ; } }
Append Http headers to string builder .
102
9
28,436
public ContainerStart start ( String containerId ) { ContainerStart command = new ContainerStart ( ) ; command . container ( containerId ) ; action . setCommand ( command ) ; return command ; }
Adds a start command .
40
5
28,437
public ContainerStop stop ( String containerId ) { ContainerStop command = new ContainerStop ( ) ; command . container ( containerId ) ; action . setCommand ( command ) ; return command ; }
Adds a stop command .
40
5
28,438
public ContainerWait wait ( String containerId ) { ContainerWait command = new ContainerWait ( ) ; command . container ( containerId ) ; action . setCommand ( command ) ; return command ; }
Adds a wait command .
40
5
28,439
public T messageType ( String messageType ) { this . messageType = messageType ; getAction ( ) . setMessageType ( messageType ) ; if ( binaryMessageConstructionInterceptor . supportsMessageType ( messageType ) ) { getMessageContentBuilder ( ) . add ( binaryMessageConstructionInterceptor ) ; } if ( gzipMessageConstructionInterceptor . supportsMessageType ( messageType ) ) { getMessageContentBuilder ( ) . add ( gzipMessageConstructionInterceptor ) ; } return self ; }
Sets a explicit message type for this send action .
105
11
28,440
public T xpath ( String expression , String value ) { if ( xpathMessageConstructionInterceptor == null ) { xpathMessageConstructionInterceptor = new XpathMessageConstructionInterceptor ( ) ; if ( getAction ( ) . getMessageBuilder ( ) != null ) { ( getAction ( ) . getMessageBuilder ( ) ) . add ( xpathMessageConstructionInterceptor ) ; } else { PayloadTemplateMessageBuilder messageBuilder = new PayloadTemplateMessageBuilder ( ) ; messageBuilder . getMessageInterceptors ( ) . add ( xpathMessageConstructionInterceptor ) ; getAction ( ) . setMessageBuilder ( messageBuilder ) ; } } xpathMessageConstructionInterceptor . getXPathExpressions ( ) . put ( expression , value ) ; return self ; }
Adds XPath manipulating expression that evaluates to message payload before sending .
162
13
28,441
public T jsonPath ( String expression , String value ) { if ( jsonPathMessageConstructionInterceptor == null ) { jsonPathMessageConstructionInterceptor = new JsonPathMessageConstructionInterceptor ( ) ; if ( getAction ( ) . getMessageBuilder ( ) != null ) { ( getAction ( ) . getMessageBuilder ( ) ) . add ( jsonPathMessageConstructionInterceptor ) ; } else { PayloadTemplateMessageBuilder messageBuilder = new PayloadTemplateMessageBuilder ( ) ; messageBuilder . getMessageInterceptors ( ) . add ( jsonPathMessageConstructionInterceptor ) ; getAction ( ) . setMessageBuilder ( messageBuilder ) ; } } jsonPathMessageConstructionInterceptor . getJsonPathExpressions ( ) . put ( expression , value ) ; return self ; }
Adds JSONPath manipulating expression that evaluates to message payload before sending .
164
13
28,442
protected void logRequest ( String logMessage , MessageContext messageContext , boolean incoming ) throws TransformerException { if ( messageContext . getRequest ( ) instanceof SoapMessage ) { logSoapMessage ( logMessage , ( SoapMessage ) messageContext . getRequest ( ) , incoming ) ; } else { logWebServiceMessage ( logMessage , messageContext . getRequest ( ) , incoming ) ; } }
Logs request message from message context . SOAP messages get logged with envelope transformation other messages with serialization .
86
22
28,443
protected void logResponse ( String logMessage , MessageContext messageContext , boolean incoming ) throws TransformerException { if ( messageContext . hasResponse ( ) ) { if ( messageContext . getResponse ( ) instanceof SoapMessage ) { logSoapMessage ( logMessage , ( SoapMessage ) messageContext . getResponse ( ) , incoming ) ; } else { logWebServiceMessage ( logMessage , messageContext . getResponse ( ) , incoming ) ; } } }
Logs response message from message context if any . SOAP messages get logged with envelope transformation other messages with serialization .
98
24
28,444
protected void logSoapMessage ( String logMessage , SoapMessage soapMessage , boolean incoming ) throws TransformerException { Transformer transformer = createIndentingTransformer ( ) ; StringWriter writer = new StringWriter ( ) ; transformer . transform ( soapMessage . getEnvelope ( ) . getSource ( ) , new StreamResult ( writer ) ) ; logMessage ( logMessage , XMLUtils . prettyPrint ( writer . toString ( ) ) , incoming ) ; }
Log SOAP message with transformer instance .
99
8
28,445
protected void logMessage ( String logMessage , String message , boolean incoming ) { if ( messageListener != null ) { log . debug ( logMessage ) ; if ( incoming ) { messageListener . onInboundMessage ( new RawMessage ( message ) , null ) ; } else { messageListener . onOutboundMessage ( new RawMessage ( message ) , null ) ; } } else { if ( log . isDebugEnabled ( ) ) { log . debug ( logMessage + ":" + System . getProperty ( "line.separator" ) + message ) ; } } }
Performs the final logger call with dynamic message .
120
10
28,446
private Transformer createIndentingTransformer ( ) throws TransformerConfigurationException { Transformer transformer = createTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , "yes" ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; return transformer ; }
Get transformer implementation with output properties set .
72
8
28,447
private org . apache . kafka . clients . producer . KafkaProducer < Object , Object > createKafkaProducer ( ) { Map < String , Object > producerProps = new HashMap <> ( ) ; producerProps . put ( ProducerConfig . BOOTSTRAP_SERVERS_CONFIG , endpointConfiguration . getServer ( ) ) ; producerProps . put ( ProducerConfig . REQUEST_TIMEOUT_MS_CONFIG , new Long ( endpointConfiguration . getTimeout ( ) ) . intValue ( ) ) ; producerProps . put ( ProducerConfig . KEY_SERIALIZER_CLASS_CONFIG , endpointConfiguration . getKeySerializer ( ) ) ; producerProps . put ( ProducerConfig . VALUE_SERIALIZER_CLASS_CONFIG , endpointConfiguration . getValueSerializer ( ) ) ; producerProps . put ( ProducerConfig . CLIENT_ID_CONFIG , Optional . ofNullable ( endpointConfiguration . getClientId ( ) ) . orElse ( KafkaMessageHeaders . KAFKA_PREFIX + "producer_" + UUID . randomUUID ( ) . toString ( ) ) ) ; producerProps . putAll ( endpointConfiguration . getProducerProperties ( ) ) ; return new org . apache . kafka . clients . producer . KafkaProducer <> ( producerProps ) ; }
Creates default KafkaTemplate instance from endpoint configuration .
297
10
28,448
public void setProducer ( org . apache . kafka . clients . producer . KafkaProducer < Object , Object > producer ) { this . producer = producer ; }
Sets the producer .
37
5
28,449
public void start ( ) { application = new CitrusRemoteApplication ( configuration ) ; port ( configuration . getPort ( ) ) ; application . init ( ) ; if ( ! configuration . isSkipTests ( ) ) { new RunController ( configuration ) . run ( ) ; } if ( configuration . getTimeToLive ( ) == 0 ) { stop ( ) ; } }
Start server instance and listen for incoming requests .
78
9
28,450
public boolean waitForCompletion ( ) { try { return completed . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { log . warn ( "Failed to wait for server completion" , e ) ; } return false ; }
Waits for completed state of application .
52
8
28,451
public JmxServerBuilder environmentProperties ( Properties environmentProperties ) { HashMap < String , Object > properties = new HashMap <> ( environmentProperties . size ( ) ) ; for ( Map . Entry < Object , Object > entry : environmentProperties . entrySet ( ) ) { properties . put ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) ) ; } endpoint . getEndpointConfiguration ( ) . setEnvironmentProperties ( properties ) ; return this ; }
Sets the environment properties .
107
6
28,452
public JmxServerBuilder timeout ( long timeout ) { endpoint . setDefaultTimeout ( timeout ) ; endpoint . getEndpointConfiguration ( ) . setTimeout ( timeout ) ; return this ; }
Sets the default timeout .
39
6
28,453
private void parseFault ( BeanDefinitionBuilder builder , Element faultElement ) { if ( faultElement != null ) { Element faultCodeElement = DomUtils . getChildElementByTagName ( faultElement , "fault-code" ) ; if ( faultCodeElement != null ) { builder . addPropertyValue ( "faultCode" , DomUtils . getTextValue ( faultCodeElement ) . trim ( ) ) ; } Element faultStringElement = DomUtils . getChildElementByTagName ( faultElement , "fault-string" ) ; if ( faultStringElement != null ) { builder . addPropertyValue ( "faultString" , DomUtils . getTextValue ( faultStringElement ) . trim ( ) ) ; } Element faultActorElement = DomUtils . getChildElementByTagName ( faultElement , "fault-actor" ) ; if ( faultActorElement != null ) { builder . addPropertyValue ( "faultActor" , DomUtils . getTextValue ( faultActorElement ) . trim ( ) ) ; } parseFaultDetail ( builder , faultElement ) ; } }
Parses the SOAP fault information .
239
9
28,454
private void parseFaultDetail ( BeanDefinitionBuilder builder , Element faultElement ) { List < Element > faultDetailElements = DomUtils . getChildElementsByTagName ( faultElement , "fault-detail" ) ; List < String > faultDetails = new ArrayList < String > ( ) ; List < String > faultDetailResourcePaths = new ArrayList < String > ( ) ; for ( Element faultDetailElement : faultDetailElements ) { if ( faultDetailElement . hasAttribute ( "file" ) ) { if ( StringUtils . hasText ( DomUtils . getTextValue ( faultDetailElement ) . trim ( ) ) ) { throw new BeanCreationException ( "You tried to set fault-detail by file resource attribute and inline text value at the same time! " + "Please choose one of them." ) ; } String charset = faultDetailElement . getAttribute ( "charset" ) ; String filePath = faultDetailElement . getAttribute ( "file" ) ; faultDetailResourcePaths . add ( filePath + ( StringUtils . hasText ( charset ) ? FileUtils . FILE_PATH_CHARSET_PARAMETER + charset : "" ) ) ; } else { String faultDetailData = DomUtils . getTextValue ( faultDetailElement ) . trim ( ) ; if ( StringUtils . hasText ( faultDetailData ) ) { faultDetails . add ( faultDetailData ) ; } else { throw new BeanCreationException ( "Not content for fault-detail is set! Either use file attribute or inline text value for fault-detail element." ) ; } } } builder . addPropertyValue ( "faultDetails" , faultDetails ) ; builder . addPropertyValue ( "faultDetailResourcePaths" , faultDetailResourcePaths ) ; }
Parses the fault detail element .
405
8
28,455
public static FtpMessage command ( FTPCmd command ) { Command cmd = new Command ( ) ; cmd . setSignal ( command . getCommand ( ) ) ; return new FtpMessage ( cmd ) ; }
Sets the ftp command .
45
7
28,456
public static FtpMessage connect ( String sessionId ) { ConnectCommand cmd = new ConnectCommand ( ) ; cmd . setSignal ( "OPEN" ) ; cmd . setSessionId ( sessionId ) ; return new FtpMessage ( cmd ) ; }
Creates new connect command message .
54
7
28,457
public FtpMessage arguments ( String arguments ) { if ( command != null ) { command . setArguments ( arguments ) ; } setHeader ( FtpMessageHeaders . FTP_ARGS , arguments ) ; return this ; }
Sets the command args .
48
6
28,458
public String getSignal ( ) { return Optional . ofNullable ( getHeader ( FtpMessageHeaders . FTP_COMMAND ) ) . map ( Object :: toString ) . orElse ( null ) ; }
Gets the ftp command signal .
47
8
28,459
public String getArguments ( ) { return Optional . ofNullable ( getHeader ( FtpMessageHeaders . FTP_ARGS ) ) . map ( Object :: toString ) . orElse ( null ) ; }
Gets the command args .
46
6
28,460
public Integer getReplyCode ( ) { Object replyCode = getHeader ( FtpMessageHeaders . FTP_REPLY_CODE ) ; if ( replyCode != null ) { if ( replyCode instanceof Integer ) { return ( Integer ) replyCode ; } else { return Integer . valueOf ( replyCode . toString ( ) ) ; } } else if ( commandResult != null ) { return Optional . ofNullable ( commandResult . getReplyCode ( ) ) . map ( Integer :: valueOf ) . orElse ( FTPReply . COMMAND_OK ) ; } return null ; }
Gets the reply code .
128
6
28,461
public String getReplyString ( ) { Object replyString = getHeader ( FtpMessageHeaders . FTP_REPLY_STRING ) ; if ( replyString != null ) { return replyString . toString ( ) ; } return null ; }
Gets the reply string .
53
6
28,462
private < T extends CommandResultType > T getCommandResult ( ) { if ( commandResult == null ) { if ( getPayload ( ) instanceof String ) { this . commandResult = ( T ) marshaller . unmarshal ( new StringSource ( getPayload ( String . class ) ) ) ; } } return ( T ) commandResult ; }
Gets the command result if any or tries to unmarshal String payload representation to an command result model .
76
22
28,463
private < T extends CommandType > T getCommand ( ) { if ( command == null ) { if ( getPayload ( ) instanceof String ) { this . command = ( T ) marshaller . unmarshal ( new StringSource ( getPayload ( String . class ) ) ) ; } } return ( T ) command ; }
Gets the command if any or tries to unmarshal String payload representation to an command model .
71
20
28,464
private void setCommandHeader ( CommandType command ) { String header ; if ( command instanceof ConnectCommand ) { header = FtpMessage . OPEN_COMMAND ; } else if ( command instanceof GetCommand ) { header = FTPCmd . RETR . getCommand ( ) ; } else if ( command instanceof PutCommand ) { header = FTPCmd . STOR . getCommand ( ) ; } else if ( command instanceof ListCommand ) { header = FTPCmd . LIST . getCommand ( ) ; } else if ( command instanceof DeleteCommand ) { header = FTPCmd . DELE . getCommand ( ) ; } else { header = command . getSignal ( ) ; } setHeader ( FtpMessageHeaders . FTP_COMMAND , header ) ; }
Gets command header as ftp signal from command object .
166
12
28,465
public static boolean evaluate ( final String expression ) { final Deque < String > operators = new ArrayDeque <> ( ) ; final Deque < String > values = new ArrayDeque <> ( ) ; final boolean result ; char currentCharacter ; int currentCharacterIndex = 0 ; try { while ( currentCharacterIndex < expression . length ( ) ) { currentCharacter = expression . charAt ( currentCharacterIndex ) ; if ( SeparatorToken . OPEN_PARENTHESIS . value == currentCharacter ) { operators . push ( SeparatorToken . OPEN_PARENTHESIS . toString ( ) ) ; currentCharacterIndex += moveCursor ( SeparatorToken . OPEN_PARENTHESIS . toString ( ) ) ; } else if ( SeparatorToken . SPACE . value == currentCharacter ) { currentCharacterIndex += moveCursor ( SeparatorToken . SPACE . toString ( ) ) ; } else if ( SeparatorToken . CLOSE_PARENTHESIS . value == currentCharacter ) { evaluateSubexpression ( operators , values ) ; currentCharacterIndex += moveCursor ( SeparatorToken . CLOSE_PARENTHESIS . toString ( ) ) ; } else if ( ! Character . isDigit ( currentCharacter ) ) { final String parsedNonDigit = parseNonDigits ( expression , currentCharacterIndex ) ; if ( isBoolean ( parsedNonDigit ) ) { values . push ( replaceBooleanStringByIntegerRepresentation ( parsedNonDigit ) ) ; } else { operators . push ( validateOperator ( parsedNonDigit ) ) ; } currentCharacterIndex += moveCursor ( parsedNonDigit ) ; } else if ( Character . isDigit ( currentCharacter ) ) { final String parsedDigits = parseDigits ( expression , currentCharacterIndex ) ; values . push ( parsedDigits ) ; currentCharacterIndex += moveCursor ( parsedDigits ) ; } } result = Boolean . valueOf ( evaluateExpressionStack ( operators , values ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Boolean expression {} evaluates to {}" , expression , result ) ; } } catch ( final NoSuchElementException e ) { throw new CitrusRuntimeException ( "Unable to parse boolean expression '" + expression + "'. Maybe expression is incomplete!" , e ) ; } return result ; }
Perform evaluation of boolean expression string .
509
8
28,466
private static String evaluateExpressionStack ( final Deque < String > operators , final Deque < String > values ) { while ( ! operators . isEmpty ( ) ) { values . push ( getBooleanResultAsString ( operators . pop ( ) , values . pop ( ) , values . pop ( ) ) ) ; } return replaceIntegerStringByBooleanRepresentation ( values . pop ( ) ) ; }
This method takes stacks of operators and values and evaluates possible expressions This is done by popping one operator and two values applying the operator to the values and pushing the result back onto the value stack
86
37
28,467
private static void evaluateSubexpression ( final Deque < String > operators , final Deque < String > values ) { String operator = operators . pop ( ) ; while ( ! ( operator ) . equals ( SeparatorToken . OPEN_PARENTHESIS . toString ( ) ) ) { values . push ( getBooleanResultAsString ( operator , values . pop ( ) , values . pop ( ) ) ) ; operator = operators . pop ( ) ; } }
Evaluates a sub expression within a pair of parentheses and pushes its result onto the stack of values
99
20
28,468
private static String parseDigits ( final String expression , final int startIndex ) { final StringBuilder digitBuffer = new StringBuilder ( ) ; char currentCharacter = expression . charAt ( startIndex ) ; int subExpressionIndex = startIndex ; do { digitBuffer . append ( currentCharacter ) ; ++ subExpressionIndex ; if ( subExpressionIndex < expression . length ( ) ) { currentCharacter = expression . charAt ( subExpressionIndex ) ; } } while ( subExpressionIndex < expression . length ( ) && Character . isDigit ( currentCharacter ) ) ; return digitBuffer . toString ( ) ; }
This method reads digit characters from a given string starting at a given index . It will read till the end of the string or up until it encounters a non - digit character
132
34
28,469
private static String replaceBooleanStringByIntegerRepresentation ( final String possibleBooleanString ) { if ( possibleBooleanString . equals ( TRUE . toString ( ) ) ) { return "1" ; } else if ( possibleBooleanString . equals ( FALSE . toString ( ) ) ) { return "0" ; } return possibleBooleanString ; }
Checks whether a String is a Boolean value and replaces it with its Integer representation true - > 1 false - > 0
76
24
28,470
private static boolean isSeparatorToken ( final char possibleSeparatorChar ) { for ( final SeparatorToken token : SeparatorToken . values ( ) ) { if ( token . value == possibleSeparatorChar ) { return true ; } } return false ; }
Checks whether a given character is a known separator token or no
59
14
28,471
private static String validateOperator ( final String operator ) { if ( ! OPERATORS . contains ( operator ) && ! BOOLEAN_OPERATORS . contains ( operator ) ) { throw new CitrusRuntimeException ( "Unknown operator '" + operator + "'" ) ; } return operator ; }
Check if operator is known to this class .
64
9
28,472
public void runPackages ( List < String > packages ) { CitrusAppConfiguration citrusAppConfiguration = new CitrusAppConfiguration ( ) ; citrusAppConfiguration . setIncludes ( Optional . ofNullable ( includes ) . orElse ( configuration . getIncludes ( ) ) ) ; citrusAppConfiguration . setPackages ( packages ) ; citrusAppConfiguration . setConfigClass ( configuration . getConfigClass ( ) ) ; citrusAppConfiguration . addDefaultProperties ( configuration . getDefaultProperties ( ) ) ; citrusAppConfiguration . addDefaultProperties ( defaultProperties ) ; run ( citrusAppConfiguration ) ; }
Run Citrus application with given test package names .
126
10
28,473
public void runClasses ( List < TestClass > testClasses ) { CitrusAppConfiguration citrusAppConfiguration = new CitrusAppConfiguration ( ) ; citrusAppConfiguration . setTestClasses ( testClasses ) ; citrusAppConfiguration . setConfigClass ( configuration . getConfigClass ( ) ) ; citrusAppConfiguration . addDefaultProperties ( configuration . getDefaultProperties ( ) ) ; citrusAppConfiguration . addDefaultProperties ( defaultProperties ) ; run ( citrusAppConfiguration ) ; }
Run Citrus application with given test class names .
104
10
28,474
public boolean handleRequest ( MessageContext messageContext , Object endpoint ) throws Exception { logRequest ( "Received SOAP request" , messageContext , true ) ; return true ; }
Write request message to logger .
37
6
28,475
public boolean handleResponse ( MessageContext messageContext , Object endpoint ) throws Exception { logResponse ( "Sending SOAP response" , messageContext , false ) ; return true ; }
Write response message to logger .
37
6
28,476
public RestTemplate getRestTemplate ( ) { if ( restTemplate == null ) { restTemplate = new RestTemplate ( ) ; restTemplate . setRequestFactory ( getRequestFactory ( ) ) ; } restTemplate . setErrorHandler ( getErrorHandler ( ) ) ; if ( ! defaultAcceptHeader ) { for ( org . springframework . http . converter . HttpMessageConverter messageConverter : restTemplate . getMessageConverters ( ) ) { if ( messageConverter instanceof StringHttpMessageConverter ) { ( ( StringHttpMessageConverter ) messageConverter ) . setWriteAcceptCharset ( defaultAcceptHeader ) ; } } } return restTemplate ; }
Gets the restTemplate .
148
6
28,477
private String getNodeValue ( Node node ) { if ( node . getNodeType ( ) == Node . ELEMENT_NODE && node . getFirstChild ( ) != null ) { return node . getFirstChild ( ) . getNodeValue ( ) ; } else { return node . getNodeValue ( ) ; } }
Resolves an XML node s value
68
7
28,478
public static String getRandomNumber ( int numberLength , boolean paddingOn ) { if ( numberLength < 1 ) { throw new InvalidFunctionUsageException ( "numberLength must be greater than 0 - supplied " + numberLength ) ; } StringBuilder buffer = new StringBuilder ( ) ; for ( int i = 0 ; i < numberLength ; i ++ ) { buffer . append ( generator . nextInt ( 10 ) ) ; } return checkLeadingZeros ( buffer . toString ( ) , paddingOn ) ; }
Static number generator method .
107
5
28,479
public static String checkLeadingZeros ( String generated , boolean paddingOn ) { if ( paddingOn ) { return replaceLeadingZero ( generated ) ; } else { return removeLeadingZeros ( generated ) ; } }
Remove leading Zero numbers .
47
5
28,480
private static String removeLeadingZeros ( String generated ) { StringBuilder builder = new StringBuilder ( ) ; boolean leading = true ; for ( int i = 0 ; i < generated . length ( ) ; i ++ ) { if ( generated . charAt ( i ) == ' ' && leading ) { continue ; } else { leading = false ; builder . append ( generated . charAt ( i ) ) ; } } if ( builder . length ( ) == 0 ) { // very unlikely to happen, ensures that empty string is not returned builder . append ( ' ' ) ; } return builder . toString ( ) ; }
Removes leading zero numbers if present .
129
8
28,481
private static String replaceLeadingZero ( String generated ) { if ( generated . charAt ( 0 ) == ' ' ) { // find number > 0 as replacement to avoid leading zero numbers int replacement = 0 ; while ( replacement == 0 ) { replacement = generator . nextInt ( 10 ) ; } return replacement + generated . substring ( 1 ) ; } else { return generated ; } }
Replaces first leading zero number if present .
80
9
28,482
public void configure ( @ Observes ( precedence = CitrusExtensionConstants . REMOTE_CONFIG_PRECEDENCE ) BeforeSuite event ) { try { log . info ( "Producing Citrus remote configuration" ) ; configurationInstance . set ( CitrusConfiguration . from ( getRemoteConfigurationProperties ( ) ) ) ; } catch ( Exception e ) { log . error ( CitrusExtensionConstants . CITRUS_EXTENSION_ERROR , e ) ; throw e ; } }
Observes before suite event and tries to load Citrus remote extension properties .
108
15
28,483
private Properties getRemoteConfigurationProperties ( ) { ClassLoader ctcl = AccessController . doPrivileged ( new PrivilegedAction < ClassLoader > ( ) { public ClassLoader run ( ) { return Thread . currentThread ( ) . getContextClassLoader ( ) ; } } ) ; try { if ( log . isDebugEnabled ( ) ) { log . debug ( "Loading Citrus remote extension properties ..." ) ; } Properties props = new Properties ( ) ; InputStream inputStream = ctcl . getResourceAsStream ( CitrusExtensionConstants . CITRUS_REMOTE_PROPERTIES ) ; if ( inputStream != null ) { props . load ( inputStream ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Successfully loaded Citrus remote extension properties" ) ; } return props ; } catch ( IOException e ) { log . warn ( "Unable to load Citrus remote extension properties" ) ; return new Properties ( ) ; } }
Reads configuration properties from remote property file that has been added to the auxiliary archive .
212
17
28,484
protected Map < String , String > getWithoutLabels ( String labelExpression , TestContext context ) { Map < String , String > labels = new HashMap <> ( ) ; Set < String > values = StringUtils . commaDelimitedListToSet ( labelExpression ) ; for ( String item : values ) { if ( item . contains ( "!=" ) ) { labels . put ( context . replaceDynamicContentInString ( item . substring ( 0 , item . indexOf ( "!=" ) ) ) , context . replaceDynamicContentInString ( item . substring ( item . indexOf ( "!=" ) + 2 ) ) ) ; } else if ( item . startsWith ( "!" ) ) { labels . put ( context . replaceDynamicContentInString ( item . substring ( 1 ) ) , null ) ; } } return labels ; }
Reads without labels from expression string .
184
8
28,485
private Object handleInvocation ( ManagedBeanInvocation mbeanInvocation ) { Message response = endpointAdapter . handleMessage ( endpointConfiguration . getMessageConverter ( ) . convertInbound ( mbeanInvocation , endpointConfiguration , null ) ) ; ManagedBeanResult serviceResult = null ; if ( response != null && response . getPayload ( ) != null ) { if ( response . getPayload ( ) instanceof ManagedBeanResult ) { serviceResult = ( ManagedBeanResult ) response . getPayload ( ) ; } else if ( response . getPayload ( ) instanceof String ) { serviceResult = ( ManagedBeanResult ) endpointConfiguration . getMarshaller ( ) . unmarshal ( response . getPayload ( Source . class ) ) ; } } if ( serviceResult != null ) { return serviceResult . getResultObject ( endpointConfiguration . getApplicationContext ( ) ) ; } else { return null ; } }
Handle managed bean invocation by delegating to endpoint adapter . Response is converted to proper method return result .
205
20
28,486
private void traverseJsonData ( JSONObject jsonData , String jsonPath , TestContext context ) { for ( Iterator it = jsonData . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Map . Entry jsonEntry = ( Map . Entry ) it . next ( ) ; if ( jsonEntry . getValue ( ) instanceof JSONObject ) { traverseJsonData ( ( JSONObject ) jsonEntry . getValue ( ) , ( StringUtils . hasText ( jsonPath ) ? jsonPath + "." + jsonEntry . getKey ( ) : jsonEntry . getKey ( ) . toString ( ) ) , context ) ; } else if ( jsonEntry . getValue ( ) instanceof JSONArray ) { JSONArray jsonArray = ( JSONArray ) jsonEntry . getValue ( ) ; for ( int i = 0 ; i < jsonArray . size ( ) ; i ++ ) { if ( jsonArray . get ( i ) instanceof JSONObject ) { traverseJsonData ( ( JSONObject ) jsonArray . get ( i ) , String . format ( ( StringUtils . hasText ( jsonPath ) ? jsonPath + "." + jsonEntry . getKey ( ) : jsonEntry . getKey ( ) . toString ( ) ) + "[%s]" , i ) , context ) ; } else { jsonArray . set ( i , translate ( String . format ( ( StringUtils . hasText ( jsonPath ) ? jsonPath + "." + jsonEntry . getKey ( ) : jsonEntry . getKey ( ) . toString ( ) ) + "[%s]" , i ) , jsonArray . get ( i ) , context ) ) ; } } } else { jsonEntry . setValue ( translate ( ( StringUtils . hasText ( jsonPath ) ? jsonPath + "." + jsonEntry . getKey ( ) : jsonEntry . getKey ( ) . toString ( ) ) , jsonEntry . getValue ( ) != null ? jsonEntry . getValue ( ) : null , context ) ) ; } } }
Walks through the Json object structure and translates values based on element path if necessary .
437
18
28,487
private String getDigestHex ( String algorithm , String key ) { if ( algorithm . equals ( "md5" ) ) { return DigestUtils . md5Hex ( key ) ; } else if ( algorithm . equals ( "sha" ) ) { return DigestUtils . shaHex ( key ) ; } throw new CitrusRuntimeException ( "Unsupported digest algorithm: " + algorithm ) ; }
Generates digest hexadecimal string representation of a key with given algorithm .
88
16
28,488
private boolean simulateHttpStatusCode ( Message replyMessage ) throws IOException { if ( replyMessage == null || CollectionUtils . isEmpty ( replyMessage . getHeaders ( ) ) ) { return false ; } for ( Entry < String , Object > headerEntry : replyMessage . getHeaders ( ) . entrySet ( ) ) { if ( headerEntry . getKey ( ) . equalsIgnoreCase ( SoapMessageHeaders . HTTP_STATUS_CODE ) ) { WebServiceConnection connection = TransportContextHolder . getTransportContext ( ) . getConnection ( ) ; int statusCode = Integer . valueOf ( headerEntry . getValue ( ) . toString ( ) ) ; if ( connection instanceof HttpServletConnection ) { ( ( HttpServletConnection ) connection ) . setFault ( false ) ; ( ( HttpServletConnection ) connection ) . getHttpServletResponse ( ) . setStatus ( statusCode ) ; return true ; } else { log . warn ( "Unable to set custom Http status code on connection other than HttpServletConnection (" + connection . getClass ( ) . getName ( ) + ")" ) ; } } } return false ; }
If Http status code is set on reply message headers simulate Http error with status code . No SOAP response is sent back in this case .
256
30
28,489
private void addSoapBody ( SoapMessage response , Message replyMessage ) throws TransformerException { if ( ! ( replyMessage . getPayload ( ) instanceof String ) || StringUtils . hasText ( replyMessage . getPayload ( String . class ) ) ) { Source responseSource = getPayloadAsSource ( replyMessage . getPayload ( ) ) ; TransformerFactory transformerFactory = TransformerFactory . newInstance ( ) ; Transformer transformer = transformerFactory . newTransformer ( ) ; transformer . transform ( responseSource , response . getPayloadResult ( ) ) ; } }
Add message payload as SOAP body element to the SOAP response .
126
14
28,490
private void addSoapHeaders ( SoapMessage response , Message replyMessage ) throws TransformerException { for ( Entry < String , Object > headerEntry : replyMessage . getHeaders ( ) . entrySet ( ) ) { if ( MessageHeaderUtils . isSpringInternalHeader ( headerEntry . getKey ( ) ) || headerEntry . getKey ( ) . startsWith ( DEFAULT_JMS_HEADER_PREFIX ) ) { continue ; } if ( headerEntry . getKey ( ) . equalsIgnoreCase ( SoapMessageHeaders . SOAP_ACTION ) ) { response . setSoapAction ( headerEntry . getValue ( ) . toString ( ) ) ; } else if ( ! headerEntry . getKey ( ) . startsWith ( MessageHeaders . PREFIX ) ) { SoapHeaderElement headerElement ; if ( QNameUtils . validateQName ( headerEntry . getKey ( ) ) ) { QName qname = QNameUtils . parseQNameString ( headerEntry . getKey ( ) ) ; if ( StringUtils . hasText ( qname . getNamespaceURI ( ) ) ) { headerElement = response . getSoapHeader ( ) . addHeaderElement ( qname ) ; } else { headerElement = response . getSoapHeader ( ) . addHeaderElement ( getDefaultQName ( headerEntry . getKey ( ) ) ) ; } } else { throw new SoapHeaderException ( "Failed to add SOAP header '" + headerEntry . getKey ( ) + "', " + "because of invalid QName" ) ; } headerElement . setText ( headerEntry . getValue ( ) . toString ( ) ) ; } } for ( String headerData : replyMessage . getHeaderData ( ) ) { TransformerFactory transformerFactory = TransformerFactory . newInstance ( ) ; Transformer transformer = transformerFactory . newTransformer ( ) ; transformer . transform ( new StringSource ( headerData ) , response . getSoapHeader ( ) . getResult ( ) ) ; } }
Translates message headers to SOAP headers in response .
438
12
28,491
private QName getDefaultQName ( String localPart ) { if ( StringUtils . hasText ( defaultNamespaceUri ) ) { return new QName ( defaultNamespaceUri , localPart , defaultPrefix ) ; } else { throw new SoapHeaderException ( "Failed to add SOAP header '" + localPart + "', " + "because neither valid QName nor default namespace-uri is set!" ) ; } }
Get the default QName from local part .
95
9
28,492
protected static String getBaseKey ( ExtensionContext extensionContext ) { return extensionContext . getRequiredTestClass ( ) . getName ( ) + "." + extensionContext . getRequiredTestMethod ( ) . getName ( ) + "#" ; }
Gets base key for store .
51
7
28,493
public static Stream < DynamicTest > packageScan ( String ... packagesToScan ) { List < DynamicTest > tests = new ArrayList <> ( ) ; for ( String packageScan : packagesToScan ) { try { for ( String fileNamePattern : Citrus . getXmlTestFileNamePattern ( ) ) { Resource [ ] fileResources = new PathMatchingResourcePatternResolver ( ) . getResources ( packageScan . replace ( ' ' , File . separatorChar ) + fileNamePattern ) ; for ( Resource fileResource : fileResources ) { String filePath = fileResource . getFile ( ) . getParentFile ( ) . getCanonicalPath ( ) ; if ( packageScan . startsWith ( "file:" ) ) { filePath = "file:" + filePath ; } filePath = filePath . substring ( filePath . indexOf ( packageScan . replace ( ' ' , File . separatorChar ) ) ) ; String testName = fileResource . getFilename ( ) . substring ( 0 , fileResource . getFilename ( ) . length ( ) - ".xml" . length ( ) ) ; XmlTestLoader testLoader = new XmlTestLoader ( DynamicTest . class , testName , filePath , citrus . getApplicationContext ( ) ) ; tests . add ( DynamicTest . dynamicTest ( testName , ( ) -> citrus . run ( testLoader . load ( ) ) ) ) ; } } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Unable to locate file resources for test package '" + packageScan + "'" , e ) ; } } return tests . stream ( ) ; }
Creates stream of dynamic tests based on package scan . Scans package for all Xml test case files and creates dynamic test instance for it .
349
29
28,494
public static KubernetesMessage request ( KubernetesCommand < ? > command ) { KubernetesRequest request = new KubernetesRequest ( ) ; request . setCommand ( command . getName ( ) ) ; for ( Map . Entry < String , Object > entry : command . getParameters ( ) . entrySet ( ) ) { if ( entry . getKey ( ) . equals ( KubernetesMessageHeaders . NAME ) ) { request . setName ( entry . getValue ( ) . toString ( ) ) ; } if ( entry . getKey ( ) . equals ( KubernetesMessageHeaders . NAMESPACE ) ) { request . setNamespace ( entry . getValue ( ) . toString ( ) ) ; } if ( entry . getKey ( ) . equals ( KubernetesMessageHeaders . LABEL ) ) { request . setLabel ( entry . getValue ( ) . toString ( ) ) ; } } return new KubernetesMessage ( request ) ; }
Request generating instantiation .
219
5
28,495
public boolean isFunction ( final String variableExpression ) { if ( variableExpression == null || variableExpression . length ( ) == 0 ) { return false ; } for ( int i = 0 ; i < functionLibraries . size ( ) ; i ++ ) { FunctionLibrary lib = ( FunctionLibrary ) functionLibraries . get ( i ) ; if ( variableExpression . startsWith ( lib . getPrefix ( ) ) ) { return true ; } } return false ; }
Check if variable expression is a custom function . Expression has to start with one of the registered function library prefix .
101
22
28,496
public FunctionLibrary getLibraryForPrefix ( String functionPrefix ) { for ( int i = 0 ; i < functionLibraries . size ( ) ; i ++ ) { if ( ( ( FunctionLibrary ) functionLibraries . get ( i ) ) . getPrefix ( ) . equals ( functionPrefix ) ) { return ( FunctionLibrary ) functionLibraries . get ( i ) ; } } throw new NoSuchFunctionLibraryException ( "Can not find function library for prefix " + functionPrefix ) ; }
Get library for function prefix .
107
6
28,497
protected void configureMessageEndpoint ( ApplicationContext context ) { if ( context . containsBean ( MESSAGE_ENDPOINT_BEAN_NAME ) ) { WebServiceEndpoint messageEndpoint = context . getBean ( MESSAGE_ENDPOINT_BEAN_NAME , WebServiceEndpoint . class ) ; EndpointAdapter endpointAdapter = webServiceServer . getEndpointAdapter ( ) ; if ( endpointAdapter != null ) { messageEndpoint . setEndpointAdapter ( endpointAdapter ) ; } WebServiceEndpointConfiguration endpointConfiguration = new WebServiceEndpointConfiguration ( ) ; endpointConfiguration . setHandleMimeHeaders ( webServiceServer . isHandleMimeHeaders ( ) ) ; endpointConfiguration . setHandleAttributeHeaders ( webServiceServer . isHandleAttributeHeaders ( ) ) ; endpointConfiguration . setKeepSoapEnvelope ( webServiceServer . isKeepSoapEnvelope ( ) ) ; endpointConfiguration . setMessageConverter ( webServiceServer . getMessageConverter ( ) ) ; messageEndpoint . setEndpointConfiguration ( endpointConfiguration ) ; if ( StringUtils . hasText ( webServiceServer . getSoapHeaderNamespace ( ) ) ) { messageEndpoint . setDefaultNamespaceUri ( webServiceServer . getSoapHeaderNamespace ( ) ) ; } if ( StringUtils . hasText ( webServiceServer . getSoapHeaderPrefix ( ) ) ) { messageEndpoint . setDefaultPrefix ( webServiceServer . getSoapHeaderPrefix ( ) ) ; } } }
Post process endpoint .
337
4
28,498
private List < EndpointInterceptor > adaptInterceptors ( List < Object > interceptors ) { List < EndpointInterceptor > endpointInterceptors = new ArrayList < EndpointInterceptor > ( ) ; if ( interceptors != null ) { for ( Object interceptor : interceptors ) { if ( interceptor instanceof EndpointInterceptor ) { endpointInterceptors . add ( ( EndpointInterceptor ) interceptor ) ; } } } return endpointInterceptors ; }
Adapts object list to endpoint interceptors .
102
9
28,499
public ZipMessage addEntry ( Resource resource ) { try { addEntry ( new Entry ( resource . getFile ( ) ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read zip entry content from given resource" , e ) ; } return this ; }
Adds new zip archive entry . Resource can be a file or directory . In case of directory all files will be automatically added to the zip archive . Directory structures are retained throughout this process .
63
37