idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
28,100
private String getStackTraceHtml ( Throwable cause ) { StringBuilder stackTraceBuilder = new StringBuilder ( ) ; stackTraceBuilder . append ( cause . getClass ( ) . getName ( ) ) . append ( ": " ) . append ( cause . getMessage ( ) ) . append ( "\n " ) ; for ( int i = 0 ; i < cause . getStackTrace ( ) . length ; i ++ ) { stackTraceBuilder . append ( "\n\t at " ) ; stackTraceBuilder . append ( cause . getStackTrace ( ) [ i ] ) ; } return "<tr><td colspan=\"2\">" + "<div class=\"error-detail\"><pre>" + stackTraceBuilder . toString ( ) + "</pre>" + getCodeSnippetHtml ( cause ) + "</div></td></tr>" ; }
Construct HTML code snippet for stack trace information .
191
9
28,101
protected void validateNamespaces ( Map < String , String > expectedNamespaces , Message receivedMessage ) { if ( CollectionUtils . isEmpty ( expectedNamespaces ) ) { return ; } if ( receivedMessage . getPayload ( ) == null || ! StringUtils . hasText ( receivedMessage . getPayload ( String . class ) ) ) { throw new ValidationException ( "Unable to validate message namespaces - receive message payload was empty" ) ; } log . debug ( "Start XML namespace validation" ) ; Document received = XMLUtils . parseMessagePayload ( receivedMessage . getPayload ( String . class ) ) ; Map < String , String > foundNamespaces = XMLUtils . lookupNamespaces ( receivedMessage . getPayload ( String . class ) ) ; if ( foundNamespaces . size ( ) != expectedNamespaces . size ( ) ) { throw new ValidationException ( "Number of namespace declarations not equal for node " + XMLUtils . getNodesPathName ( received . getFirstChild ( ) ) + " found " + foundNamespaces . size ( ) + " expected " + expectedNamespaces . size ( ) ) ; } for ( Entry < String , String > entry : expectedNamespaces . entrySet ( ) ) { String namespace = entry . getKey ( ) ; String url = entry . getValue ( ) ; if ( foundNamespaces . containsKey ( namespace ) ) { if ( ! foundNamespaces . get ( namespace ) . equals ( url ) ) { throw new ValidationException ( "Namespace '" + namespace + "' values not equal: found '" + foundNamespaces . get ( namespace ) + "' expected '" + url + "' in reference node " + XMLUtils . getNodesPathName ( received . getFirstChild ( ) ) ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Validating namespace " + namespace + " value as expected " + url + " - value OK" ) ; } } } else { throw new ValidationException ( "Missing namespace " + namespace + "(" + url + ") in node " + XMLUtils . getNodesPathName ( received . getFirstChild ( ) ) ) ; } } log . info ( "XML namespace validation successful: All values OK" ) ; }
Validate namespaces in message . The method compares namespace declarations in the root element of the received message to expected namespaces . Prefixes are important too so differing namespace prefixes will fail the validation .
493
40
28,102
protected void validateMessageContent ( Message receivedMessage , Message controlMessage , XmlMessageValidationContext validationContext , TestContext context ) { if ( controlMessage == null || controlMessage . getPayload ( ) == null ) { log . debug ( "Skip message payload validation as no control message was defined" ) ; return ; } if ( ! ( controlMessage . getPayload ( ) instanceof String ) ) { throw new IllegalArgumentException ( "DomXmlMessageValidator does only support message payload of type String, " + "but was " + controlMessage . getPayload ( ) . getClass ( ) ) ; } String controlMessagePayload = controlMessage . getPayload ( String . class ) ; if ( receivedMessage . getPayload ( ) == null || ! StringUtils . hasText ( receivedMessage . getPayload ( String . class ) ) ) { Assert . isTrue ( ! StringUtils . hasText ( controlMessagePayload ) , "Unable to validate message payload - received message payload was empty, control message payload is not" ) ; return ; } else if ( ! StringUtils . hasText ( controlMessagePayload ) ) { return ; } log . debug ( "Start XML tree validation ..." ) ; Document received = XMLUtils . parseMessagePayload ( receivedMessage . getPayload ( String . class ) ) ; Document source = XMLUtils . parseMessagePayload ( controlMessagePayload ) ; XMLUtils . stripWhitespaceNodes ( received ) ; XMLUtils . stripWhitespaceNodes ( source ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Received message:\n" + XMLUtils . serialize ( received ) ) ; log . debug ( "Control message:\n" + XMLUtils . serialize ( source ) ) ; } validateXmlTree ( received , source , validationContext , namespaceContextBuilder . buildContext ( receivedMessage , validationContext . getNamespaces ( ) ) , context ) ; }
Validate message payloads by comparing to a control message .
427
12
28,103
private void validateXmlHeaderFragment ( String receivedHeaderData , String controlHeaderData , XmlMessageValidationContext validationContext , TestContext context ) { log . debug ( "Start XML header data validation ..." ) ; Document received = XMLUtils . parseMessagePayload ( receivedHeaderData ) ; Document source = XMLUtils . parseMessagePayload ( controlHeaderData ) ; XMLUtils . stripWhitespaceNodes ( received ) ; XMLUtils . stripWhitespaceNodes ( source ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Received header data:\n" + XMLUtils . serialize ( received ) ) ; log . debug ( "Control header data:\n" + XMLUtils . serialize ( source ) ) ; } validateXmlTree ( received , source , validationContext , namespaceContextBuilder . buildContext ( new DefaultMessage ( receivedHeaderData ) , validationContext . getNamespaces ( ) ) , context ) ; }
Validates XML header fragment data .
209
7
28,104
private void validateXmlTree ( Node received , Node source , XmlMessageValidationContext validationContext , NamespaceContext namespaceContext , TestContext context ) { switch ( received . getNodeType ( ) ) { case Node . DOCUMENT_TYPE_NODE : doDocumentTypeDefinition ( received , source , validationContext , namespaceContext , context ) ; break ; case Node . DOCUMENT_NODE : validateXmlTree ( received . getFirstChild ( ) , source . getFirstChild ( ) , validationContext , namespaceContext , context ) ; break ; case Node . ELEMENT_NODE : doElement ( received , source , validationContext , namespaceContext , context ) ; break ; case Node . ATTRIBUTE_NODE : throw new IllegalStateException ( ) ; case Node . COMMENT_NODE : validateXmlTree ( received . getNextSibling ( ) , source , validationContext , namespaceContext , context ) ; break ; case Node . PROCESSING_INSTRUCTION_NODE : doPI ( received ) ; break ; } }
Walk the XML tree and validate all nodes .
224
9
28,105
private void doDocumentTypeDefinition ( Node received , Node source , XmlMessageValidationContext validationContext , NamespaceContext namespaceContext , TestContext context ) { Assert . isTrue ( source instanceof DocumentType , "Missing document type definition in expected xml fragment" ) ; DocumentType receivedDTD = ( DocumentType ) received ; DocumentType sourceDTD = ( DocumentType ) source ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Validating document type definition: " + receivedDTD . getPublicId ( ) + " (" + receivedDTD . getSystemId ( ) + ")" ) ; } if ( ! StringUtils . hasText ( sourceDTD . getPublicId ( ) ) ) { Assert . isNull ( receivedDTD . getPublicId ( ) , ValidationUtils . buildValueMismatchErrorMessage ( "Document type public id not equal" , sourceDTD . getPublicId ( ) , receivedDTD . getPublicId ( ) ) ) ; } else if ( sourceDTD . getPublicId ( ) . trim ( ) . equals ( Citrus . IGNORE_PLACEHOLDER ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Document type public id: '" + receivedDTD . getPublicId ( ) + "' is ignored by placeholder '" + Citrus . IGNORE_PLACEHOLDER + "'" ) ; } } else { Assert . isTrue ( StringUtils . hasText ( receivedDTD . getPublicId ( ) ) && receivedDTD . getPublicId ( ) . equals ( sourceDTD . getPublicId ( ) ) , ValidationUtils . buildValueMismatchErrorMessage ( "Document type public id not equal" , sourceDTD . getPublicId ( ) , receivedDTD . getPublicId ( ) ) ) ; } if ( ! StringUtils . hasText ( sourceDTD . getSystemId ( ) ) ) { Assert . isNull ( receivedDTD . getSystemId ( ) , ValidationUtils . buildValueMismatchErrorMessage ( "Document type system id not equal" , sourceDTD . getSystemId ( ) , receivedDTD . getSystemId ( ) ) ) ; } else if ( sourceDTD . getSystemId ( ) . trim ( ) . equals ( Citrus . IGNORE_PLACEHOLDER ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Document type system id: '" + receivedDTD . getSystemId ( ) + "' is ignored by placeholder '" + Citrus . IGNORE_PLACEHOLDER + "'" ) ; } } else { Assert . isTrue ( StringUtils . hasText ( receivedDTD . getSystemId ( ) ) && receivedDTD . getSystemId ( ) . equals ( sourceDTD . getSystemId ( ) ) , ValidationUtils . buildValueMismatchErrorMessage ( "Document type system id not equal" , sourceDTD . getSystemId ( ) , receivedDTD . getSystemId ( ) ) ) ; } validateXmlTree ( received . getNextSibling ( ) , source . getNextSibling ( ) , validationContext , namespaceContext , context ) ; }
Handle document type definition with validation of publicId and systemId .
706
13
28,106
private void doElement ( Node received , Node source , XmlMessageValidationContext validationContext , NamespaceContext namespaceContext , TestContext context ) { doElementNameValidation ( received , source ) ; doElementNamespaceValidation ( received , source ) ; //check if element is ignored either by xpath or by ignore placeholder in source message if ( XmlValidationUtils . isElementIgnored ( source , received , validationContext . getIgnoreExpressions ( ) , namespaceContext ) ) { return ; } //work on attributes if ( log . isDebugEnabled ( ) ) { log . debug ( "Validating attributes for element: " + received . getLocalName ( ) ) ; } NamedNodeMap receivedAttr = received . getAttributes ( ) ; NamedNodeMap sourceAttr = source . getAttributes ( ) ; Assert . isTrue ( countAttributes ( receivedAttr ) == countAttributes ( sourceAttr ) , ValidationUtils . buildValueMismatchErrorMessage ( "Number of attributes not equal for element '" + received . getLocalName ( ) + "'" , countAttributes ( sourceAttr ) , countAttributes ( receivedAttr ) ) ) ; for ( int i = 0 ; i < receivedAttr . getLength ( ) ; i ++ ) { doAttribute ( received , receivedAttr . item ( i ) , source , validationContext , namespaceContext , context ) ; } //check if validation matcher on element is specified if ( isValidationMatcherExpression ( source ) ) { ValidationMatcherUtils . resolveValidationMatcher ( source . getNodeName ( ) , received . getFirstChild ( ) . getNodeValue ( ) . trim ( ) , source . getFirstChild ( ) . getNodeValue ( ) . trim ( ) , context ) ; return ; } doText ( ( Element ) received , ( Element ) source ) ; //work on child nodes List < Element > receivedChildElements = DomUtils . getChildElements ( ( Element ) received ) ; List < Element > sourceChildElements = DomUtils . getChildElements ( ( Element ) source ) ; Assert . isTrue ( receivedChildElements . size ( ) == sourceChildElements . size ( ) , ValidationUtils . buildValueMismatchErrorMessage ( "Number of child elements not equal for element '" + received . getLocalName ( ) + "'" , sourceChildElements . size ( ) , receivedChildElements . size ( ) ) ) ; for ( int i = 0 ; i < receivedChildElements . size ( ) ; i ++ ) { this . validateXmlTree ( receivedChildElements . get ( i ) , sourceChildElements . get ( i ) , validationContext , namespaceContext , context ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Validation successful for element: " + received . getLocalName ( ) + " (" + received . getNamespaceURI ( ) + ")" ) ; } }
Handle element node .
640
4
28,107
private void doText ( Element received , Element source ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Validating node value for element: " + received . getLocalName ( ) ) ; } String receivedText = DomUtils . getTextValue ( received ) ; String sourceText = DomUtils . getTextValue ( source ) ; if ( receivedText != null ) { Assert . isTrue ( sourceText != null , ValidationUtils . buildValueMismatchErrorMessage ( "Node value not equal for element '" + received . getLocalName ( ) + "'" , null , receivedText . trim ( ) ) ) ; Assert . isTrue ( receivedText . trim ( ) . equals ( sourceText . trim ( ) ) , ValidationUtils . buildValueMismatchErrorMessage ( "Node value not equal for element '" + received . getLocalName ( ) + "'" , sourceText . trim ( ) , receivedText . trim ( ) ) ) ; } else { Assert . isTrue ( sourceText == null , ValidationUtils . buildValueMismatchErrorMessage ( "Node value not equal for element '" + received . getLocalName ( ) + "'" , sourceText . trim ( ) , null ) ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Node value '" + receivedText . trim ( ) + "': OK" ) ; } }
Handle text node during validation .
310
6
28,108
private void doAttribute ( Node receivedElement , Node receivedAttribute , Node sourceElement , XmlMessageValidationContext validationContext , NamespaceContext namespaceContext , TestContext context ) { if ( receivedAttribute . getNodeName ( ) . startsWith ( XMLConstants . XMLNS_ATTRIBUTE ) ) { return ; } String receivedAttributeName = receivedAttribute . getLocalName ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Validating attribute: " + receivedAttributeName + " (" + receivedAttribute . getNamespaceURI ( ) + ")" ) ; } NamedNodeMap sourceAttributes = sourceElement . getAttributes ( ) ; Node sourceAttribute = sourceAttributes . getNamedItemNS ( receivedAttribute . getNamespaceURI ( ) , receivedAttributeName ) ; Assert . isTrue ( sourceAttribute != null , "Attribute validation failed for element '" + receivedElement . getLocalName ( ) + "', unknown attribute " + receivedAttributeName + " (" + receivedAttribute . getNamespaceURI ( ) + ")" ) ; if ( XmlValidationUtils . isAttributeIgnored ( receivedElement , receivedAttribute , sourceAttribute , validationContext . getIgnoreExpressions ( ) , namespaceContext ) ) { return ; } String receivedValue = receivedAttribute . getNodeValue ( ) ; String sourceValue = sourceAttribute . getNodeValue ( ) ; if ( isValidationMatcherExpression ( sourceAttribute ) ) { ValidationMatcherUtils . resolveValidationMatcher ( sourceAttribute . getNodeName ( ) , receivedAttribute . getNodeValue ( ) . trim ( ) , sourceAttribute . getNodeValue ( ) . trim ( ) , context ) ; } else if ( receivedValue . contains ( ":" ) && sourceValue . contains ( ":" ) ) { doNamespaceQualifiedAttributeValidation ( receivedElement , receivedAttribute , sourceElement , sourceAttribute ) ; } else { Assert . isTrue ( receivedValue . equals ( sourceValue ) , ValidationUtils . buildValueMismatchErrorMessage ( "Values not equal for attribute '" + receivedAttributeName + "'" , sourceValue , receivedValue ) ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Attribute '" + receivedAttributeName + "'='" + receivedValue + "': OK" ) ; } }
Handle attribute node during validation .
498
6
28,109
private void doNamespaceQualifiedAttributeValidation ( Node receivedElement , Node receivedAttribute , Node sourceElement , Node sourceAttribute ) { String receivedValue = receivedAttribute . getNodeValue ( ) ; String sourceValue = sourceAttribute . getNodeValue ( ) ; if ( receivedValue . contains ( ":" ) && sourceValue . contains ( ":" ) ) { // value has namespace prefix set, do special QName validation String receivedPrefix = receivedValue . substring ( 0 , receivedValue . indexOf ( ' ' ) ) ; String sourcePrefix = sourceValue . substring ( 0 , sourceValue . indexOf ( ' ' ) ) ; Map < String , String > receivedNamespaces = XMLUtils . lookupNamespaces ( receivedAttribute . getOwnerDocument ( ) ) ; receivedNamespaces . putAll ( XMLUtils . lookupNamespaces ( receivedElement ) ) ; if ( receivedNamespaces . containsKey ( receivedPrefix ) ) { Map < String , String > sourceNamespaces = XMLUtils . lookupNamespaces ( sourceAttribute . getOwnerDocument ( ) ) ; sourceNamespaces . putAll ( XMLUtils . lookupNamespaces ( sourceElement ) ) ; if ( sourceNamespaces . containsKey ( sourcePrefix ) ) { Assert . isTrue ( sourceNamespaces . get ( sourcePrefix ) . equals ( receivedNamespaces . get ( receivedPrefix ) ) , ValidationUtils . buildValueMismatchErrorMessage ( "Values not equal for attribute value namespace '" + receivedValue + "'" , sourceNamespaces . get ( sourcePrefix ) , receivedNamespaces . get ( receivedPrefix ) ) ) ; // remove namespace prefixes as they must not form equality receivedValue = receivedValue . substring ( ( receivedPrefix + ":" ) . length ( ) ) ; sourceValue = sourceValue . substring ( ( sourcePrefix + ":" ) . length ( ) ) ; } else { throw new ValidationException ( "Received attribute value '" + receivedAttribute . getLocalName ( ) + "' describes namespace qualified attribute value," + " control value '" + sourceValue + "' does not" ) ; } } } Assert . isTrue ( receivedValue . equals ( sourceValue ) , ValidationUtils . buildValueMismatchErrorMessage ( "Values not equal for attribute '" + receivedAttribute . getLocalName ( ) + "'" , sourceValue , receivedValue ) ) ; }
Perform validation on namespace qualified attribute values if present . This includes the validation of namespace presence and equality .
513
21
28,110
private void doPI ( Node received ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Ignored processing instruction (" + received . getLocalName ( ) + "=" + received . getNodeValue ( ) + ")" ) ; } }
Handle processing instruction during validation .
56
6
28,111
private boolean isValidationMatcherExpression ( Node node ) { switch ( node . getNodeType ( ) ) { case Node . ELEMENT_NODE : return node . getFirstChild ( ) != null && StringUtils . hasText ( node . getFirstChild ( ) . getNodeValue ( ) ) && ValidationMatcherUtils . isValidationMatcherExpression ( node . getFirstChild ( ) . getNodeValue ( ) . trim ( ) ) ; case Node . ATTRIBUTE_NODE : return StringUtils . hasText ( node . getNodeValue ( ) ) && ValidationMatcherUtils . isValidationMatcherExpression ( node . getNodeValue ( ) . trim ( ) ) ; default : return false ; //validation matchers makes no sense } }
Checks whether the given node contains a validation matcher
172
11
28,112
public void addSchemaRepository ( XsdSchemaRepository schemaRepository ) { if ( schemaRepositories == null ) { schemaRepositories = new ArrayList < XsdSchemaRepository > ( ) ; } schemaRepositories . add ( schemaRepository ) ; }
Set the schema repository holding all known schema definition files .
59
11
28,113
public SchemaRepositoryModelBuilder addSchema ( String id , String location ) { SchemaModel schema = new SchemaModel ( ) ; schema . setId ( id ) ; schema . setLocation ( location ) ; if ( model . getSchemas ( ) == null ) { model . setSchemas ( new SchemaRepositoryModel . Schemas ( ) ) ; } model . getSchemas ( ) . getSchemas ( ) . add ( schema ) ; return this ; }
Adds new schema by id and location .
103
8
28,114
public SchemaRepositoryModelBuilder addSchema ( SchemaModel schema ) { if ( model . getSchemas ( ) == null ) { model . setSchemas ( new SchemaRepositoryModel . Schemas ( ) ) ; } model . getSchemas ( ) . getSchemas ( ) . add ( schema ) ; return this ; }
Adds new schema by instance .
74
6
28,115
public SchemaRepositoryModelBuilder addSchemaReference ( String schemaId ) { SchemaRepositoryModel . Schemas . Reference schemaRef = new SchemaRepositoryModel . Schemas . Reference ( ) ; schemaRef . setSchema ( schemaId ) ; if ( model . getSchemas ( ) == null ) { model . setSchemas ( new SchemaRepositoryModel . Schemas ( ) ) ; } model . getSchemas ( ) . getReferences ( ) . add ( schemaRef ) ; return this ; }
Add new schema reference by id
114
6
28,116
public void execute ( StepTemplate stepTemplate , Object [ ] args ) { Template steps = new Template ( ) ; steps . setActions ( stepTemplate . getActions ( ) ) ; steps . setActor ( stepTemplate . getActor ( ) ) ; TemplateBuilder templateBuilder = new TemplateBuilder ( steps ) . name ( stepTemplate . getName ( ) ) . globalContext ( stepTemplate . isGlobalContext ( ) ) ; if ( stepTemplate . getParameterNames ( ) . size ( ) != args . length ) { throw new CitrusRuntimeException ( String . format ( "Step argument mismatch for template '%s', expected %s arguments but found %s" , stepTemplate . getName ( ) , stepTemplate . getParameterNames ( ) . size ( ) , args . length ) ) ; } for ( int i = 0 ; i < args . length ; i ++ ) { templateBuilder . parameter ( stepTemplate . getParameterNames ( ) . get ( i ) , args [ i ] . toString ( ) ) ; } if ( designer != null ) { designer . action ( templateBuilder ) ; } if ( runner != null ) { runner . run ( templateBuilder . build ( ) ) ; } }
Run template within designer .
253
5
28,117
protected Map < String , Object > createMessageHeaders ( MimeMailMessage msg ) throws MessagingException , IOException { Map < String , Object > headers = new HashMap <> ( ) ; headers . put ( CitrusMailMessageHeaders . MAIL_MESSAGE_ID , msg . getMimeMessage ( ) . getMessageID ( ) ) ; headers . put ( CitrusMailMessageHeaders . MAIL_FROM , StringUtils . arrayToCommaDelimitedString ( msg . getMimeMessage ( ) . getFrom ( ) ) ) ; headers . put ( CitrusMailMessageHeaders . MAIL_TO , StringUtils . arrayToCommaDelimitedString ( ( msg . getMimeMessage ( ) . getRecipients ( javax . mail . Message . RecipientType . TO ) ) ) ) ; headers . put ( CitrusMailMessageHeaders . MAIL_CC , StringUtils . arrayToCommaDelimitedString ( ( msg . getMimeMessage ( ) . getRecipients ( javax . mail . Message . RecipientType . CC ) ) ) ) ; headers . put ( CitrusMailMessageHeaders . MAIL_BCC , StringUtils . arrayToCommaDelimitedString ( ( msg . getMimeMessage ( ) . getRecipients ( javax . mail . Message . RecipientType . BCC ) ) ) ) ; headers . put ( CitrusMailMessageHeaders . MAIL_REPLY_TO , StringUtils . arrayToCommaDelimitedString ( ( msg . getMimeMessage ( ) . getReplyTo ( ) ) ) ) ; headers . put ( CitrusMailMessageHeaders . MAIL_DATE , msg . getMimeMessage ( ) . getSentDate ( ) != null ? dateFormat . format ( msg . getMimeMessage ( ) . getSentDate ( ) ) : null ) ; headers . put ( CitrusMailMessageHeaders . MAIL_SUBJECT , msg . getMimeMessage ( ) . getSubject ( ) ) ; headers . put ( CitrusMailMessageHeaders . MAIL_CONTENT_TYPE , parseContentType ( msg . getMimeMessage ( ) . getContentType ( ) ) ) ; return headers ; }
Reads basic message information such as sender recipients and mail subject to message headers .
499
16
28,118
protected BodyPart handlePart ( MimePart part ) throws IOException , MessagingException { String contentType = parseContentType ( part . getContentType ( ) ) ; if ( part . isMimeType ( "multipart/*" ) ) { return handleMultiPart ( ( Multipart ) part . getContent ( ) ) ; } else if ( part . isMimeType ( "text/*" ) ) { return handleTextPart ( part , contentType ) ; } else if ( part . isMimeType ( "image/*" ) ) { return handleImageBinaryPart ( part , contentType ) ; } else if ( part . isMimeType ( "application/*" ) ) { return handleApplicationContentPart ( part , contentType ) ; } else { return handleBinaryPart ( part , contentType ) ; } }
Process message part . Can be a text binary or multipart instance .
179
14
28,119
private BodyPart handleMultiPart ( Multipart body ) throws IOException , MessagingException { BodyPart bodyPart = null ; for ( int i = 0 ; i < body . getCount ( ) ; i ++ ) { MimePart entity = ( MimePart ) body . getBodyPart ( i ) ; if ( bodyPart == null ) { bodyPart = handlePart ( entity ) ; } else { BodyPart attachment = handlePart ( entity ) ; bodyPart . addPart ( new AttachmentPart ( attachment . getContent ( ) , parseContentType ( attachment . getContentType ( ) ) , entity . getFileName ( ) ) ) ; } } return bodyPart ; }
Construct multipart body with first part being the body content and further parts being the attachments .
144
18
28,120
protected BodyPart handleApplicationContentPart ( MimePart applicationData , String contentType ) throws IOException , MessagingException { if ( applicationData . isMimeType ( "application/pdf" ) ) { return handleImageBinaryPart ( applicationData , contentType ) ; } else if ( applicationData . isMimeType ( "application/rtf" ) ) { return handleImageBinaryPart ( applicationData , contentType ) ; } else if ( applicationData . isMimeType ( "application/java" ) ) { return handleTextPart ( applicationData , contentType ) ; } else if ( applicationData . isMimeType ( "application/x-javascript" ) ) { return handleTextPart ( applicationData , contentType ) ; } else if ( applicationData . isMimeType ( "application/xhtml+xml" ) ) { return handleTextPart ( applicationData , contentType ) ; } else if ( applicationData . isMimeType ( "application/json" ) ) { return handleTextPart ( applicationData , contentType ) ; } else if ( applicationData . isMimeType ( "application/postscript" ) ) { return handleTextPart ( applicationData , contentType ) ; } else { return handleBinaryPart ( applicationData , contentType ) ; } }
Construct body part form special application data . Based on known application content types delegate to text image or binary body construction .
277
23
28,121
protected BodyPart handleImageBinaryPart ( MimePart image , String contentType ) throws IOException , MessagingException { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; FileCopyUtils . copy ( image . getInputStream ( ) , bos ) ; String base64 = Base64 . encodeBase64String ( bos . toByteArray ( ) ) ; return new BodyPart ( base64 , contentType ) ; }
Construct base64 body part from image data .
92
9
28,122
protected BodyPart handleBinaryPart ( MimePart mediaPart , String contentType ) throws IOException , MessagingException { String contentId = mediaPart . getContentID ( ) != null ? "(" + mediaPart . getContentID ( ) + ")" : "" ; return new BodyPart ( mediaPart . getFileName ( ) + contentId , contentType ) ; }
Construct simple body part from binary data just adding file name as content .
80
14
28,123
protected BodyPart handleTextPart ( MimePart textPart , String contentType ) throws IOException , MessagingException { String content ; if ( textPart . getContent ( ) instanceof String ) { content = ( String ) textPart . getContent ( ) ; } else if ( textPart . getContent ( ) instanceof InputStream ) { content = FileUtils . readToString ( ( InputStream ) textPart . getContent ( ) , Charset . forName ( parseCharsetFromContentType ( contentType ) ) ) ; } else { throw new CitrusRuntimeException ( "Cannot handle text content of type: " + textPart . getContent ( ) . getClass ( ) . toString ( ) ) ; } return new BodyPart ( stripMailBodyEnding ( content ) , contentType ) ; }
Construct simple binary body part with base64 data .
175
10
28,124
private String stripMailBodyEnding ( String textBody ) throws IOException { BufferedReader reader = null ; StringBuilder body = new StringBuilder ( ) ; try { reader = new BufferedReader ( new StringReader ( textBody ) ) ; String line = reader . readLine ( ) ; while ( line != null && ! line . equals ( "." ) ) { body . append ( line ) ; body . append ( System . getProperty ( "line.separator" ) ) ; line = reader . readLine ( ) ; } } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException e ) { log . warn ( "Failed to close reader" , e ) ; } } } return body . toString ( ) . trim ( ) ; }
Removes SMTP mail body ending which is defined by single . character in separate line marking the mail body end of file .
169
25
28,125
static String parseContentType ( String contentType ) throws IOException { if ( contentType . indexOf ( System . getProperty ( "line.separator" ) ) > 0 ) { BufferedReader reader = new BufferedReader ( new StringReader ( contentType ) ) ; try { String plainContentType = reader . readLine ( ) ; if ( plainContentType != null && plainContentType . trim ( ) . endsWith ( ";" ) ) { plainContentType = plainContentType . trim ( ) . substring ( 0 , plainContentType . length ( ) - 1 ) ; } return plainContentType ; } finally { try { reader . close ( ) ; } catch ( IOException e ) { log . warn ( "Failed to close reader" , e ) ; } } } return contentType ; }
When content type has multiple lines this method just returns plain content type information in first line . This is the case when multipart mixed content type has boundary information in next line .
172
35
28,126
public SoapServerRequestActionBuilder receive ( ) { SoapServerRequestActionBuilder soapServerRequestActionBuilder = new SoapServerRequestActionBuilder ( action , soapServer ) . withApplicationContext ( applicationContext ) ; return soapServerRequestActionBuilder ; }
Generic request builder for receiving SOAP messages on server .
53
11
28,127
public SoapServerResponseActionBuilder send ( ) { SoapServerResponseActionBuilder soapServerResponseActionBuilder = new SoapServerResponseActionBuilder ( action , soapServer ) . withApplicationContext ( applicationContext ) ; return soapServerResponseActionBuilder ; }
Generic response builder for sending SOAP response messages to client .
53
12
28,128
public SoapServerFaultResponseActionBuilder sendFault ( ) { SoapServerFaultResponseActionBuilder soapServerResponseActionBuilder = new SoapServerFaultResponseActionBuilder ( action , soapServer ) . withApplicationContext ( applicationContext ) ; return soapServerResponseActionBuilder ; }
Generic response builder for sending SOAP fault messages to client .
61
12
28,129
public static Object evaluate ( ReadContext readerContext , String jsonPathExpression ) { String expression = jsonPathExpression ; String jsonPathFunction = null ; for ( String name : JsonPathFunctions . getSupportedFunctions ( ) ) { if ( expression . endsWith ( String . format ( ".%s()" , name ) ) ) { jsonPathFunction = name ; expression = expression . substring ( 0 , expression . length ( ) - String . format ( ".%s()" , name ) . length ( ) ) ; } } Object jsonPathResult = null ; PathNotFoundException pathNotFoundException = null ; try { if ( JsonPath . isPathDefinite ( expression ) ) { jsonPathResult = readerContext . read ( expression ) ; } else { JSONArray values = readerContext . read ( expression ) ; if ( values . size ( ) == 1 ) { jsonPathResult = values . get ( 0 ) ; } else { jsonPathResult = values ; } } } catch ( PathNotFoundException e ) { pathNotFoundException = e ; } if ( StringUtils . hasText ( jsonPathFunction ) ) { jsonPathResult = JsonPathFunctions . evaluate ( jsonPathResult , jsonPathFunction ) ; } if ( jsonPathResult == null && pathNotFoundException != null ) { throw new CitrusRuntimeException ( String . format ( "Failed to evaluate JSON path expression: %s" , jsonPathExpression ) , pathNotFoundException ) ; } return jsonPathResult ; }
Evaluate JsonPath expression using given read context and return result as object .
323
17
28,130
public static String evaluateAsString ( String payload , String jsonPathExpression ) { try { JSONParser parser = new JSONParser ( JSONParser . MODE_JSON_SIMPLE ) ; Object receivedJson = parser . parse ( payload ) ; ReadContext readerContext = JsonPath . parse ( receivedJson ) ; return evaluateAsString ( readerContext , jsonPathExpression ) ; } catch ( ParseException e ) { throw new CitrusRuntimeException ( "Failed to parse JSON text" , e ) ; } }
Evaluate JsonPath expression on given payload string and return result as string .
111
17
28,131
public static String evaluateAsString ( ReadContext readerContext , String jsonPathExpression ) { Object jsonPathResult = evaluate ( readerContext , jsonPathExpression ) ; if ( jsonPathResult instanceof JSONArray ) { return ( ( JSONArray ) jsonPathResult ) . toJSONString ( ) ; } else if ( jsonPathResult instanceof JSONObject ) { return ( ( JSONObject ) jsonPathResult ) . toJSONString ( ) ; } else { return Optional . ofNullable ( jsonPathResult ) . map ( Object :: toString ) . orElse ( "null" ) ; } }
Evaluate JsonPath expression using given read context and return result as string .
126
17
28,132
public static void stripWhitespaceNodes ( Node element ) { Node node , child ; for ( child = element . getFirstChild ( ) ; child != null ; child = node ) { node = child . getNextSibling ( ) ; stripWhitespaceNodes ( child ) ; } if ( element . getNodeType ( ) == Node . TEXT_NODE && element . getNodeValue ( ) . trim ( ) . length ( ) == 0 ) { element . getParentNode ( ) . removeChild ( element ) ; } }
Removes text nodes that are only containing whitespace characters inside a DOM tree .
114
16
28,133
private static void buildNodeName ( Node node , StringBuffer buffer ) { if ( node . getParentNode ( ) == null ) { return ; } buildNodeName ( node . getParentNode ( ) , buffer ) ; if ( node . getParentNode ( ) != null && node . getParentNode ( ) . getParentNode ( ) != null ) { buffer . append ( "." ) ; } buffer . append ( node . getLocalName ( ) ) ; }
Builds the node path expression for a node in the DOM tree .
98
14
28,134
public static String serialize ( Document doc ) { LSSerializer serializer = configurer . createLSSerializer ( ) ; LSOutput output = configurer . createLSOutput ( ) ; String charset = getTargetCharset ( doc ) . displayName ( ) ; output . setEncoding ( charset ) ; StringWriter writer = new StringWriter ( ) ; output . setCharacterStream ( writer ) ; serializer . write ( doc , output ) ; return writer . toString ( ) ; }
Serializes a DOM document
107
5
28,135
public static String prettyPrint ( String xml ) { LSParser parser = configurer . createLSParser ( ) ; configurer . setParserConfigParameter ( parser , VALIDATE_IF_SCHEMA , false ) ; LSInput input = configurer . createLSInput ( ) ; try { Charset charset = getTargetCharset ( xml ) ; input . setByteStream ( new ByteArrayInputStream ( xml . trim ( ) . getBytes ( charset ) ) ) ; input . setEncoding ( charset . displayName ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new CitrusRuntimeException ( e ) ; } Document doc ; try { doc = parser . parse ( input ) ; } catch ( Exception e ) { return xml ; } return serialize ( doc ) ; }
Pretty prints a XML string .
175
6
28,136
public static Map < String , String > lookupNamespaces ( Node referenceNode ) { Map < String , String > namespaces = new HashMap < String , String > ( ) ; Node node ; if ( referenceNode . getNodeType ( ) == Node . DOCUMENT_NODE ) { node = referenceNode . getFirstChild ( ) ; } else { node = referenceNode ; } if ( node != null && node . hasAttributes ( ) ) { for ( int i = 0 ; i < node . getAttributes ( ) . getLength ( ) ; i ++ ) { Node attribute = node . getAttributes ( ) . item ( i ) ; if ( attribute . getNodeName ( ) . startsWith ( XMLConstants . XMLNS_ATTRIBUTE + ":" ) ) { namespaces . put ( attribute . getNodeName ( ) . substring ( ( XMLConstants . XMLNS_ATTRIBUTE + ":" ) . length ( ) ) , attribute . getNodeValue ( ) ) ; } else if ( attribute . getNodeName ( ) . startsWith ( XMLConstants . XMLNS_ATTRIBUTE ) ) { //default namespace namespaces . put ( XMLConstants . DEFAULT_NS_PREFIX , attribute . getNodeValue ( ) ) ; } } } return namespaces ; }
Look up namespace attribute declarations in the specified node and store them in a binding map where the key is the namespace prefix and the value is the namespace uri .
279
32
28,137
public static Map < String , String > lookupNamespaces ( String xml ) { Map < String , String > namespaces = new HashMap < String , String > ( ) ; //TODO: handle inner CDATA sections because namespaces they might interfere with real namespaces in xml fragment if ( xml . indexOf ( XMLConstants . XMLNS_ATTRIBUTE ) != - 1 ) { String [ ] tokens = StringUtils . split ( xml , XMLConstants . XMLNS_ATTRIBUTE ) ; do { String token = tokens [ 1 ] ; String nsPrefix ; if ( token . startsWith ( ":" ) ) { nsPrefix = token . substring ( 1 , token . indexOf ( ' ' ) ) ; } else if ( token . startsWith ( "=" ) ) { nsPrefix = XMLConstants . DEFAULT_NS_PREFIX ; } else { //we have found a "xmlns" phrase that is no namespace attribute - ignore and continue tokens = StringUtils . split ( token , XMLConstants . XMLNS_ATTRIBUTE ) ; continue ; } String nsUri ; try { nsUri = token . substring ( token . indexOf ( ' ' ) + 1 , token . indexOf ( ' ' , token . indexOf ( ' ' ) + 1 ) ) ; } catch ( StringIndexOutOfBoundsException e ) { //maybe we have more luck with single "'" nsUri = token . substring ( token . indexOf ( ' ' ) + 1 , token . indexOf ( ' ' , token . indexOf ( ' ' ) + 1 ) ) ; } namespaces . put ( nsPrefix , nsUri ) ; tokens = StringUtils . split ( token , XMLConstants . XMLNS_ATTRIBUTE ) ; } while ( tokens != null ) ; } return namespaces ; }
Look up namespace attribute declarations in the XML fragment and store them in a binding map where the key is the namespace prefix and the value is the namespace uri .
400
32
28,138
public static Document parseMessagePayload ( String messagePayload ) { LSParser parser = configurer . createLSParser ( ) ; LSInput receivedInput = configurer . createLSInput ( ) ; try { Charset charset = getTargetCharset ( messagePayload ) ; receivedInput . setByteStream ( new ByteArrayInputStream ( messagePayload . trim ( ) . getBytes ( charset ) ) ) ; receivedInput . setEncoding ( charset . displayName ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new CitrusRuntimeException ( e ) ; } return parser . parse ( receivedInput ) ; }
Parse message payload with DOM implementation .
140
8
28,139
public static Charset getTargetCharset ( Document doc ) { String defaultEncoding = System . getProperty ( Citrus . CITRUS_FILE_ENCODING_PROPERTY , System . getenv ( Citrus . CITRUS_FILE_ENCODING_ENV ) ) ; if ( StringUtils . hasText ( defaultEncoding ) ) { return Charset . forName ( defaultEncoding ) ; } if ( doc . getInputEncoding ( ) != null ) { return Charset . forName ( doc . getInputEncoding ( ) ) ; } // return as encoding the default UTF-8 return Charset . forName ( "UTF-8" ) ; }
Try to find encoding for document node . Also supports Citrus default encoding set as System property .
154
19
28,140
private static Charset getTargetCharset ( String messagePayload ) throws UnsupportedEncodingException { String defaultEncoding = System . getProperty ( Citrus . CITRUS_FILE_ENCODING_PROPERTY , System . getenv ( Citrus . CITRUS_FILE_ENCODING_ENV ) ) ; if ( StringUtils . hasText ( defaultEncoding ) ) { return Charset . forName ( defaultEncoding ) ; } // trim incoming payload String payload = messagePayload . trim ( ) ; char doubleQuote = ' ' ; char singleQuote = ' ' ; // make sure payload has an XML encoding string String encodingKey = "encoding" ; if ( payload . startsWith ( "<?xml" ) && payload . contains ( encodingKey ) && payload . contains ( "?>" ) && ( payload . indexOf ( encodingKey ) < payload . indexOf ( "?>" ) ) ) { // extract only encoding part, as otherwise the rest of the complete pay load will be load String encoding = payload . substring ( payload . indexOf ( encodingKey ) + encodingKey . length ( ) , payload . indexOf ( "?>" ) ) ; char quoteChar = doubleQuote ; int idxDoubleQuote = encoding . indexOf ( doubleQuote ) ; int idxSingleQuote = encoding . indexOf ( singleQuote ) ; // check which character is the first one, allowing for <encoding = 'UTF-8'> white spaces if ( idxSingleQuote >= 0 && ( idxDoubleQuote < 0 || idxSingleQuote < idxDoubleQuote ) ) { quoteChar = singleQuote ; } // build encoding using the found character encoding = encoding . substring ( encoding . indexOf ( quoteChar ) + 1 ) ; encoding = encoding . substring ( 0 , encoding . indexOf ( quoteChar ) ) ; // check if it has a valid char set if ( ! Charset . availableCharsets ( ) . containsKey ( encoding ) ) { throw new UnsupportedEncodingException ( "Found unsupported encoding: '" + encoding + "'" ) ; } // should be a valid encoding return Charset . forName ( encoding ) ; } // return as encoding the default UTF-8 return Charset . forName ( "UTF-8" ) ; }
Try to find target encoding in XML declaration .
492
9
28,141
public static String omitXmlDeclaration ( String xml ) { if ( xml . startsWith ( "<?xml" ) && xml . contains ( "?>" ) ) { return xml . substring ( xml . indexOf ( "?>" ) + 2 ) . trim ( ) ; } return xml ; }
Removes leading XML declaration from xml if present .
64
10
28,142
private Resource loadSchemas ( Definition definition ) throws WSDLException , IOException , TransformerException , TransformerFactoryConfigurationError { Types types = definition . getTypes ( ) ; Resource targetXsd = null ; Resource firstSchemaInWSDL = null ; if ( types != null ) { List < ? > schemaTypes = types . getExtensibilityElements ( ) ; for ( Object schemaObject : schemaTypes ) { if ( schemaObject instanceof SchemaImpl ) { SchemaImpl schema = ( SchemaImpl ) schemaObject ; inheritNamespaces ( schema , definition ) ; addImportedSchemas ( schema ) ; addIncludedSchemas ( schema ) ; if ( ! importedSchemas . contains ( getTargetNamespace ( schema ) ) ) { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; Source source = new DOMSource ( schema . getElement ( ) ) ; Result result = new StreamResult ( bos ) ; TransformerFactory . newInstance ( ) . newTransformer ( ) . transform ( source , result ) ; Resource schemaResource = new ByteArrayResource ( bos . toByteArray ( ) ) ; importedSchemas . add ( getTargetNamespace ( schema ) ) ; schemaResources . add ( schemaResource ) ; if ( definition . getTargetNamespace ( ) . equals ( getTargetNamespace ( schema ) ) && targetXsd == null ) { targetXsd = schemaResource ; } else if ( targetXsd == null && firstSchemaInWSDL == null ) { firstSchemaInWSDL = schemaResource ; } } } else { log . warn ( "Found unsupported schema type implementation " + schemaObject . getClass ( ) ) ; } } } for ( Object imports : definition . getImports ( ) . values ( ) ) { for ( Import wsdlImport : ( Vector < Import > ) imports ) { String schemaLocation ; URI locationURI = URI . create ( wsdlImport . getLocationURI ( ) ) ; if ( locationURI . isAbsolute ( ) ) { schemaLocation = wsdlImport . getLocationURI ( ) ; } else { schemaLocation = definition . getDocumentBaseURI ( ) . substring ( 0 , definition . getDocumentBaseURI ( ) . lastIndexOf ( ' ' ) + 1 ) + wsdlImport . getLocationURI ( ) ; } loadSchemas ( getWsdlDefinition ( new FileSystemResource ( schemaLocation ) ) ) ; } } if ( targetXsd == null ) { // Obviously no schema resource in WSDL did match the targetNamespace, just use the first schema resource found as main schema if ( firstSchemaInWSDL != null ) { targetXsd = firstSchemaInWSDL ; } else if ( ! CollectionUtils . isEmpty ( schemaResources ) ) { targetXsd = schemaResources . get ( 0 ) ; } } return targetXsd ; }
Loads nested schema type definitions from wsdl .
619
11
28,143
@ SuppressWarnings ( "unchecked" ) private void inheritNamespaces ( SchemaImpl schema , Definition wsdl ) { Map < String , String > wsdlNamespaces = wsdl . getNamespaces ( ) ; for ( Entry < String , String > nsEntry : wsdlNamespaces . entrySet ( ) ) { if ( StringUtils . hasText ( nsEntry . getKey ( ) ) ) { if ( ! schema . getElement ( ) . hasAttributeNS ( WWW_W3_ORG_2000_XMLNS , nsEntry . getKey ( ) ) ) { schema . getElement ( ) . setAttributeNS ( WWW_W3_ORG_2000_XMLNS , "xmlns:" + nsEntry . getKey ( ) , nsEntry . getValue ( ) ) ; } } else { // handle default namespace if ( ! schema . getElement ( ) . hasAttribute ( "xmlns" ) ) { schema . getElement ( ) . setAttributeNS ( WWW_W3_ORG_2000_XMLNS , "xmlns" + nsEntry . getKey ( ) , nsEntry . getValue ( ) ) ; } } } }
Adds WSDL level namespaces to schema definition if necessary .
260
13
28,144
private Definition getWsdlDefinition ( Resource wsdl ) { try { Definition definition ; if ( wsdl . getURI ( ) . toString ( ) . startsWith ( "jar:" ) ) { // Locate WSDL imports in Jar files definition = WSDLFactory . newInstance ( ) . newWSDLReader ( ) . readWSDL ( new JarWSDLLocator ( wsdl ) ) ; } else { definition = WSDLFactory . newInstance ( ) . newWSDLReader ( ) . readWSDL ( wsdl . getURI ( ) . getPath ( ) , new InputSource ( wsdl . getInputStream ( ) ) ) ; } return definition ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read wsdl file resource" , e ) ; } catch ( WSDLException e ) { throw new CitrusRuntimeException ( "Failed to wsdl schema instance" , e ) ; } }
Reads WSDL definition from resource .
219
9
28,145
protected FtpMessage listFiles ( ListCommand list , TestContext context ) { String remoteFilePath = Optional . ofNullable ( list . getTarget ( ) ) . map ( ListCommand . Target :: getPath ) . map ( context :: replaceDynamicContentInString ) . orElse ( "" ) ; try { List < String > fileNames = new ArrayList <> ( ) ; FTPFile [ ] ftpFiles ; if ( StringUtils . hasText ( remoteFilePath ) ) { ftpFiles = ftpClient . listFiles ( remoteFilePath ) ; } else { ftpFiles = ftpClient . listFiles ( remoteFilePath ) ; } for ( FTPFile ftpFile : ftpFiles ) { fileNames . add ( ftpFile . getName ( ) ) ; } return FtpMessage . result ( ftpClient . getReplyCode ( ) , ftpClient . getReplyString ( ) , fileNames ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( String . format ( "Failed to list files in path '%s'" , remoteFilePath ) , e ) ; } }
Perform list files operation and provide file information as response .
241
12
28,146
protected FtpMessage deleteFile ( DeleteCommand delete , TestContext context ) { String remoteFilePath = context . replaceDynamicContentInString ( delete . getTarget ( ) . getPath ( ) ) ; try { if ( ! StringUtils . hasText ( remoteFilePath ) ) { return null ; } boolean success = true ; if ( isDirectory ( remoteFilePath ) ) { if ( ! ftpClient . changeWorkingDirectory ( remoteFilePath ) ) { throw new CitrusRuntimeException ( "Failed to change working directory to " + remoteFilePath + ". FTP reply code: " + ftpClient . getReplyString ( ) ) ; } if ( delete . isRecursive ( ) ) { FTPFile [ ] ftpFiles = ftpClient . listFiles ( ) ; for ( FTPFile ftpFile : ftpFiles ) { DeleteCommand recursiveDelete = new DeleteCommand ( ) ; DeleteCommand . Target target = new DeleteCommand . Target ( ) ; target . setPath ( remoteFilePath + "/" + ftpFile . getName ( ) ) ; recursiveDelete . setTarget ( target ) ; recursiveDelete . setIncludeCurrent ( true ) ; deleteFile ( recursiveDelete , context ) ; } } if ( delete . isIncludeCurrent ( ) ) { // we cannot delete the current working directory, so go to root directory and delete from there ftpClient . changeWorkingDirectory ( "/" ) ; success = ftpClient . removeDirectory ( remoteFilePath ) ; } } else { success = ftpClient . deleteFile ( remoteFilePath ) ; } if ( ! success ) { throw new CitrusRuntimeException ( "Failed to delete path " + remoteFilePath + ". FTP reply code: " + ftpClient . getReplyString ( ) ) ; } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to delete file from FTP server" , e ) ; } // If there was no file to delete, the ftpClient has the reply code from the previously executed // operation. Since we want to have a deterministic behaviour, we need to set the reply code and // reply string on our own! if ( ftpClient . getReplyCode ( ) != FILE_ACTION_OK ) { return FtpMessage . deleteResult ( FILE_ACTION_OK , String . format ( "%s No files to delete." , FILE_ACTION_OK ) , true ) ; } return FtpMessage . deleteResult ( ftpClient . getReplyCode ( ) , ftpClient . getReplyString ( ) , isPositive ( ftpClient . getReplyCode ( ) ) ) ; }
Performs delete file operation .
555
6
28,147
protected boolean isDirectory ( String remoteFilePath ) throws IOException { if ( ! ftpClient . changeWorkingDirectory ( remoteFilePath ) ) { // not a directory or not accessible switch ( ftpClient . listFiles ( remoteFilePath ) . length ) { case 0 : throw new CitrusRuntimeException ( "Remote file path does not exist or is not accessible: " + remoteFilePath ) ; case 1 : return false ; default : throw new CitrusRuntimeException ( "Unexpected file type result for file path: " + remoteFilePath ) ; } } else { return true ; } }
Check file path type directory or file .
125
8
28,148
protected FtpMessage storeFile ( PutCommand command , TestContext context ) { try { String localFilePath = context . replaceDynamicContentInString ( command . getFile ( ) . getPath ( ) ) ; String remoteFilePath = addFileNameToTargetPath ( localFilePath , context . replaceDynamicContentInString ( command . getTarget ( ) . getPath ( ) ) ) ; String dataType = context . replaceDynamicContentInString ( Optional . ofNullable ( command . getFile ( ) . getType ( ) ) . orElse ( DataType . BINARY . name ( ) ) ) ; try ( InputStream localFileInputStream = getLocalFileInputStream ( command . getFile ( ) . getPath ( ) , dataType , context ) ) { ftpClient . setFileType ( getFileType ( dataType ) ) ; if ( ! ftpClient . storeFile ( remoteFilePath , localFileInputStream ) ) { throw new IOException ( "Failed to put file to FTP server. Remote path: " + remoteFilePath + ". Local file path: " + localFilePath + ". FTP reply: " + ftpClient . getReplyString ( ) ) ; } } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to put file to FTP server" , e ) ; } return FtpMessage . putResult ( ftpClient . getReplyCode ( ) , ftpClient . getReplyString ( ) , isPositive ( ftpClient . getReplyCode ( ) ) ) ; }
Performs store file operation .
330
6
28,149
protected InputStream getLocalFileInputStream ( String path , String dataType , TestContext context ) throws IOException { if ( dataType . equals ( DataType . ASCII . name ( ) ) ) { String content = context . replaceDynamicContentInString ( FileUtils . readToString ( FileUtils . getFileResource ( path ) ) ) ; return new ByteArrayInputStream ( content . getBytes ( FileUtils . getDefaultCharset ( ) ) ) ; } else { return FileUtils . getFileResource ( path ) . getInputStream ( ) ; } }
Constructs local file input stream . When using ASCII data type the test variable replacement is activated otherwise plain byte stream is used .
123
25
28,150
protected FtpMessage retrieveFile ( GetCommand command , TestContext context ) { try { String remoteFilePath = context . replaceDynamicContentInString ( command . getFile ( ) . getPath ( ) ) ; String localFilePath = addFileNameToTargetPath ( remoteFilePath , context . replaceDynamicContentInString ( command . getTarget ( ) . getPath ( ) ) ) ; if ( Paths . get ( localFilePath ) . getParent ( ) != null ) { Files . createDirectories ( Paths . get ( localFilePath ) . getParent ( ) ) ; } String dataType = context . replaceDynamicContentInString ( Optional . ofNullable ( command . getFile ( ) . getType ( ) ) . orElse ( DataType . BINARY . name ( ) ) ) ; try ( FileOutputStream localFileOutputStream = new FileOutputStream ( localFilePath ) ) { ftpClient . setFileType ( getFileType ( dataType ) ) ; if ( ! ftpClient . retrieveFile ( remoteFilePath , localFileOutputStream ) ) { throw new CitrusRuntimeException ( "Failed to get file from FTP server. Remote path: " + remoteFilePath + ". Local file path: " + localFilePath + ". FTP reply: " + ftpClient . getReplyString ( ) ) ; } } if ( getEndpointConfiguration ( ) . isAutoReadFiles ( ) ) { String fileContent ; if ( command . getFile ( ) . getType ( ) . equals ( DataType . BINARY . name ( ) ) ) { fileContent = Base64 . encodeBase64String ( FileCopyUtils . copyToByteArray ( FileUtils . getFileResource ( localFilePath ) . getInputStream ( ) ) ) ; } else { fileContent = FileUtils . readToString ( FileUtils . getFileResource ( localFilePath ) ) ; } return FtpMessage . result ( ftpClient . getReplyCode ( ) , ftpClient . getReplyString ( ) , localFilePath , fileContent ) ; } else { return FtpMessage . result ( ftpClient . getReplyCode ( ) , ftpClient . getReplyString ( ) , localFilePath , null ) ; } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to get file from FTP server" , e ) ; } }
Performs retrieve file operation .
512
6
28,151
private int getFileType ( String typeInfo ) { switch ( typeInfo ) { case "ASCII" : return FTP . ASCII_FILE_TYPE ; case "BINARY" : return FTP . BINARY_FILE_TYPE ; case "EBCDIC" : return FTP . EBCDIC_FILE_TYPE ; case "LOCAL" : return FTP . LOCAL_FILE_TYPE ; default : return FTP . BINARY_FILE_TYPE ; } }
Get file type from info string .
101
7
28,152
protected void connectAndLogin ( ) throws IOException { if ( ! ftpClient . isConnected ( ) ) { ftpClient . connect ( getEndpointConfiguration ( ) . getHost ( ) , getEndpointConfiguration ( ) . getPort ( ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Connected to FTP server: " + ftpClient . getReplyString ( ) ) ; } int reply = ftpClient . getReplyCode ( ) ; if ( ! FTPReply . isPositiveCompletion ( reply ) ) { throw new CitrusRuntimeException ( "FTP server refused connection." ) ; } log . info ( "Opened connection to FTP server" ) ; if ( getEndpointConfiguration ( ) . getUser ( ) != null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Login as user: '%s'" , getEndpointConfiguration ( ) . getUser ( ) ) ) ; } boolean login = ftpClient . login ( getEndpointConfiguration ( ) . getUser ( ) , getEndpointConfiguration ( ) . getPassword ( ) ) ; if ( ! login ) { throw new CitrusRuntimeException ( String . format ( "Failed to login to FTP server using credentials: %s:%s" , getEndpointConfiguration ( ) . getUser ( ) , getEndpointConfiguration ( ) . getPassword ( ) ) ) ; } } if ( getEndpointConfiguration ( ) . isLocalPassiveMode ( ) ) { ftpClient . enterLocalPassiveMode ( ) ; } } }
Opens a new connection and performs login with user name and password if set .
345
16
28,153
private Source getPayloadSource ( Object payload ) { Source source = null ; if ( payload instanceof String ) { source = new StringSource ( ( String ) payload ) ; } else if ( payload instanceof File ) { source = new StreamSource ( ( File ) payload ) ; } else if ( payload instanceof Document ) { source = new DOMSource ( ( Document ) payload ) ; } else if ( payload instanceof Source ) { source = ( Source ) payload ; } if ( source == null ) { throw new CitrusRuntimeException ( "Failed to create payload source for unmarshalling message" ) ; } return source ; }
Creates the payload source for unmarshalling .
132
10
28,154
public Endpoint getOrCreateEndpoint ( TestContext context ) { if ( endpoint != null ) { return endpoint ; } else if ( StringUtils . hasText ( endpointUri ) ) { endpoint = context . getEndpointFactory ( ) . create ( endpointUri , context ) ; return endpoint ; } else { throw new CitrusRuntimeException ( "Neither endpoint nor endpoint uri is set properly!" ) ; } }
Creates or gets the endpoint instance .
89
8
28,155
public boolean shouldExecute ( String suiteName , String [ ] includedGroups ) { String baseErrorMessage = "Suite container restrictions did not match %s - do not execute container '%s'" ; if ( StringUtils . hasText ( suiteName ) && ! CollectionUtils . isEmpty ( suiteNames ) && ! suiteNames . contains ( suiteName ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( baseErrorMessage , "suite name" , getName ( ) ) ) ; } return false ; } if ( ! checkTestGroups ( includedGroups ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( baseErrorMessage , "test groups" , getName ( ) ) ) ; } return false ; } for ( Map . Entry < String , String > envEntry : env . entrySet ( ) ) { if ( ! System . getenv ( ) . containsKey ( envEntry . getKey ( ) ) || ( StringUtils . hasText ( envEntry . getValue ( ) ) && ! System . getenv ( ) . get ( envEntry . getKey ( ) ) . equals ( envEntry . getValue ( ) ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( baseErrorMessage , "env properties" , getName ( ) ) ) ; } return false ; } } for ( Map . Entry < String , String > systemProperty : systemProperties . entrySet ( ) ) { if ( ! System . getProperties ( ) . containsKey ( systemProperty . getKey ( ) ) || ( StringUtils . hasText ( systemProperty . getValue ( ) ) && ! System . getProperties ( ) . get ( systemProperty . getKey ( ) ) . equals ( systemProperty . getValue ( ) ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( baseErrorMessage , "system properties" , getName ( ) ) ) ; } return false ; } } return true ; }
Checks if this suite actions should execute according to suite name and included test groups .
448
17
28,156
public CamelControlBusActionBuilder route ( String id , String action ) { super . action . setRouteId ( id ) ; super . action . setAction ( action ) ; return this ; }
Sets route action to execute .
40
7
28,157
public CamelControlBusActionBuilder language ( String language , String expression ) { action . setLanguageType ( language ) ; action . setLanguageExpression ( expression ) ; return this ; }
Sets a language expression to execute .
38
8
28,158
public void handleRequest ( String request ) { if ( messageListener != null ) { log . debug ( "Received Http request" ) ; messageListener . onInboundMessage ( new RawMessage ( request ) , null ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Received Http request:" + NEWLINE + request ) ; } } }
Handle request message and write request to logger .
83
9
28,159
public void handleResponse ( String response ) { if ( messageListener != null ) { log . debug ( "Sending Http response" ) ; messageListener . onOutboundMessage ( new RawMessage ( response ) , null ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Sending Http response:" + NEWLINE + response ) ; } } }
Handle response message and write content to logger .
83
9
28,160
private String getRequestContent ( HttpServletRequest request ) throws IOException { StringBuilder builder = new StringBuilder ( ) ; builder . append ( request . getProtocol ( ) ) ; builder . append ( " " ) ; builder . append ( request . getMethod ( ) ) ; builder . append ( " " ) ; builder . append ( request . getRequestURI ( ) ) ; builder . append ( NEWLINE ) ; Enumeration < ? > headerNames = request . getHeaderNames ( ) ; while ( headerNames . hasMoreElements ( ) ) { String headerName = headerNames . nextElement ( ) . toString ( ) ; builder . append ( headerName ) ; builder . append ( ":" ) ; Enumeration < ? > headerValues = request . getHeaders ( headerName ) ; if ( headerValues . hasMoreElements ( ) ) { builder . append ( headerValues . nextElement ( ) ) ; } while ( headerValues . hasMoreElements ( ) ) { builder . append ( "," ) ; builder . append ( headerValues . nextElement ( ) ) ; } builder . append ( NEWLINE ) ; } builder . append ( NEWLINE ) ; builder . append ( FileUtils . readToString ( request . getInputStream ( ) ) ) ; return builder . toString ( ) ; }
Builds raw request message content from Http servlet request .
281
13
28,161
private javax . jms . Message receive ( String destinationName , String selector ) { javax . jms . Message receivedJmsMessage ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Receiving JMS message on destination: '" + destinationName + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; } if ( StringUtils . hasText ( selector ) ) { receivedJmsMessage = endpointConfiguration . getJmsTemplate ( ) . receiveSelected ( destinationName , selector ) ; } else { receivedJmsMessage = endpointConfiguration . getJmsTemplate ( ) . receive ( destinationName ) ; } if ( receivedJmsMessage == null ) { throw new ActionTimeoutException ( "Action timed out while receiving JMS message on '" + destinationName + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; } log . info ( "Received JMS message on destination: '" + destinationName + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; return receivedJmsMessage ; }
Receive message from destination name .
264
7
28,162
private javax . jms . Message receive ( Destination destination , String selector ) { javax . jms . Message receivedJmsMessage ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Receiving JMS message on destination: '" + endpointConfiguration . getDestinationName ( destination ) + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; } if ( StringUtils . hasText ( selector ) ) { receivedJmsMessage = endpointConfiguration . getJmsTemplate ( ) . receiveSelected ( destination , selector ) ; } else { receivedJmsMessage = endpointConfiguration . getJmsTemplate ( ) . receive ( destination ) ; } if ( receivedJmsMessage == null ) { throw new ActionTimeoutException ( "Action timed out while receiving JMS message on '" + endpointConfiguration . getDestinationName ( destination ) + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; } log . info ( "Received JMS message on destination: '" + endpointConfiguration . getDestinationName ( destination ) + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; return receivedJmsMessage ; }
Receive message from destination .
285
6
28,163
public String convert ( String messagePayload ) { initialize ( ) ; // check if we already have XHTML message content if ( messagePayload . contains ( XHTML_DOCTYPE_DEFINITION ) ) { return messagePayload ; } else { String xhtmlPayload ; StringWriter xhtmlWriter = new StringWriter ( ) ; tidyInstance . parse ( new StringReader ( messagePayload ) , xhtmlWriter ) ; xhtmlPayload = xhtmlWriter . toString ( ) ; xhtmlPayload = xhtmlPayload . replaceFirst ( W3_XHTML1_URL , "org/w3/xhtml/" ) ; return xhtmlPayload ; } }
Converts message to XHTML conform representation .
146
9
28,164
public void initialize ( ) { try { if ( tidyInstance == null ) { tidyInstance = new Tidy ( ) ; tidyInstance . setXHTML ( true ) ; tidyInstance . setShowWarnings ( false ) ; tidyInstance . setQuiet ( true ) ; tidyInstance . setEscapeCdata ( true ) ; tidyInstance . setTidyMark ( false ) ; if ( tidyConfiguration != null ) { tidyInstance . setConfigurationFromFile ( tidyConfiguration . getFile ( ) . getAbsolutePath ( ) ) ; } } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to initialize XHTML tidy instance" ) ; } }
Initialize tidy from configuration .
143
6
28,165
public void start ( ) { if ( kafkaServer != null ) { log . warn ( "Found instance of Kafka server - avoid duplicate Kafka server startup" ) ; return ; } File logDir = createLogDir ( ) ; zookeeper = createZookeeperServer ( logDir ) ; serverFactory = createServerFactory ( ) ; try { serverFactory . startup ( zookeeper ) ; } catch ( InterruptedException | IOException e ) { throw new CitrusRuntimeException ( "Failed to start embedded zookeeper server" , e ) ; } Properties brokerConfigProperties = createBrokerProperties ( "localhost:" + zookeeperPort , kafkaServerPort , logDir ) ; brokerConfigProperties . setProperty ( KafkaConfig . ReplicaSocketTimeoutMsProp ( ) , "1000" ) ; brokerConfigProperties . setProperty ( KafkaConfig . ControllerSocketTimeoutMsProp ( ) , "1000" ) ; brokerConfigProperties . setProperty ( KafkaConfig . OffsetsTopicReplicationFactorProp ( ) , "1" ) ; brokerConfigProperties . setProperty ( KafkaConfig . ReplicaHighWatermarkCheckpointIntervalMsProp ( ) , String . valueOf ( Long . MAX_VALUE ) ) ; if ( brokerProperties != null ) { brokerProperties . forEach ( brokerConfigProperties :: put ) ; } kafkaServer = new KafkaServer ( new KafkaConfig ( brokerConfigProperties ) , Time . SYSTEM , scala . Option . apply ( null ) , scala . collection . JavaConversions . asScalaBuffer ( Collections . < KafkaMetricsReporter > emptyList ( ) ) . toList ( ) ) ; kafkaServer . startup ( ) ; kafkaServer . boundPort ( ListenerName . forSecurityProtocol ( SecurityProtocol . PLAINTEXT ) ) ; createKafkaTopics ( StringUtils . commaDelimitedListToSet ( topics ) ) ; }
Start embedded server instances for Kafka and Zookeeper .
415
11
28,166
public void stop ( ) { if ( kafkaServer != null ) { try { if ( kafkaServer . brokerState ( ) . currentState ( ) != ( NotRunning . state ( ) ) ) { kafkaServer . shutdown ( ) ; kafkaServer . awaitShutdown ( ) ; } } catch ( Exception e ) { log . warn ( "Failed to shutdown Kafka embedded server" , e ) ; } try { CoreUtils . delete ( kafkaServer . config ( ) . logDirs ( ) ) ; } catch ( Exception e ) { log . warn ( "Failed to remove logs on Kafka embedded server" , e ) ; } } if ( serverFactory != null ) { try { serverFactory . shutdown ( ) ; } catch ( Exception e ) { log . warn ( "Failed to shutdown Zookeeper instance" , e ) ; } } }
Shutdown embedded Kafka and Zookeeper server instances
188
10
28,167
protected ZooKeeperServer createZookeeperServer ( File logDir ) { try { return new ZooKeeperServer ( logDir , logDir , 2000 ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to create embedded zookeeper server" , e ) ; } }
Creates new embedded Zookeeper server .
67
9
28,168
protected File createLogDir ( ) { File logDir = Optional . ofNullable ( logDirPath ) . map ( Paths :: get ) . map ( Path :: toFile ) . orElse ( new File ( System . getProperty ( "java.io.tmpdir" ) ) ) ; if ( ! logDir . exists ( ) ) { if ( ! logDir . mkdirs ( ) ) { log . warn ( "Unable to create log directory: " + logDir . getAbsolutePath ( ) ) ; logDir = new File ( System . getProperty ( "java.io.tmpdir" ) ) ; log . info ( "Using default log directory: " + logDir . getAbsolutePath ( ) ) ; } } File logs = new File ( logDir , "zookeeper" + System . currentTimeMillis ( ) ) . getAbsoluteFile ( ) ; if ( autoDeleteLogs ) { logs . deleteOnExit ( ) ; } return logs ; }
Creates Zookeeper log directory . By default logs are created in Java temp directory . By default directory is automatically deleted on exit .
211
27
28,169
protected ServerCnxnFactory createServerFactory ( ) { try { ServerCnxnFactory serverFactory = new NIOServerCnxnFactory ( ) ; serverFactory . configure ( new InetSocketAddress ( zookeeperPort ) , 5000 ) ; return serverFactory ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to create default zookeeper server factory" , e ) ; } }
Create server factory for embedded Zookeeper server instance .
93
11
28,170
protected void createKafkaTopics ( Set < String > topics ) { Map < String , Object > adminConfigs = new HashMap <> ( ) ; adminConfigs . put ( AdminClientConfig . BOOTSTRAP_SERVERS_CONFIG , "localhost:" + kafkaServerPort ) ; try ( AdminClient admin = AdminClient . create ( adminConfigs ) ) { List < NewTopic > newTopics = topics . stream ( ) . map ( t -> new NewTopic ( t , partitions , ( short ) 1 ) ) . collect ( Collectors . toList ( ) ) ; CreateTopicsResult createTopics = admin . createTopics ( newTopics ) ; try { createTopics . all ( ) . get ( ) ; } catch ( Exception e ) { log . warn ( "Failed to create Kafka topics" , e ) ; } } }
Create topics on embedded Kafka server .
180
7
28,171
protected Properties createBrokerProperties ( String zooKeeperConnect , int kafkaServerPort , File logDir ) { Properties props = new Properties ( ) ; props . put ( KafkaConfig . BrokerIdProp ( ) , "0" ) ; props . put ( KafkaConfig . ZkConnectProp ( ) , zooKeeperConnect ) ; props . put ( KafkaConfig . ZkConnectionTimeoutMsProp ( ) , "10000" ) ; props . put ( KafkaConfig . ReplicaSocketTimeoutMsProp ( ) , "1500" ) ; props . put ( KafkaConfig . ControllerSocketTimeoutMsProp ( ) , "1500" ) ; props . put ( KafkaConfig . ControlledShutdownEnableProp ( ) , "false" ) ; props . put ( KafkaConfig . DeleteTopicEnableProp ( ) , "true" ) ; props . put ( KafkaConfig . LogDeleteDelayMsProp ( ) , "1000" ) ; props . put ( KafkaConfig . ControlledShutdownRetryBackoffMsProp ( ) , "100" ) ; props . put ( KafkaConfig . LogCleanerDedupeBufferSizeProp ( ) , "2097152" ) ; props . put ( KafkaConfig . LogMessageTimestampDifferenceMaxMsProp ( ) , Long . MAX_VALUE ) ; props . put ( KafkaConfig . OffsetsTopicReplicationFactorProp ( ) , "1" ) ; props . put ( KafkaConfig . OffsetsTopicPartitionsProp ( ) , "5" ) ; props . put ( KafkaConfig . GroupInitialRebalanceDelayMsProp ( ) , "0" ) ; props . put ( KafkaConfig . LogDirProp ( ) , logDir . getAbsolutePath ( ) ) ; props . put ( KafkaConfig . ListenersProp ( ) , SecurityProtocol . PLAINTEXT . name + "://localhost:" + kafkaServerPort ) ; props . forEach ( ( key , value ) -> log . debug ( String . format ( "Using default Kafka broker property %s='%s'" , key , value ) ) ) ; return props ; }
Creates Kafka broker properties .
440
6
28,172
public void doWithMessage ( WebServiceMessage responseMessage ) throws IOException , TransformerException { // convert and set response for later access via getResponse(): response = endpointConfiguration . getMessageConverter ( ) . convertInbound ( responseMessage , endpointConfiguration , context ) ; }
Callback method called with actual web service response message . Method constructs a Spring Integration message from this web service message for further processing .
59
25
28,173
public void saveReplyDestination ( Message receivedMessage , TestContext context ) { if ( receivedMessage . getHeader ( CitrusVertxMessageHeaders . VERTX_REPLY_ADDRESS ) != null ) { String correlationKeyName = endpointConfiguration . getCorrelator ( ) . getCorrelationKeyName ( getName ( ) ) ; String correlationKey = endpointConfiguration . getCorrelator ( ) . getCorrelationKey ( receivedMessage ) ; correlationManager . saveCorrelationKey ( correlationKeyName , correlationKey , context ) ; correlationManager . store ( correlationKey , receivedMessage . getHeader ( CitrusVertxMessageHeaders . VERTX_REPLY_ADDRESS ) . toString ( ) ) ; } else { log . warn ( "Unable to retrieve reply address for message \n" + receivedMessage + "\n - no reply address found in message headers!" ) ; } }
Store the reply address either straight forward or with a given message correlation key .
195
15
28,174
private ZooKeeper createZooKeeperClient ( ) throws IOException { ZooClientConfig config = getZookeeperClientConfig ( ) ; return new ZooKeeper ( config . getUrl ( ) , config . getTimeout ( ) , getConnectionWatcher ( ) ) ; }
Creates a new Zookeeper client instance with configuration .
60
12
28,175
public ZooKeeper getZooKeeperClient ( ) { if ( zookeeper == null ) { try { zookeeper = createZooKeeperClient ( ) ; int retryAttempts = 5 ; while ( ! zookeeper . getState ( ) . isConnected ( ) && retryAttempts > 0 ) { LOG . debug ( "connecting..." ) ; retryAttempts -- ; Thread . sleep ( 1000 ) ; } } catch ( IOException | InterruptedException e ) { throw new CitrusRuntimeException ( e ) ; } } return zookeeper ; }
Constructs or gets the zookeeper client implementation .
122
11
28,176
private void loadEndpointComponentProperties ( ) { try { endpointComponentProperties = PropertiesLoaderUtils . loadProperties ( new ClassPathResource ( "com/consol/citrus/endpoint/endpoint.components" ) ) ; } catch ( IOException e ) { log . warn ( "Unable to laod default endpoint components from resource '%s'" , e ) ; } }
Loads property file from classpath holding default endpoint component definitions in Citrus .
86
16
28,177
private void loadEndpointParserProperties ( ) { try { endpointParserProperties = PropertiesLoaderUtils . loadProperties ( new ClassPathResource ( "com/consol/citrus/endpoint/endpoint.parser" ) ) ; } catch ( IOException e ) { log . warn ( "Unable to laod default endpoint annotation parsers from resource '%s'" , e ) ; } }
Loads property file from classpath holding default endpoint annotation parser definitions in Citrus .
87
17
28,178
public void setAction ( String action ) { try { this . action = new URI ( action ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid action uri" , e ) ; } }
Sets the action from uri string .
51
9
28,179
public void setTo ( String to ) { try { this . to = new URI ( to ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid to uri" , e ) ; } }
Sets the to uri by string .
51
9
28,180
public void setMessageId ( String messageId ) { try { this . messageId = new URI ( messageId ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid messageId uri" , e ) ; } }
Sets the message id from uri string .
56
10
28,181
public void setFrom ( String from ) { try { this . from = new EndpointReference ( new URI ( from ) ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid from uri" , e ) ; } }
Sets the from endpoint reference by string .
57
9
28,182
public void setReplyTo ( String replyTo ) { try { this . replyTo = new EndpointReference ( new URI ( replyTo ) ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid replyTo uri" , e ) ; } }
Sets the reply to endpoint reference by string .
62
10
28,183
public void setFaultTo ( String faultTo ) { try { this . faultTo = new EndpointReference ( new URI ( faultTo ) ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid faultTo uri" , e ) ; } }
Sets the fault to endpoint reference by string .
63
10
28,184
private void createHtmlDoc ( ) throws PrompterException { HtmlDocConfiguration configuration = new HtmlDocConfiguration ( ) ; String heading = prompter . prompt ( "Enter overview title:" , configuration . getHeading ( ) ) ; String columns = prompter . prompt ( "Enter number of columns in overview:" , configuration . getColumns ( ) ) ; String pageTitle = prompter . prompt ( "Enter page title:" , configuration . getPageTitle ( ) ) ; String outputFile = prompter . prompt ( "Enter output file name:" , configuration . getOutputFile ( ) ) ; String logo = prompter . prompt ( "Enter file path to logo:" , configuration . getLogo ( ) ) ; String confirm = prompter . prompt ( "Confirm HTML documentation: outputFile='target/" + outputFile + ( outputFile . endsWith ( ".html" ) ? "" : ".html" ) + "'\n" , Arrays . asList ( "y" , "n" ) , "y" ) ; if ( confirm . equalsIgnoreCase ( "n" ) ) { return ; } HtmlTestDocsGenerator generator = getHtmlTestDocsGenerator ( ) ; generator . withOutputFile ( outputFile + ( outputFile . endsWith ( ".html" ) ? "" : ".html" ) ) . withPageTitle ( pageTitle ) . withOverviewTitle ( heading ) . withColumns ( columns ) . useSrcDirectory ( getTestSrcDirectory ( ) ) . withLogo ( logo ) ; generator . generateDoc ( ) ; getLog ( ) . info ( "Successfully created HTML documentation: outputFile='target/" + outputFile + ( outputFile . endsWith ( ".html" ) ? "" : ".html" ) + "'" ) ; }
Create HTML documentation in interactive mode .
381
7
28,185
private void createExcelDoc ( ) throws PrompterException { ExcelDocConfiguration configuration = new ExcelDocConfiguration ( ) ; String company = prompter . prompt ( "Enter company:" , configuration . getCompany ( ) ) ; String author = prompter . prompt ( "Enter author:" , configuration . getAuthor ( ) ) ; String pageTitle = prompter . prompt ( "Enter page title:" , configuration . getPageTitle ( ) ) ; String outputFile = prompter . prompt ( "Enter output file name:" , configuration . getOutputFile ( ) ) ; String headers = prompter . prompt ( "Enter custom headers:" , configuration . getHeaders ( ) ) ; String confirm = prompter . prompt ( "Confirm Excel documentation: outputFile='target/" + outputFile + ( outputFile . endsWith ( ".xls" ) ? "" : ".xls" ) + "'\n" , Arrays . asList ( "y" , "n" ) , "y" ) ; if ( confirm . equalsIgnoreCase ( "n" ) ) { return ; } ExcelTestDocsGenerator generator = getExcelTestDocsGenerator ( ) ; generator . withOutputFile ( outputFile + ( outputFile . endsWith ( ".xls" ) ? "" : ".xls" ) ) . withPageTitle ( pageTitle ) . withAuthor ( author ) . withCompany ( company ) . useSrcDirectory ( getTestSrcDirectory ( ) ) . withCustomHeaders ( headers ) ; generator . generateDoc ( ) ; getLog ( ) . info ( "Successfully created Excel documentation: outputFile='target/" + outputFile + ( outputFile . endsWith ( ".xls" ) ? "" : ".xls" ) + "'" ) ; }
Create Excel documentation in interactive mode .
374
7
28,186
public static String changeDate ( String date , String dateOffset , String dateFormat , TestContext context ) { return new ChangeDateFunction ( ) . execute ( Arrays . asList ( date , dateOffset , dateFormat ) , context ) ; }
Runs change date function with arguments .
51
8
28,187
public static String createCDataSection ( String content , TestContext context ) { return new CreateCDataSectionFunction ( ) . execute ( Collections . singletonList ( content ) , context ) ; }
Runs create CData section function with arguments .
41
10
28,188
public static String digestAuthHeader ( String username , String password , String realm , String noncekey , String method , String uri , String opaque , String algorithm , TestContext context ) { return new DigestAuthHeaderFunction ( ) . execute ( Arrays . asList ( username , password , realm , noncekey , method , uri , opaque , algorithm ) , context ) ; }
Runs create digest auth header function with arguments .
80
10
28,189
public static String randomUUID ( TestContext context ) { return new RandomUUIDFunction ( ) . execute ( Collections . < String > emptyList ( ) , context ) ; }
Runs random UUID function with arguments .
37
9
28,190
public static String escapeXml ( String content , TestContext context ) { return new EscapeXmlFunction ( ) . execute ( Collections . singletonList ( content ) , context ) ; }
Runs escape XML function with arguments .
39
8
28,191
public static String readFile ( String filePath , TestContext context ) { return new ReadFileResourceFunction ( ) . execute ( Collections . singletonList ( filePath ) , context ) ; }
Reads the file resource and returns the complete file content .
40
12
28,192
public static void parseJsonPathElements ( Element validateElement , Map < String , Object > validateJsonPathExpressions ) { List < ? > jsonPathElements = DomUtils . getChildElementsByTagName ( validateElement , "json-path" ) ; if ( jsonPathElements . size ( ) > 0 ) { for ( Iterator < ? > jsonPathIterator = jsonPathElements . iterator ( ) ; jsonPathIterator . hasNext ( ) ; ) { Element jsonPathElement = ( Element ) jsonPathIterator . next ( ) ; String expression = jsonPathElement . getAttribute ( "expression" ) ; if ( StringUtils . hasText ( expression ) ) { validateJsonPathExpressions . put ( expression , jsonPathElement . getAttribute ( "value" ) ) ; } } } }
Parses validate element containing nested json - path elements .
176
12
28,193
public static String readToString ( Resource resource , Charset charset ) throws IOException { if ( simulationMode ) { if ( resource instanceof ClassPathResource ) { return ( ( ClassPathResource ) resource ) . getPath ( ) ; } else if ( resource instanceof FileSystemResource ) { return ( ( FileSystemResource ) resource ) . getPath ( ) ; } else { return resource . getFilename ( ) ; } } if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Reading file resource: '%s' (encoding is '%s')" , resource . getFilename ( ) , charset . displayName ( ) ) ) ; } return readToString ( resource . getInputStream ( ) , charset ) ; }
Read file resource to string value .
165
7
28,194
public static String readToString ( InputStream inputStream , Charset charset ) throws IOException { return new String ( FileCopyUtils . copyToByteArray ( inputStream ) , charset ) ; }
Read file input stream to string value .
45
8
28,195
public static void writeToFile ( InputStream inputStream , File file ) { try ( InputStreamReader inputStreamReader = new InputStreamReader ( inputStream ) ) { writeToFile ( FileCopyUtils . copyToString ( inputStreamReader ) , file , getDefaultCharset ( ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to write file" , e ) ; } }
Writes inputStream content to file . Uses default charset encoding .
92
14
28,196
public static void writeToFile ( String content , File file , Charset charset ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Writing file resource: '%s' (encoding is '%s')" , file . getName ( ) , charset . displayName ( ) ) ) ; } if ( ! file . getParentFile ( ) . exists ( ) ) { if ( ! file . getParentFile ( ) . mkdirs ( ) ) { throw new CitrusRuntimeException ( "Unable to create folder structure for file: " + file . getPath ( ) ) ; } } try ( OutputStream fos = new BufferedOutputStream ( new FileOutputStream ( file ) ) ) { fos . write ( content . getBytes ( charset ) ) ; fos . flush ( ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to write file" , e ) ; } }
Writes String content to file with given charset encoding . Automatically closes file output streams when done .
212
21
28,197
public static List < File > findFiles ( final String startDir , final Set < String > fileNamePatterns ) { /* file names to be returned */ final List < File > files = new ArrayList < File > ( ) ; /* Stack to hold potential sub directories */ final Stack < File > dirs = new Stack < File > ( ) ; /* start directory */ final File startdir = new File ( startDir ) ; if ( ! startdir . exists ( ) ) { throw new CitrusRuntimeException ( "Test directory " + startdir . getAbsolutePath ( ) + " does not exist" ) ; } if ( startdir . isDirectory ( ) ) { dirs . push ( startdir ) ; } /* walk through the directories */ while ( dirs . size ( ) > 0 ) { final File file = dirs . pop ( ) ; File [ ] foundFiles = file . listFiles ( ( dir , name ) -> { File tmp = new File ( dir . getPath ( ) + File . separator + name ) ; boolean accepted = tmp . isDirectory ( ) ; for ( String fileNamePattern : fileNamePatterns ) { if ( fileNamePattern . contains ( "/" ) ) { fileNamePattern = fileNamePattern . substring ( fileNamePattern . lastIndexOf ( ' ' ) + 1 ) ; } fileNamePattern = fileNamePattern . replace ( "." , "\\." ) . replace ( "*" , ".*" ) ; if ( name . matches ( fileNamePattern ) ) { accepted = true ; } } /* Only allowing XML files as spring configuration files */ return accepted && ! name . startsWith ( "CVS" ) && ! name . startsWith ( ".svn" ) && ! name . startsWith ( ".git" ) ; } ) ; for ( File found : Optional . ofNullable ( foundFiles ) . orElse ( new File [ ] { } ) ) { /* Subfolder support */ if ( found . isDirectory ( ) ) { dirs . push ( found ) ; } else { files . add ( found ) ; } } } return files ; }
Method to retrieve all files with given file name pattern in given directory . Hierarchy of folders is supported .
446
21
28,198
@ SuppressWarnings ( "unchecked" ) public static ClientServerEndpointBuilder < DockerClientBuilder , DockerClientBuilder > docker ( ) { return new ClientServerEndpointBuilder ( new DockerClientBuilder ( ) , new DockerClientBuilder ( ) ) { @ Override public EndpointBuilder < ? extends Endpoint > server ( ) { throw new UnsupportedOperationException ( "Citrus Docker stack has no support for server implementation" ) ; } } ; }
Creates new DockerClient builder .
98
7
28,199
@ SuppressWarnings ( "unchecked" ) public static ClientServerEndpointBuilder < KubernetesClientBuilder , KubernetesClientBuilder > kubernetes ( ) { return new ClientServerEndpointBuilder ( new KubernetesClientBuilder ( ) , new KubernetesClientBuilder ( ) ) { @ Override public EndpointBuilder < ? extends Endpoint > server ( ) { throw new UnsupportedOperationException ( "Citrus Kubernetes stack has no support for server implementation" ) ; } } ; }
Creates new KubernetesClient builder .
116
10