idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
28,100
public static String parseMessagePayload ( Element payloadElement ) { if ( payloadElement == null ) { return "" ; } try { Document payload = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) . newDocument ( ) ; payload . appendChild ( payload . importNode ( payloadElement , true ) ) ; String payloadData = XMLUtils . serialize ( payload ) ; payloadData = payloadData . replaceAll ( " xmlns=\\\"http://www.citrusframework.org/schema/testcase\\\"" , "" ) ; return payloadData . trim ( ) ; } catch ( DOMException e ) { throw new CitrusRuntimeException ( "Error while constructing message payload" , e ) ; } catch ( ParserConfigurationException e ) { throw new CitrusRuntimeException ( "Error while constructing message payload" , e ) ; } }
Static parse method taking care of payload element .
28,101
public ServerCnxnFactory getServerFactory ( ) { if ( serverFactory == null ) { try { serverFactory = new NIOServerCnxnFactory ( ) ; serverFactory . configure ( new InetSocketAddress ( port ) , 5000 ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to create default zookeeper server factory" , e ) ; } } return serverFactory ; }
Gets the value of the serverFactory property .
28,102
public ZooKeeperServer getZooKeeperServer ( ) { if ( zooKeeperServer == null ) { String dataDirectory = System . getProperty ( "java.io.tmpdir" ) ; File dir = new File ( dataDirectory , "zookeeper" ) . getAbsoluteFile ( ) ; try { zooKeeperServer = new ZooKeeperServer ( dir , dir , 2000 ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to create default zookeeper server" , e ) ; } } return zooKeeperServer ; }
Gets the value of the zooKeeperServer property .
28,103
public HttpComponentsClientHttpRequestFactory getObject ( ) throws Exception { Assert . notNull ( credentials , "User credentials not set properly!" ) ; HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory ( httpClient ) { protected HttpContext createHttpContext ( HttpMethod httpMethod , URI uri ) { AuthCache authCache = new BasicAuthCache ( ) ; BasicScheme basicAuth = new BasicScheme ( ) ; authCache . put ( new HttpHost ( authScope . getHost ( ) , authScope . getPort ( ) , "http" ) , basicAuth ) ; authCache . put ( new HttpHost ( authScope . getHost ( ) , authScope . getPort ( ) , "https" ) , basicAuth ) ; BasicHttpContext localcontext = new BasicHttpContext ( ) ; localcontext . setAttribute ( ClientContext . AUTH_CACHE , authCache ) ; return localcontext ; } } ; if ( httpClient instanceof AbstractHttpClient ) { ( ( AbstractHttpClient ) httpClient ) . getCredentialsProvider ( ) . setCredentials ( authScope , credentials ) ; } else { log . warn ( "Unable to set username password credentials for basic authentication, " + "because nested HttpClient implementation does not support a credentials provider!" ) ; } return requestFactory ; }
Construct the client factory bean with user credentials .
28,104
protected T findValidationContext ( List < ValidationContext > validationContexts ) { for ( ValidationContext validationContext : validationContexts ) { if ( getRequiredValidationContextType ( ) . isInstance ( validationContext ) ) { return ( T ) validationContext ; } } return null ; }
Finds the message validation context that is most appropriate for this validator implementation .
28,105
private long getWaitTimeMs ( TestContext context ) { if ( StringUtils . hasText ( seconds ) ) { return Long . valueOf ( context . replaceDynamicContentInString ( seconds ) ) * 1000 ; } else { return Long . valueOf ( context . replaceDynamicContentInString ( milliseconds ) ) ; } }
Gets total wait time in milliseconds . Either uses second time value or default milliseconds .
28,106
protected void createConnection ( ) throws JMSException { if ( connection == null ) { if ( ! endpointConfiguration . isPubSubDomain ( ) && endpointConfiguration . getConnectionFactory ( ) instanceof QueueConnectionFactory ) { connection = ( ( QueueConnectionFactory ) endpointConfiguration . getConnectionFactory ( ) ) . createQueueConnection ( ) ; } else if ( endpointConfiguration . isPubSubDomain ( ) && endpointConfiguration . getConnectionFactory ( ) instanceof TopicConnectionFactory ) { connection = ( ( TopicConnectionFactory ) endpointConfiguration . getConnectionFactory ( ) ) . createTopicConnection ( ) ; connection . setClientID ( getName ( ) ) ; } else { log . warn ( "Not able to create a connection with connection factory '" + endpointConfiguration . getConnectionFactory ( ) + "'" + " when using setting 'publish-subscribe-domain' (=" + endpointConfiguration . isPubSubDomain ( ) + ")" ) ; connection = endpointConfiguration . getConnectionFactory ( ) . createConnection ( ) ; } connection . start ( ) ; } }
Create new JMS connection .
28,107
protected void createSession ( Connection connection ) throws JMSException { if ( session == null ) { if ( ! endpointConfiguration . isPubSubDomain ( ) && connection instanceof QueueConnection ) { session = ( ( QueueConnection ) connection ) . createQueueSession ( false , Session . AUTO_ACKNOWLEDGE ) ; } else if ( endpointConfiguration . isPubSubDomain ( ) && endpointConfiguration . getConnectionFactory ( ) instanceof TopicConnectionFactory ) { session = ( ( TopicConnection ) connection ) . createTopicSession ( false , Session . AUTO_ACKNOWLEDGE ) ; } else { log . warn ( "Not able to create a session with connection factory '" + endpointConfiguration . getConnectionFactory ( ) + "'" + " when using setting 'publish-subscribe-domain' (=" + endpointConfiguration . isPubSubDomain ( ) + ")" ) ; session = connection . createSession ( false , Session . AUTO_ACKNOWLEDGE ) ; } } }
Create new JMS session .
28,108
private void deleteTemporaryDestination ( Destination destination ) { log . debug ( "Delete temporary destination: '{}'" , destination ) ; try { if ( destination instanceof TemporaryQueue ) { ( ( TemporaryQueue ) destination ) . delete ( ) ; } else if ( destination instanceof TemporaryTopic ) { ( ( TemporaryTopic ) destination ) . delete ( ) ; } } catch ( JMSException e ) { log . error ( "Error while deleting temporary destination '" + destination + "'" , e ) ; } }
Delete temporary destinations .
28,109
private Destination getReplyDestination ( Session session , Message message ) throws JMSException { if ( message . getHeader ( org . springframework . messaging . MessageHeaders . REPLY_CHANNEL ) != null ) { if ( message . getHeader ( org . springframework . messaging . MessageHeaders . REPLY_CHANNEL ) instanceof Destination ) { return ( Destination ) message . getHeader ( org . springframework . messaging . MessageHeaders . REPLY_CHANNEL ) ; } else { return resolveDestinationName ( message . getHeader ( org . springframework . messaging . MessageHeaders . REPLY_CHANNEL ) . toString ( ) , session ) ; } } else if ( endpointConfiguration . getReplyDestination ( ) != null ) { return endpointConfiguration . getReplyDestination ( ) ; } else if ( StringUtils . hasText ( endpointConfiguration . getReplyDestinationName ( ) ) ) { return resolveDestinationName ( endpointConfiguration . getReplyDestinationName ( ) , session ) ; } if ( endpointConfiguration . isPubSubDomain ( ) && session instanceof TopicSession ) { return session . createTemporaryTopic ( ) ; } else { return session . createTemporaryQueue ( ) ; } }
Retrieve the reply destination either by injected instance destination name or by creating a new temporary destination .
28,110
private Destination resolveDestination ( String destinationName ) throws JMSException { if ( log . isDebugEnabled ( ) ) { log . debug ( "Sending JMS message to destination: '" + destinationName + "'" ) ; } return resolveDestinationName ( destinationName , session ) ; }
Resolve destination from given name .
28,111
private Destination resolveDestinationName ( String name , Session session ) throws JMSException { if ( endpointConfiguration . getDestinationResolver ( ) != null ) { return endpointConfiguration . getDestinationResolver ( ) . resolveDestinationName ( session , name , endpointConfiguration . isPubSubDomain ( ) ) ; } return new DynamicDestinationResolver ( ) . resolveDestinationName ( session , name , endpointConfiguration . isPubSubDomain ( ) ) ; }
Resolves the destination name from Jms session .
28,112
public void destroy ( ) { JmsUtils . closeSession ( session ) ; if ( connection != null ) { ConnectionFactoryUtils . releaseConnection ( connection , endpointConfiguration . getConnectionFactory ( ) , true ) ; } }
Destroy method closing JMS session and connection
28,113
public CamelRouteActionBuilder context ( String camelContext ) { Assert . notNull ( applicationContext , "Citrus application context is not initialized!" ) ; this . camelContext = applicationContext . getBean ( camelContext , ModelCamelContext . class ) ; return this ; }
Sets the Camel context to use .
28,114
public CamelControlBusActionBuilder controlBus ( ) { CamelControlBusAction camelControlBusAction = new CamelControlBusAction ( ) ; camelControlBusAction . setCamelContext ( getCamelContext ( ) ) ; action . setDelegate ( camelControlBusAction ) ; return new CamelControlBusActionBuilder ( camelControlBusAction ) ; }
Execute control bus Camel operations .
28,115
public CamelRouteActionBuilder create ( RouteBuilder routeBuilder ) { CreateCamelRouteAction camelRouteAction = new CreateCamelRouteAction ( ) ; try { if ( ! routeBuilder . getContext ( ) . equals ( getCamelContext ( ) ) ) { routeBuilder . configureRoutes ( getCamelContext ( ) ) ; } else { routeBuilder . configure ( ) ; } camelRouteAction . setRoutes ( routeBuilder . getRouteCollection ( ) . getRoutes ( ) ) ; } catch ( Exception e ) { throw new CitrusRuntimeException ( "Failed to configure route definitions with camel context" , e ) ; } camelRouteAction . setCamelContext ( getCamelContext ( ) ) ; action . setDelegate ( camelRouteAction ) ; return this ; }
Creates new Camel routes in route builder .
28,116
public void start ( String ... routes ) { StartCamelRouteAction camelRouteAction = new StartCamelRouteAction ( ) ; camelRouteAction . setRouteIds ( Arrays . asList ( routes ) ) ; camelRouteAction . setCamelContext ( getCamelContext ( ) ) ; action . setDelegate ( camelRouteAction ) ; }
Start these Camel routes .
28,117
public void stop ( String ... routes ) { StopCamelRouteAction camelRouteAction = new StopCamelRouteAction ( ) ; camelRouteAction . setRouteIds ( Arrays . asList ( routes ) ) ; camelRouteAction . setCamelContext ( getCamelContext ( ) ) ; action . setDelegate ( camelRouteAction ) ; }
Stop these Camel routes .
28,118
public void remove ( String ... routes ) { RemoveCamelRouteAction camelRouteAction = new RemoveCamelRouteAction ( ) ; camelRouteAction . setRouteIds ( Arrays . asList ( routes ) ) ; camelRouteAction . setCamelContext ( getCamelContext ( ) ) ; action . setDelegate ( camelRouteAction ) ; }
Remove these Camel routes .
28,119
private ModelCamelContext getCamelContext ( ) { if ( camelContext == null ) { Assert . notNull ( applicationContext , "Citrus application context is not initialized!" ) ; if ( applicationContext . containsBean ( "citrusCamelContext" ) ) { camelContext = applicationContext . getBean ( "citrusCamelContext" , ModelCamelContext . class ) ; } else { camelContext = applicationContext . getBean ( ModelCamelContext . class ) ; } } return camelContext ; }
Gets the camel context either explicitly set before or default context from Spring application context .
28,120
private void replaceHeaders ( final Message from , final Message to ) { to . getHeaders ( ) . clear ( ) ; to . getHeaders ( ) . putAll ( from . getHeaders ( ) ) ; }
Replaces all headers
28,121
protected SoapAttachment findAttachment ( SoapMessage soapMessage , SoapAttachment controlAttachment ) { List < SoapAttachment > attachments = soapMessage . getAttachments ( ) ; Attachment matching = null ; if ( controlAttachment . getContentId ( ) == null ) { if ( attachments . size ( ) == 1 ) { matching = attachments . get ( 0 ) ; } else { throw new ValidationException ( "Found more than one SOAP attachment - need control attachment content id for validation!" ) ; } } else { for ( Attachment attachment : attachments ) { if ( controlAttachment . getContentId ( ) != null && controlAttachment . getContentId ( ) . equals ( attachment . getContentId ( ) ) ) { matching = attachment ; } } } if ( matching != null ) { return SoapAttachment . from ( matching ) ; } else { throw new ValidationException ( String . format ( "Unable to find SOAP attachment with content id '%s'" , controlAttachment . getContentId ( ) ) ) ; } }
Finds attachment in list of soap attachments on incoming soap message . By default uses content id of control attachment as search key . If no proper attachment with this content id was found in soap message throws validation exception .
28,122
protected void validateAttachmentContentId ( SoapAttachment receivedAttachment , SoapAttachment controlAttachment ) { if ( ! StringUtils . hasText ( controlAttachment . getContentId ( ) ) ) { return ; } if ( receivedAttachment . getContentId ( ) != null ) { Assert . isTrue ( controlAttachment . getContentId ( ) != null , buildValidationErrorMessage ( "Values not equal for attachment contentId" , null , receivedAttachment . getContentId ( ) ) ) ; Assert . isTrue ( receivedAttachment . getContentId ( ) . equals ( controlAttachment . getContentId ( ) ) , buildValidationErrorMessage ( "Values not equal for attachment contentId" , controlAttachment . getContentId ( ) , receivedAttachment . getContentId ( ) ) ) ; } else { Assert . isTrue ( controlAttachment . getContentId ( ) == null || controlAttachment . getContentId ( ) . length ( ) == 0 , buildValidationErrorMessage ( "Values not equal for attachment contentId" , controlAttachment . getContentId ( ) , null ) ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Validating attachment contentId: " + receivedAttachment . getContentId ( ) + "='" + controlAttachment . getContentId ( ) + "': OK." ) ; } }
Validating SOAP attachment content id .
28,123
protected void validateAttachmentContentType ( SoapAttachment receivedAttachment , SoapAttachment controlAttachment ) { if ( ! StringUtils . hasText ( controlAttachment . getContentType ( ) ) ) { return ; } if ( receivedAttachment . getContentType ( ) != null ) { Assert . isTrue ( controlAttachment . getContentType ( ) != null , buildValidationErrorMessage ( "Values not equal for attachment contentType" , null , receivedAttachment . getContentType ( ) ) ) ; Assert . isTrue ( receivedAttachment . getContentType ( ) . equals ( controlAttachment . getContentType ( ) ) , buildValidationErrorMessage ( "Values not equal for attachment contentType" , controlAttachment . getContentType ( ) , receivedAttachment . getContentType ( ) ) ) ; } else { Assert . isTrue ( controlAttachment . getContentType ( ) == null || controlAttachment . getContentType ( ) . length ( ) == 0 , buildValidationErrorMessage ( "Values not equal for attachment contentType" , controlAttachment . getContentType ( ) , null ) ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Validating attachment contentType: " + receivedAttachment . getContentType ( ) + "='" + controlAttachment . getContentType ( ) + "': OK." ) ; } }
Validating SOAP attachment content type .
28,124
public static String replaceDynamicNamespaces ( String expression , Map < String , String > namespaces ) { String expressionResult = expression ; for ( Entry < String , String > namespaceEntry : namespaces . entrySet ( ) ) { if ( expressionResult . contains ( DYNAMIC_NS_START + namespaceEntry . getValue ( ) + DYNAMIC_NS_END ) ) { expressionResult = expressionResult . replaceAll ( "\\" + DYNAMIC_NS_START + namespaceEntry . getValue ( ) . replace ( "." , "\\." ) + "\\" + DYNAMIC_NS_END , namespaceEntry . getKey ( ) + ":" ) ; } } return expressionResult ; }
Replaces all dynamic namespaces in a XPath expression with respective prefixes in namespace map .
28,125
public static Object evaluate ( Node node , String xPathExpression , NamespaceContext nsContext , XPathExpressionResult resultType ) { if ( resultType . equals ( XPathExpressionResult . NODE ) ) { Node resultNode = evaluateAsNode ( node , xPathExpression , nsContext ) ; if ( resultNode . getNodeType ( ) == Node . ELEMENT_NODE ) { if ( resultNode . getFirstChild ( ) != null ) { return resultNode . getFirstChild ( ) . getNodeValue ( ) ; } else { return "" ; } } else { return resultNode . getNodeValue ( ) ; } } else if ( resultType . equals ( XPathExpressionResult . NODESET ) ) { NodeList resultNodeList = evaluateAsNodeList ( node , xPathExpression , nsContext ) ; List < String > values = new ArrayList < > ( ) ; for ( int i = 0 ; i < resultNodeList . getLength ( ) ; i ++ ) { Node resultNode = resultNodeList . item ( i ) ; if ( resultNode . getNodeType ( ) == Node . ELEMENT_NODE ) { if ( resultNode . getFirstChild ( ) != null ) { values . add ( resultNode . getFirstChild ( ) . getNodeValue ( ) ) ; } else { values . add ( "" ) ; } } else { values . add ( resultNode . getNodeValue ( ) ) ; } } return values ; } else if ( resultType . equals ( XPathExpressionResult . STRING ) ) { return evaluateAsString ( node , xPathExpression , nsContext ) ; } else { Object result = evaluateAsObject ( node , xPathExpression , nsContext , resultType . getAsQName ( ) ) ; if ( result == null ) { throw new CitrusRuntimeException ( "No result for XPath expression: '" + xPathExpression + "'" ) ; } if ( resultType . equals ( XPathExpressionResult . INTEGER ) ) { return ( int ) Math . round ( ( Double ) result ) ; } return result ; } }
Evaluate XPath expression as String result type regardless what actual result type the expression will evaluate to .
28,126
public static Node evaluateAsNode ( Node node , String xPathExpression , NamespaceContext nsContext ) { Node result = ( Node ) evaluateExpression ( node , xPathExpression , nsContext , XPathConstants . NODE ) ; if ( result == null ) { throw new CitrusRuntimeException ( "No result for XPath expression: '" + xPathExpression + "'" ) ; } return result ; }
Evaluate XPath expression with result type Node .
28,127
public static NodeList evaluateAsNodeList ( Node node , String xPathExpression , NamespaceContext nsContext ) { NodeList result = ( NodeList ) evaluateExpression ( node , xPathExpression , nsContext , XPathConstants . NODESET ) ; if ( result == null ) { throw new CitrusRuntimeException ( "No result for XPath expression: '" + xPathExpression + "'" ) ; } return result ; }
Evaluate XPath expression with result type NodeList .
28,128
public static String evaluateAsString ( Node node , String xPathExpression , NamespaceContext nsContext ) { String result = ( String ) evaluateExpression ( node , xPathExpression , nsContext , XPathConstants . STRING ) ; if ( ! StringUtils . hasText ( result ) ) { evaluateAsNode ( node , xPathExpression , nsContext ) ; } return result ; }
Evaluate XPath expression with result type String .
28,129
public static Boolean evaluateAsBoolean ( Node node , String xPathExpression , NamespaceContext nsContext ) { return ( Boolean ) evaluateExpression ( node , xPathExpression , nsContext , XPathConstants . BOOLEAN ) ; }
Evaluate XPath expression with result type Boolean value .
28,130
public static Double evaluateAsNumber ( Node node , String xPathExpression , NamespaceContext nsContext ) { return ( Double ) evaluateExpression ( node , xPathExpression , nsContext , XPathConstants . NUMBER ) ; }
Evaluate XPath expression with result type Number .
28,131
public static Object evaluateAsObject ( Node node , String xPathExpression , NamespaceContext nsContext , QName resultType ) { return evaluateExpression ( node , xPathExpression , nsContext , resultType ) ; }
Evaluate XPath expression .
28,132
private static XPathExpression buildExpression ( String xPathExpression , NamespaceContext nsContext ) throws XPathExpressionException { XPath xpath = createXPathFactory ( ) . newXPath ( ) ; if ( nsContext != null ) { xpath . setNamespaceContext ( nsContext ) ; } return xpath . compile ( xPathExpression ) ; }
Construct a xPath expression instance with given expression string and namespace context . If namespace context is not specified a default context is built from the XML node that is evaluated against .
28,133
public static Object evaluateExpression ( Node node , String xPathExpression , NamespaceContext nsContext , QName returnType ) { try { return buildExpression ( xPathExpression , nsContext ) . evaluate ( node , returnType ) ; } catch ( XPathExpressionException e ) { throw new CitrusRuntimeException ( "Can not evaluate xpath expression '" + xPathExpression + "'" , e ) ; } }
Evaluates the expression .
28,134
private synchronized static XPathFactory createXPathFactory ( ) { XPathFactory factory = null ; Properties properties = System . getProperties ( ) ; for ( Map . Entry < Object , Object > prop : properties . entrySet ( ) ) { String key = ( String ) prop . getKey ( ) ; if ( key . startsWith ( XPathFactory . DEFAULT_PROPERTY_NAME ) ) { String uri = key . indexOf ( ":" ) > 0 ? key . substring ( key . indexOf ( ":" ) + 1 ) : null ; if ( uri != null ) { try { factory = XPathFactory . newInstance ( uri ) ; } catch ( XPathFactoryConfigurationException e ) { log . warn ( "Failed to instantiate xpath factory" , e ) ; factory = XPathFactory . newInstance ( ) ; } log . info ( "Created xpath factory {} using system property {} with value {}" , factory , key , uri ) ; } } } if ( factory == null ) { factory = XPathFactory . newInstance ( ) ; log . info ( "Created default xpath factory {}" , factory ) ; } return factory ; }
Creates new xpath factory which is not thread safe per definition .
28,135
public Registry getRegistry ( ) throws RemoteException { if ( registry == null ) { if ( StringUtils . hasText ( host ) ) { registry = LocateRegistry . getRegistry ( host , port ) ; } else { registry = LocateRegistry . getRegistry ( port ) ; } } return registry ; }
Gets the RMI registry based on host and port settings in this configuration .
28,136
public File [ ] build ( ) { MavenStrategyStage maven = Maven . configureResolver ( ) . workOffline ( offline ) . resolve ( artifactCoordinates ) ; return applyTransitivity ( maven ) . asFile ( ) ; }
Resolve artifacts for given coordinates .
28,137
public CitrusArchiveBuilder all ( ) { core ( ) ; jms ( ) ; kafka ( ) ; jdbc ( ) ; http ( ) ; websocket ( ) ; ws ( ) ; ssh ( ) ; ftp ( ) ; mail ( ) ; camel ( ) ; vertx ( ) ; docker ( ) ; kubernetes ( ) ; selenium ( ) ; cucumber ( ) ; zookeeper ( ) ; rmi ( ) ; jmx ( ) ; restdocs ( ) ; javaDsl ( ) ; return this ; }
Gets the complete Citrus stack as resolved Maven dependency set .
28,138
private void createReportFile ( String reportFileName , String content ) { File targetDirectory = new File ( getReportDirectory ( ) ) ; if ( ! targetDirectory . exists ( ) ) { if ( ! targetDirectory . mkdirs ( ) ) { throw new CitrusRuntimeException ( "Unable to create report output directory: " + getReportDirectory ( ) ) ; } } try ( Writer fileWriter = new FileWriter ( new File ( targetDirectory , reportFileName ) ) ) { fileWriter . append ( content ) ; fileWriter . flush ( ) ; log . info ( "Generated test report: " + targetDirectory + File . separator + reportFileName ) ; } catch ( IOException e ) { log . error ( "Failed to create test report" , e ) ; } }
Creates the HTML report file
28,139
private void verifyPage ( String pageId ) { if ( ! pages . containsKey ( pageId ) ) { throw new CitrusRuntimeException ( String . format ( "Unknown page '%s' - please introduce page with type information first" , pageId ) ) ; } }
Verify that page is known .
28,140
public static < T extends CitrusAppConfiguration > T apply ( T configuration , String [ ] arguments ) { LinkedList < String > args = new LinkedList < > ( Arrays . asList ( arguments ) ) ; CitrusAppOptions options = new CitrusAppOptions ( ) ; while ( ! args . isEmpty ( ) ) { String arg = args . removeFirst ( ) ; for ( CliOption option : options . options ) { if ( option . processOption ( configuration , arg , args ) ) { break ; } } } return configuration ; }
Apply options based on given argument line .
28,141
private void parseMappingDefinitions ( BeanDefinitionBuilder builder , Element element ) { HashMap < String , String > mappings = new HashMap < String , String > ( ) ; for ( Element matcher : DomUtils . getChildElementsByTagName ( element , "mapping" ) ) { mappings . put ( matcher . getAttribute ( "path" ) , matcher . getAttribute ( "value" ) ) ; } if ( ! mappings . isEmpty ( ) ) { builder . addPropertyValue ( "mappings" , mappings ) ; } }
Parses all mapping definitions and adds those to the bean definition builder as property value .
28,142
private String getJUnitReportsFolder ( ) { if ( ClassUtils . isPresent ( "org.testng.annotations.Test" , getClass ( ) . getClassLoader ( ) ) ) { return "test-output" + File . separator + "junitreports" ; } else if ( ClassUtils . isPresent ( "org.junit.Test" , getClass ( ) . getClassLoader ( ) ) ) { JUnitReporter jUnitReporter = new JUnitReporter ( ) ; return jUnitReporter . getReportDirectory ( ) + File . separator + jUnitReporter . getOutputDirectory ( ) ; } else { return new LoggingReporter ( ) . getReportDirectory ( ) ; } }
Find reports folder based in unit testing framework present on classpath .
28,143
public io . fabric8 . kubernetes . client . KubernetesClient getKubernetesClient ( ) { if ( kubernetesClient == null ) { kubernetesClient = createKubernetesClient ( ) ; } return kubernetesClient ; }
Constructs or gets the kubernetes client implementation .
28,144
private String getLogoImageData ( ) { ByteArrayOutputStream os = new ByteArrayOutputStream ( ) ; BufferedInputStream reader = null ; try { reader = new BufferedInputStream ( FileUtils . getFileResource ( logo ) . getInputStream ( ) ) ; byte [ ] contents = new byte [ 1024 ] ; while ( reader . read ( contents ) != - 1 ) { os . write ( contents ) ; } } catch ( IOException e ) { log . warn ( "Failed to add logo image data to HTML report" , e ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException ex ) { log . warn ( "Failed to close logo image resource for HTML report" , ex ) ; } } try { os . flush ( ) ; } catch ( IOException ex ) { log . warn ( "Failed to flush logo image stream for HTML report" , ex ) ; } } return Base64 . encodeBase64String ( os . toByteArray ( ) ) ; }
Reads citrus logo png image and converts to base64 encoded string for inline HTML image display .
28,145
private String getCodeSnippetHtml ( Throwable cause ) { StringBuilder codeSnippet = new StringBuilder ( ) ; BufferedReader reader = null ; try { if ( cause instanceof CitrusRuntimeException ) { CitrusRuntimeException ex = ( CitrusRuntimeException ) cause ; if ( ! ex . getFailureStack ( ) . isEmpty ( ) ) { FailureStackElement stackElement = ex . getFailureStack ( ) . pop ( ) ; if ( stackElement . getLineNumberStart ( ) > 0 ) { reader = new BufferedReader ( new FileReader ( new ClassPathResource ( stackElement . getTestFilePath ( ) + ".xml" ) . getFile ( ) ) ) ; codeSnippet . append ( "<div class=\"code-snippet\">" ) ; codeSnippet . append ( "<h2 class=\"code-title\">" + stackElement . getTestFilePath ( ) + ".xml</h2>" ) ; String line ; String codeStyle ; int lineIndex = 1 ; int snippetOffset = 5 ; while ( ( line = reader . readLine ( ) ) != null ) { if ( lineIndex >= stackElement . getLineNumberStart ( ) - snippetOffset && lineIndex < stackElement . getLineNumberStart ( ) || lineIndex > stackElement . getLineNumberEnd ( ) && lineIndex <= stackElement . getLineNumberEnd ( ) + snippetOffset ) { codeStyle = "code" ; } else if ( lineIndex >= stackElement . getLineNumberStart ( ) && lineIndex <= stackElement . getLineNumberEnd ( ) ) { codeStyle = "code-failed" ; } else { codeStyle = "" ; } if ( StringUtils . hasText ( codeStyle ) ) { codeSnippet . append ( "<pre class=\"" + codeStyle + "\"><span class=\"line-number\">" + lineIndex + ":</span>" + line . replaceAll ( ">" , "&gt;" ) . replaceAll ( "<" , "&lt;" ) + "</pre>" ) ; } lineIndex ++ ; } codeSnippet . append ( "</div>" ) ; } } } } catch ( IOException e ) { log . error ( "Failed to construct HTML code snippet" , e ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException e ) { log . warn ( "Failed to close test file" , e ) ; } } } return codeSnippet . toString ( ) ; }
Gets the code section from test case XML which is responsible for the error .
28,146
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 .
28,147
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 .
28,148
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 .
28,149
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 .
28,150
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 .
28,151
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 .
28,152
private void doElement ( Node received , Node source , XmlMessageValidationContext validationContext , NamespaceContext namespaceContext , TestContext context ) { doElementNameValidation ( received , source ) ; doElementNamespaceValidation ( received , source ) ; if ( XmlValidationUtils . isElementIgnored ( source , received , validationContext . getIgnoreExpressions ( ) , namespaceContext ) ) { return ; } 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 ) ; } if ( isValidationMatcherExpression ( source ) ) { ValidationMatcherUtils . resolveValidationMatcher ( source . getNodeName ( ) , received . getFirstChild ( ) . getNodeValue ( ) . trim ( ) , source . getFirstChild ( ) . getNodeValue ( ) . trim ( ) , context ) ; return ; } doText ( ( Element ) received , ( Element ) source ) ; 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 .
28,153
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 .
28,154
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 .
28,155
private void doNamespaceQualifiedAttributeValidation ( Node receivedElement , Node receivedAttribute , Node sourceElement , Node sourceAttribute ) { String receivedValue = receivedAttribute . getNodeValue ( ) ; String sourceValue = sourceAttribute . getNodeValue ( ) ; if ( receivedValue . contains ( ":" ) && sourceValue . contains ( ":" ) ) { 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 ) ) ) ; 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 .
28,156
private void doPI ( Node received ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Ignored processing instruction (" + received . getLocalName ( ) + "=" + received . getNodeValue ( ) + ")" ) ; } }
Handle processing instruction during validation .
28,157
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 ; } }
Checks whether the given node contains a validation matcher
28,158
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 .
28,159
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 .
28,160
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 .
28,161
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
28,162
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 .
28,163
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 .
28,164
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 .
28,165
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 .
28,166
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 .
28,167
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 .
28,168
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 .
28,169
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 .
28,170
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 .
28,171
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 .
28,172
public SoapServerRequestActionBuilder receive ( ) { SoapServerRequestActionBuilder soapServerRequestActionBuilder = new SoapServerRequestActionBuilder ( action , soapServer ) . withApplicationContext ( applicationContext ) ; return soapServerRequestActionBuilder ; }
Generic request builder for receiving SOAP messages on server .
28,173
public SoapServerResponseActionBuilder send ( ) { SoapServerResponseActionBuilder soapServerResponseActionBuilder = new SoapServerResponseActionBuilder ( action , soapServer ) . withApplicationContext ( applicationContext ) ; return soapServerResponseActionBuilder ; }
Generic response builder for sending SOAP response messages to client .
28,174
public SoapServerFaultResponseActionBuilder sendFault ( ) { SoapServerFaultResponseActionBuilder soapServerResponseActionBuilder = new SoapServerFaultResponseActionBuilder ( action , soapServer ) . withApplicationContext ( applicationContext ) ; return soapServerResponseActionBuilder ; }
Generic response builder for sending SOAP fault messages to client .
28,175
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 .
28,176
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 .
28,177
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 .
28,178
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 .
28,179
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 .
28,180
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
28,181
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 .
28,182
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 ) ) { 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 .
28,183
public static Map < String , String > lookupNamespaces ( String xml ) { Map < String , String > namespaces = new HashMap < String , String > ( ) ; 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 { 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 ) { 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 .
28,184
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 .
28,185
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 Charset . forName ( "UTF-8" ) ; }
Try to find encoding for document node . Also supports Citrus default encoding set as System property .
28,186
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 ) ; } String payload = messagePayload . trim ( ) ; char doubleQuote = '\"' ; char singleQuote = '\'' ; String encodingKey = "encoding" ; if ( payload . startsWith ( "<?xml" ) && payload . contains ( encodingKey ) && payload . contains ( "?>" ) && ( payload . indexOf ( encodingKey ) < payload . indexOf ( "?>" ) ) ) { String encoding = payload . substring ( payload . indexOf ( encodingKey ) + encodingKey . length ( ) , payload . indexOf ( "?>" ) ) ; char quoteChar = doubleQuote ; int idxDoubleQuote = encoding . indexOf ( doubleQuote ) ; int idxSingleQuote = encoding . indexOf ( singleQuote ) ; if ( idxSingleQuote >= 0 && ( idxDoubleQuote < 0 || idxSingleQuote < idxDoubleQuote ) ) { quoteChar = singleQuote ; } encoding = encoding . substring ( encoding . indexOf ( quoteChar ) + 1 ) ; encoding = encoding . substring ( 0 , encoding . indexOf ( quoteChar ) ) ; if ( ! Charset . availableCharsets ( ) . containsKey ( encoding ) ) { throw new UnsupportedEncodingException ( "Found unsupported encoding: '" + encoding + "'" ) ; } return Charset . forName ( encoding ) ; } return Charset . forName ( "UTF-8" ) ; }
Try to find target encoding in XML declaration .
28,187
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 .
28,188
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 ) { if ( firstSchemaInWSDL != null ) { targetXsd = firstSchemaInWSDL ; } else if ( ! CollectionUtils . isEmpty ( schemaResources ) ) { targetXsd = schemaResources . get ( 0 ) ; } } return targetXsd ; }
Loads nested schema type definitions from wsdl .
28,189
@ 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 { 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 .
28,190
private Definition getWsdlDefinition ( Resource wsdl ) { try { Definition definition ; if ( wsdl . getURI ( ) . toString ( ) . startsWith ( "jar:" ) ) { 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 .
28,191
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 .
28,192
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 ( ) ) { 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 ( 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 .
28,193
protected boolean isDirectory ( String remoteFilePath ) throws IOException { if ( ! ftpClient . changeWorkingDirectory ( remoteFilePath ) ) { 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 .
28,194
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 .
28,195
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 .
28,196
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 .
28,197
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 .
28,198
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 .
28,199
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 .