idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
28,000
public HttpMessage uri ( final String requestUri ) { setHeader ( DynamicEndpointUriResolver . ENDPOINT_URI_HEADER_NAME , requestUri ) ; setHeader ( HttpMessageHeaders . HTTP_REQUEST_URI , requestUri ) ; return this ; }
Sets the Http request request uri header .
67
11
28,001
public HttpMessage queryParam ( final String name , final String value ) { if ( ! StringUtils . hasText ( name ) ) { throw new CitrusRuntimeException ( "Invalid query param name - must not be empty!" ) ; } this . addQueryParam ( name , value ) ; final String queryParamString = queryParams . entrySet ( ) . stream ( ) . map ( this :: outputQueryParam ) . collect ( Collectors . joining ( "," ) ) ; header ( HttpMessageHeaders . HTTP_QUERY_PARAMS , queryParamString ) ; header ( DynamicEndpointUriResolver . QUERY_PARAM_HEADER_NAME , queryParamString ) ; return this ; }
Sets a new Http request query param .
153
10
28,002
public HttpMessage path ( final String path ) { header ( HttpMessageHeaders . HTTP_REQUEST_URI , path ) ; header ( DynamicEndpointUriResolver . REQUEST_PATH_HEADER_NAME , path ) ; return this ; }
Sets request path that is dynamically added to base uri .
56
13
28,003
public HttpMethod getRequestMethod ( ) { final Object method = getHeader ( HttpMessageHeaders . HTTP_REQUEST_METHOD ) ; if ( method != null ) { return HttpMethod . valueOf ( method . toString ( ) ) ; } return null ; }
Gets the Http request method .
59
8
28,004
public String getUri ( ) { final Object requestUri = getHeader ( HttpMessageHeaders . HTTP_REQUEST_URI ) ; if ( requestUri != null ) { return requestUri . toString ( ) ; } return null ; }
Gets the Http request request uri .
55
10
28,005
public String getContextPath ( ) { final Object contextPath = getHeader ( HttpMessageHeaders . HTTP_CONTEXT_PATH ) ; if ( contextPath != null ) { return contextPath . toString ( ) ; } return null ; }
Gets the Http request context path .
52
9
28,006
public String getContentType ( ) { final Object contentType = getHeader ( HttpMessageHeaders . HTTP_CONTENT_TYPE ) ; if ( contentType != null ) { return contentType . toString ( ) ; } return null ; }
Gets the Http content type header .
52
9
28,007
public String getAccept ( ) { final Object accept = getHeader ( "Accept" ) ; if ( accept != null ) { return accept . toString ( ) ; } return null ; }
Gets the accept header .
39
6
28,008
public String getQueryParamString ( ) { return Optional . ofNullable ( getHeader ( HttpMessageHeaders . HTTP_QUERY_PARAMS ) ) . map ( Object :: toString ) . orElse ( "" ) ; }
Gets the Http request query param string .
50
10
28,009
public HttpStatus getStatusCode ( ) { final Object statusCode = getHeader ( HttpMessageHeaders . HTTP_STATUS_CODE ) ; if ( statusCode != null ) { if ( statusCode instanceof HttpStatus ) { return ( HttpStatus ) statusCode ; } else if ( statusCode instanceof Integer ) { return HttpStatus . valueOf ( ( Integer ) statusCode ) ; } else { return HttpStatus . valueOf ( Integer . valueOf ( statusCode . toString ( ) ) ) ; } } return null ; }
Gets the Http response status code .
119
9
28,010
public String getReasonPhrase ( ) { final Object reasonPhrase = getHeader ( HttpMessageHeaders . HTTP_REASON_PHRASE ) ; if ( reasonPhrase != null ) { return reasonPhrase . toString ( ) ; } return null ; }
Gets the Http response reason phrase .
58
9
28,011
public String getVersion ( ) { final Object version = getHeader ( HttpMessageHeaders . HTTP_VERSION ) ; if ( version != null ) { return version . toString ( ) ; } return null ; }
Gets the Http version .
45
7
28,012
public String getPath ( ) { final Object path = getHeader ( DynamicEndpointUriResolver . REQUEST_PATH_HEADER_NAME ) ; if ( path != null ) { return path . toString ( ) ; } return null ; }
Gets the request path after the context path .
53
10
28,013
public void setCookies ( final Cookie [ ] cookies ) { this . cookies . clear ( ) ; if ( cookies != null ) { for ( final Cookie cookie : cookies ) { cookie ( cookie ) ; } } }
Sets the cookies .
45
5
28,014
public HttpMessage cookie ( final Cookie cookie ) { this . cookies . put ( cookie . getName ( ) , cookie ) ; setHeader ( HttpMessageHeaders . HTTP_COOKIE_PREFIX + cookie . getName ( ) , cookieConverter . getCookieString ( cookie ) ) ; return this ; }
Adds new cookie to this http message .
71
8
28,015
public static HttpMessage fromRequestData ( final String requestData ) { try ( final BufferedReader reader = new BufferedReader ( new StringReader ( requestData ) ) ) { final HttpMessage request = new HttpMessage ( ) ; final String [ ] requestLine = reader . readLine ( ) . split ( "\\s" ) ; if ( requestLine . length > 0 ) { request . method ( HttpMethod . valueOf ( requestLine [ 0 ] ) ) ; } if ( requestLine . length > 1 ) { request . uri ( requestLine [ 1 ] ) ; } if ( requestLine . length > 2 ) { request . version ( requestLine [ 2 ] ) ; } return parseHttpMessage ( reader , request ) ; } catch ( final IOException e ) { throw new CitrusRuntimeException ( "Failed to parse Http raw request data" , e ) ; } }
Reads request from complete request dump .
191
8
28,016
public static HttpMessage fromResponseData ( final String responseData ) { try ( final BufferedReader reader = new BufferedReader ( new StringReader ( responseData ) ) ) { final HttpMessage response = new HttpMessage ( ) ; final String [ ] statusLine = reader . readLine ( ) . split ( "\\s" ) ; if ( statusLine . length > 0 ) { response . version ( statusLine [ 0 ] ) ; } if ( statusLine . length > 1 ) { response . status ( HttpStatus . valueOf ( Integer . valueOf ( statusLine [ 1 ] ) ) ) ; } return parseHttpMessage ( reader , response ) ; } catch ( final IOException e ) { throw new CitrusRuntimeException ( "Failed to parse Http raw response data" , e ) ; } }
Reads response from complete response dump .
174
8
28,017
public void loadPropertiesAsVariables ( ) { BufferedReader reader = null ; try { if ( propertyFilesSet ( ) ) { for ( String propertyFilePath : propertyFiles ) { Resource propertyFile = new PathMatchingResourcePatternResolver ( ) . getResource ( propertyFilePath . trim ( ) ) ; log . debug ( "Reading property file " + propertyFile . getFilename ( ) ) ; // Use input stream as this also allows to read from resources in a JAR file reader = new BufferedReader ( new InputStreamReader ( propertyFile . getInputStream ( ) ) ) ; // local context instance handling variable replacement in property values TestContext context = new TestContext ( ) ; // Careful!! The function registry *must* be set before setting the global variables. // Variables can contain functions which are resolved when context.setGlobalVariables is invoked. context . setFunctionRegistry ( functionRegistry ) ; context . setGlobalVariables ( globalVariables ) ; String propertyExpression ; while ( ( propertyExpression = reader . readLine ( ) ) != null ) { log . debug ( "Property line [ {} ]" , propertyExpression ) ; propertyExpression = propertyExpression . trim ( ) ; if ( ! isPropertyLine ( propertyExpression ) ) { continue ; } String key = propertyExpression . substring ( 0 , propertyExpression . indexOf ( ' ' ) ) . trim ( ) ; String value = propertyExpression . substring ( propertyExpression . indexOf ( ' ' ) + 1 ) . trim ( ) ; log . debug ( "Property value replace dynamic content [ {} ]" , value ) ; value = context . replaceDynamicContentInString ( value ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Loading property: " + key + "=" + value + " into default variables" ) ; } if ( log . isDebugEnabled ( ) && globalVariables . getVariables ( ) . containsKey ( key ) ) { log . debug ( "Overwriting property " + key + " old value:" + globalVariables . getVariables ( ) . get ( key ) + " new value:" + value ) ; } globalVariables . getVariables ( ) . put ( key , value ) ; // we need to keep local context up to date in case of recursive variable usage context . setVariable ( key , globalVariables . getVariables ( ) . get ( key ) ) ; } log . info ( "Loaded property file " + propertyFile . getFilename ( ) ) ; } } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Error while loading property file" , e ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException e ) { log . warn ( "Unable to close property file reader" , e ) ; } } } }
Load the properties as variables .
618
6
28,018
private int invokeUrl ( TestContext context ) { URL contextUrl = getUrl ( context ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Probing Http request url '%s'" , contextUrl . toExternalForm ( ) ) ) ; } int responseCode = - 1 ; HttpURLConnection httpURLConnection = null ; try { httpURLConnection = openConnection ( contextUrl ) ; httpURLConnection . setConnectTimeout ( getTimeout ( context ) ) ; httpURLConnection . setRequestMethod ( context . resolveDynamicValue ( method ) ) ; responseCode = httpURLConnection . getResponseCode ( ) ; } catch ( IOException e ) { log . warn ( String . format ( "Could not access Http url '%s' - %s" , contextUrl . toExternalForm ( ) , e . getMessage ( ) ) ) ; } finally { if ( httpURLConnection != null ) { httpURLConnection . disconnect ( ) ; } } return responseCode ; }
Invokes Http request URL and returns response code .
216
11
28,019
private URL getUrl ( TestContext context ) { try { return new URL ( context . replaceDynamicContentInString ( this . url ) ) ; } catch ( MalformedURLException e ) { throw new CitrusRuntimeException ( "Invalid request url" , e ) ; } }
Gets the request url with test variable support .
60
10
28,020
private SoapFault constructControlFault ( TestContext context ) { SoapFault controlFault = new SoapFault ( ) ; if ( StringUtils . hasText ( faultActor ) ) { controlFault . faultActor ( context . replaceDynamicContentInString ( faultActor ) ) ; } controlFault . faultCode ( context . replaceDynamicContentInString ( faultCode ) ) ; controlFault . faultString ( context . replaceDynamicContentInString ( faultString ) ) ; for ( String faultDetail : faultDetails ) { controlFault . addFaultDetail ( context . replaceDynamicContentInString ( faultDetail ) ) ; } try { for ( String faultDetailPath : faultDetailResourcePaths ) { String resourcePath = context . replaceDynamicContentInString ( faultDetailPath ) ; controlFault . addFaultDetail ( context . replaceDynamicContentInString ( FileUtils . readToString ( FileUtils . getFileResource ( resourcePath , context ) , FileUtils . getCharset ( resourcePath ) ) ) ) ; } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to create SOAP fault detail from file resource" , e ) ; } return controlFault ; }
Constructs the control soap fault holding all expected fault information like faultCode faultString and faultDetail .
274
21
28,021
private KubernetesCommand < ? > getCommandByName ( String commandName ) { if ( ! StringUtils . hasText ( commandName ) ) { throw new CitrusRuntimeException ( "Missing command name property" ) ; } switch ( commandName ) { case "info" : return new Info ( ) ; case "list-events" : return new ListEvents ( ) ; case "list-endpoints" : return new ListEndpoints ( ) ; case "create-pod" : return new CreatePod ( ) ; case "get-pod" : return new GetPod ( ) ; case "delete-pod" : return new DeletePod ( ) ; case "list-pods" : return new ListPods ( ) ; case "watch-pods" : return new WatchPods ( ) ; case "list-namespaces" : return new ListNamespaces ( ) ; case "watch-namespaces" : return new WatchNamespaces ( ) ; case "list-nodes" : return new ListNodes ( ) ; case "watch-nodes" : return new WatchNodes ( ) ; case "list-replication-controllers" : return new ListReplicationControllers ( ) ; case "watch-replication-controllers" : return new WatchReplicationControllers ( ) ; case "create-service" : return new CreateService ( ) ; case "get-service" : return new GetService ( ) ; case "delete-service" : return new DeleteService ( ) ; case "list-services" : return new ListServices ( ) ; case "watch-services" : return new WatchServices ( ) ; default : throw new CitrusRuntimeException ( "Unknown kubernetes command: " + commandName ) ; } }
Creates a new kubernetes command message model object from message headers .
372
16
28,022
private Map < String , Object > createMessageHeaders ( KubernetesCommand < ? > command ) { Map < String , Object > headers = new HashMap < String , Object > ( ) ; headers . put ( KubernetesMessageHeaders . COMMAND , command . getName ( ) ) ; for ( Map . Entry < String , Object > entry : command . getParameters ( ) . entrySet ( ) ) { headers . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } return headers ; }
Reads basic command information and converts to message headers .
114
11
28,023
private Volume [ ] getVolumes ( TestContext context ) { String [ ] volumes = StringUtils . commaDelimitedListToStringArray ( getParameter ( "volumes" , context ) ) ; Volume [ ] volumeSpecs = new Volume [ volumes . length ] ; for ( int i = 0 ; i < volumes . length ; i ++ ) { volumeSpecs [ i ] = new Volume ( volumes [ i ] ) ; } return volumeSpecs ; }
Gets the volume specs from comma delimited string .
98
11
28,024
private Capability [ ] getCapabilities ( String addDrop , TestContext context ) { String [ ] capabilities = StringUtils . commaDelimitedListToStringArray ( getParameter ( addDrop , context ) ) ; Capability [ ] capAdd = new Capability [ capabilities . length ] ; for ( int i = 0 ; i < capabilities . length ; i ++ ) { capAdd [ i ] = Capability . valueOf ( capabilities [ i ] ) ; } return capAdd ; }
Gets the capabilities added .
103
6
28,025
private ExposedPort [ ] getExposedPorts ( String portSpecs , TestContext context ) { String [ ] ports = StringUtils . commaDelimitedListToStringArray ( portSpecs ) ; ExposedPort [ ] exposedPorts = new ExposedPort [ ports . length ] ; for ( int i = 0 ; i < ports . length ; i ++ ) { String portSpec = context . replaceDynamicContentInString ( ports [ i ] ) ; if ( portSpec . startsWith ( "udp:" ) ) { exposedPorts [ i ] = ExposedPort . udp ( Integer . valueOf ( portSpec . substring ( "udp:" . length ( ) ) ) ) ; } else if ( portSpec . startsWith ( "tcp:" ) ) { exposedPorts [ i ] = ExposedPort . tcp ( Integer . valueOf ( portSpec . substring ( "tcp:" . length ( ) ) ) ) ; } else { exposedPorts [ i ] = ExposedPort . tcp ( Integer . valueOf ( portSpec ) ) ; } } return exposedPorts ; }
Construct set of exposed ports from comma delimited list of ports .
238
13
28,026
private Ports getPortBindings ( String portSpecs , ExposedPort [ ] exposedPorts , TestContext context ) { String [ ] ports = StringUtils . commaDelimitedListToStringArray ( portSpecs ) ; Ports portsBindings = new Ports ( ) ; for ( String portSpec : ports ) { String [ ] binding = context . replaceDynamicContentInString ( portSpec ) . split ( ":" ) ; if ( binding . length == 2 ) { Integer hostPort = Integer . valueOf ( binding [ 0 ] ) ; Integer port = Integer . valueOf ( binding [ 1 ] ) ; portsBindings . bind ( Stream . of ( exposedPorts ) . filter ( exposed -> port . equals ( exposed . getPort ( ) ) ) . findAny ( ) . orElse ( ExposedPort . tcp ( port ) ) , Ports . Binding . bindPort ( hostPort ) ) ; } } Stream . of ( exposedPorts ) . filter ( exposed -> ! portsBindings . getBindings ( ) . keySet ( ) . contains ( exposed ) ) . forEach ( exposed -> portsBindings . bind ( exposed , Ports . Binding . empty ( ) ) ) ; return portsBindings ; }
Construct set of port bindings from comma delimited list of ports .
257
13
28,027
private void buildOutMessage ( Exchange exchange , Message message ) { org . apache . camel . Message reply = exchange . getOut ( ) ; for ( Map . Entry < String , Object > header : message . getHeaders ( ) . entrySet ( ) ) { if ( ! header . getKey ( ) . startsWith ( MessageHeaders . PREFIX ) ) { reply . setHeader ( header . getKey ( ) , header . getValue ( ) ) ; } } if ( message . getHeader ( CitrusCamelMessageHeaders . EXCHANGE_EXCEPTION ) != null ) { String exceptionClass = message . getHeader ( CitrusCamelMessageHeaders . EXCHANGE_EXCEPTION ) . toString ( ) ; String exceptionMsg = null ; if ( message . getHeader ( CitrusCamelMessageHeaders . EXCHANGE_EXCEPTION_MESSAGE ) != null ) { exceptionMsg = message . getHeader ( CitrusCamelMessageHeaders . EXCHANGE_EXCEPTION_MESSAGE ) . toString ( ) ; } try { Class < ? > exception = Class . forName ( exceptionClass ) ; if ( exceptionMsg != null ) { exchange . setException ( ( Throwable ) exception . getConstructor ( String . class ) . newInstance ( exceptionMsg ) ) ; } else { exchange . setException ( ( Throwable ) exception . newInstance ( ) ) ; } } catch ( RuntimeException e ) { log . warn ( "Unable to create proper exception instance for exchange!" , e ) ; } catch ( Exception e ) { log . warn ( "Unable to create proper exception instance for exchange!" , e ) ; } } reply . setBody ( message . getPayload ( ) ) ; }
Builds response and sets it as out message on given Camel exchange .
376
14
28,028
protected Message createMessage ( TestContext context , String messageType ) { if ( dataDictionary != null ) { messageBuilder . setDataDictionary ( dataDictionary ) ; } return messageBuilder . buildMessageContent ( context , messageType , MessageDirection . OUTBOUND ) ; }
Create message to be sent .
60
6
28,029
private MBeanServerConnection getNetworkConnection ( ) { try { JMXServiceURL url = new JMXServiceURL ( getEndpointConfiguration ( ) . getServerUrl ( ) ) ; String [ ] creds = { getEndpointConfiguration ( ) . getUsername ( ) , getEndpointConfiguration ( ) . getPassword ( ) } ; JMXConnector networkConnector = JMXConnectorFactory . connect ( url , Collections . singletonMap ( JMXConnector . CREDENTIALS , creds ) ) ; connectionId = networkConnector . getConnectionId ( ) ; networkConnector . addConnectionNotificationListener ( this , null , null ) ; return networkConnector . getMBeanServerConnection ( ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to connect to network MBean server" , e ) ; } }
Establish network connection to remote mBean server .
183
11
28,030
private boolean connectionLost ( JMXConnectionNotification connectionNotification ) { return connectionNotification . getType ( ) . equals ( JMXConnectionNotification . NOTIFS_LOST ) || connectionNotification . getType ( ) . equals ( JMXConnectionNotification . CLOSED ) || connectionNotification . getType ( ) . equals ( JMXConnectionNotification . FAILED ) ; }
Finds connection lost type notifications .
85
7
28,031
public void scheduleReconnect ( ) { Runnable startRunnable = new Runnable ( ) { @ Override public void run ( ) { try { MBeanServerConnection serverConnection = getNetworkConnection ( ) ; if ( notificationListener != null ) { serverConnection . addNotificationListener ( objectName , notificationListener , getEndpointConfiguration ( ) . getNotificationFilter ( ) , getEndpointConfiguration ( ) . getNotificationHandback ( ) ) ; } } catch ( Exception e ) { log . warn ( "Failed to reconnect to JMX MBean server. {}" , e . getMessage ( ) ) ; scheduleReconnect ( ) ; } } } ; log . info ( "Reconnecting to MBean server {} in {} milliseconds." , getEndpointConfiguration ( ) . getServerUrl ( ) , getEndpointConfiguration ( ) . getDelayOnReconnect ( ) ) ; scheduledExecutor . schedule ( startRunnable , getEndpointConfiguration ( ) . getDelayOnReconnect ( ) , TimeUnit . MILLISECONDS ) ; }
Schedules an attempt to re - initialize a lost connection after the reconnect delay
238
16
28,032
private void addNotificationListener ( ObjectName objectName , final String correlationKey , MBeanServerConnection serverConnection ) { try { notificationListener = new NotificationListener ( ) { @ Override public void handleNotification ( Notification notification , Object handback ) { correlationManager . store ( correlationKey , new DefaultMessage ( notification . getMessage ( ) ) ) ; } } ; serverConnection . addNotificationListener ( objectName , notificationListener , getEndpointConfiguration ( ) . getNotificationFilter ( ) , getEndpointConfiguration ( ) . getNotificationHandback ( ) ) ; } catch ( InstanceNotFoundException e ) { throw new CitrusRuntimeException ( "Failed to find object name instance" , e ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to add notification listener" , e ) ; } }
Add notification listener for response messages .
182
7
28,033
public AntRunBuilder targets ( String ... targets ) { action . setTargets ( StringUtils . collectionToCommaDelimitedString ( Arrays . asList ( targets ) ) ) ; return this ; }
Multiple build target names to call .
46
7
28,034
public AntRunBuilder property ( String name , Object value ) { action . getProperties ( ) . put ( name , value ) ; return this ; }
Adds a build property by name and value .
32
9
28,035
private CitrusWebSocketHandler getWebSocketClientHandler ( String url ) { CitrusWebSocketHandler handler = new CitrusWebSocketHandler ( ) ; if ( webSocketHttpHeaders == null ) { webSocketHttpHeaders = new WebSocketHttpHeaders ( ) ; webSocketHttpHeaders . setSecWebSocketExtensions ( Collections . singletonList ( new StandardToWebSocketExtensionAdapter ( new JsrExtension ( new PerMessageDeflateExtension ( ) . getName ( ) ) ) ) ) ; } ListenableFuture < WebSocketSession > future = client . doHandshake ( handler , webSocketHttpHeaders , UriComponentsBuilder . fromUriString ( url ) . buildAndExpand ( ) . encode ( ) . toUri ( ) ) ; try { future . get ( ) ; } catch ( Exception e ) { String errMsg = String . format ( "Failed to connect to Web Socket server - '%s'" , url ) ; LOG . error ( errMsg ) ; throw new CitrusRuntimeException ( errMsg ) ; } return handler ; }
Creates new client web socket handler by opening a new socket connection to server .
232
16
28,036
public static void main ( String [ ] args ) { CitrusApp citrusApp = new CitrusApp ( args ) ; if ( citrusApp . configuration . getTimeToLive ( ) > 0 ) { CompletableFuture . runAsync ( ( ) -> { try { new CompletableFuture < Void > ( ) . get ( citrusApp . configuration . getTimeToLive ( ) , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException | ExecutionException | TimeoutException e ) { log . info ( String . format ( "Shutdown Citrus application after %s ms" , citrusApp . configuration . getTimeToLive ( ) ) ) ; citrusApp . stop ( ) ; } } ) ; } if ( citrusApp . configuration . isSkipTests ( ) ) { if ( citrusApp . configuration . getConfigClass ( ) != null ) { Citrus . newInstance ( citrusApp . configuration . getConfigClass ( ) ) ; } else { Citrus . newInstance ( ) ; } setDefaultProperties ( citrusApp . configuration ) ; } else { try { citrusApp . run ( ) ; } finally { if ( citrusApp . configuration . getTimeToLive ( ) == 0 ) { citrusApp . stop ( ) ; } } } if ( citrusApp . configuration . isSystemExit ( ) ) { if ( citrusApp . waitForCompletion ( ) ) { System . exit ( 0 ) ; } else { System . exit ( - 1 ) ; } } else { citrusApp . waitForCompletion ( ) ; } }
Main method with command line arguments .
328
7
28,037
public void run ( ) { if ( isCompleted ( ) ) { log . info ( "Not executing tests as application state is completed!" ) ; return ; } log . info ( String . format ( "Running Citrus %s" , Citrus . getVersion ( ) ) ) ; setDefaultProperties ( configuration ) ; if ( ClassUtils . isPresent ( "org.testng.annotations.Test" , getClass ( ) . getClassLoader ( ) ) ) { new TestNGEngine ( configuration ) . run ( ) ; } else if ( ClassUtils . isPresent ( "org.junit.Test" , getClass ( ) . getClassLoader ( ) ) ) { new JUnit4TestEngine ( configuration ) . run ( ) ; } }
Run application with prepared Citrus instance .
162
8
28,038
private void stop ( ) { complete ( ) ; Citrus citrus = Citrus . CitrusInstanceManager . getSingleton ( ) ; if ( citrus != null ) { log . info ( "Closing Citrus and its application context" ) ; citrus . close ( ) ; } }
Stop application by setting completed state and stop application context .
59
11
28,039
private static void setDefaultProperties ( CitrusAppConfiguration configuration ) { for ( Map . Entry < String , String > entry : configuration . getDefaultProperties ( ) . entrySet ( ) ) { log . debug ( String . format ( "Setting application property %s=%s" , entry . getKey ( ) , entry . getValue ( ) ) ) ; System . setProperty ( entry . getKey ( ) , Optional . ofNullable ( entry . getValue ( ) ) . orElse ( "" ) ) ; } }
Reads default properties in configuration and sets them as system properties .
112
13
28,040
protected void executeStatements ( TestContext context ) { for ( String stmt : statements ) { try { final String toExecute = context . replaceDynamicContentInString ( stmt . trim ( ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Executing PLSQL statement: " + toExecute ) ; } getJdbcTemplate ( ) . execute ( toExecute ) ; log . info ( "PLSQL statement execution successful" ) ; } catch ( DataAccessException e ) { if ( ignoreErrors ) { log . warn ( "Ignoring error while executing PLSQL statement: " + e . getMessage ( ) ) ; continue ; } else { throw new CitrusRuntimeException ( "Failed to execute PLSQL statement" , e ) ; } } } }
Run all PLSQL statements .
174
7
28,041
private List < String > createStatementsFromScript ( TestContext context ) { List < String > stmts = new ArrayList <> ( ) ; script = context . replaceDynamicContentInString ( script ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Found inline PLSQL script " + script ) ; } StringTokenizer tok = new StringTokenizer ( script , PLSQL_STMT_ENDING ) ; while ( tok . hasMoreTokens ( ) ) { String next = tok . nextToken ( ) . trim ( ) ; if ( StringUtils . hasText ( next ) ) { stmts . add ( next ) ; } } return stmts ; }
Create SQL statements from inline script .
154
7
28,042
public static RmiServiceInvocation create ( Object remoteTarget , Method method , Object [ ] args ) { RmiServiceInvocation serviceInvocation = new RmiServiceInvocation ( ) ; if ( Proxy . isProxyClass ( remoteTarget . getClass ( ) ) ) { serviceInvocation . setRemote ( method . getDeclaringClass ( ) . getName ( ) ) ; } else { serviceInvocation . setRemote ( remoteTarget . getClass ( ) . getName ( ) ) ; } serviceInvocation . setMethod ( method . getName ( ) ) ; if ( args != null ) { serviceInvocation . setArgs ( new RmiServiceInvocation . Args ( ) ) ; for ( Object arg : args ) { MethodArg methodArg = new MethodArg ( ) ; methodArg . setValueObject ( arg ) ; if ( Map . class . isAssignableFrom ( arg . getClass ( ) ) ) { methodArg . setType ( Map . class . getName ( ) ) ; } else if ( List . class . isAssignableFrom ( arg . getClass ( ) ) ) { methodArg . setType ( List . class . getName ( ) ) ; } else { methodArg . setType ( arg . getClass ( ) . getName ( ) ) ; } serviceInvocation . getArgs ( ) . getArgs ( ) . add ( methodArg ) ; } } return serviceInvocation ; }
Static create method from target object and method definition .
303
10
28,043
public Class [ ] getArgTypes ( ) { List < Class > types = new ArrayList <> ( ) ; if ( args != null ) { for ( MethodArg arg : args . getArgs ( ) ) { try { types . add ( Class . forName ( arg . getType ( ) ) ) ; } catch ( ClassNotFoundException e ) { throw new CitrusRuntimeException ( "Failed to access method argument type" , e ) ; } } } return types . toArray ( new Class [ types . size ( ) ] ) ; }
Gets the argument types from list of args .
116
10
28,044
public Object [ ] getArgValues ( ApplicationContext applicationContext ) { List < Object > argValues = new ArrayList <> ( ) ; try { if ( args != null ) { for ( MethodArg methodArg : args . getArgs ( ) ) { Class argType = Class . forName ( methodArg . getType ( ) ) ; Object value = null ; if ( methodArg . getValueObject ( ) != null ) { value = methodArg . getValueObject ( ) ; } else if ( methodArg . getValue ( ) != null ) { value = methodArg . getValue ( ) ; } else if ( StringUtils . hasText ( methodArg . getRef ( ) ) && applicationContext != null ) { value = applicationContext . getBean ( methodArg . getRef ( ) ) ; } if ( value == null ) { argValues . add ( null ) ; } else if ( argType . isInstance ( value ) || argType . isAssignableFrom ( value . getClass ( ) ) ) { argValues . add ( argType . cast ( value ) ) ; } else if ( Map . class . equals ( argType ) ) { String mapString = value . toString ( ) ; Properties props = new Properties ( ) ; try { props . load ( new StringReader ( mapString . substring ( 1 , mapString . length ( ) - 1 ) . replace ( ", " , "\n" ) ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to reconstruct method argument of type map" , e ) ; } Map < String , String > map = new LinkedHashMap <> ( ) ; for ( Map . Entry < Object , Object > entry : props . entrySet ( ) ) { map . put ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) . toString ( ) ) ; } argValues . add ( map ) ; } else { try { argValues . add ( new SimpleTypeConverter ( ) . convertIfNecessary ( value , argType ) ) ; } catch ( ConversionNotSupportedException e ) { if ( String . class . equals ( argType ) ) { argValues . add ( value . toString ( ) ) ; } throw e ; } } } } } catch ( ClassNotFoundException e ) { throw new CitrusRuntimeException ( "Failed to construct method arg objects" , e ) ; } return argValues . toArray ( new Object [ argValues . size ( ) ] ) ; }
Gets method args as objects . Automatically converts simple types and ready referenced beans .
540
17
28,045
private BeanDefinitionBuilder parseSqlAction ( Element element ) { BeanDefinitionBuilder beanDefinition = BeanDefinitionBuilder . rootBeanDefinition ( ExecuteSQLAction . class ) ; String ignoreErrors = element . getAttribute ( "ignore-errors" ) ; if ( ignoreErrors != null && ignoreErrors . equals ( "true" ) ) { beanDefinition . addPropertyValue ( "ignoreErrors" , true ) ; } return beanDefinition ; }
Parses SQL action just executing a set of statements .
95
12
28,046
private BeanDefinitionBuilder parseSqlQueryAction ( Element element , Element scriptValidationElement , List < Element > validateElements , List < Element > extractElements ) { BeanDefinitionBuilder beanDefinition = BeanDefinitionBuilder . rootBeanDefinition ( ExecuteSQLQueryAction . class ) ; // check for script validation if ( scriptValidationElement != null ) { beanDefinition . addPropertyValue ( "scriptValidationContext" , getScriptValidationContext ( scriptValidationElement ) ) ; } Map < String , List < String > > controlResultSet = new HashMap < String , List < String > > ( ) ; for ( Iterator < ? > iter = validateElements . iterator ( ) ; iter . hasNext ( ) ; ) { Element validateElement = ( Element ) iter . next ( ) ; Element valueListElement = DomUtils . getChildElementByTagName ( validateElement , "values" ) ; if ( valueListElement != null ) { List < String > valueList = new ArrayList < String > ( ) ; List < ? > valueElements = DomUtils . getChildElementsByTagName ( valueListElement , "value" ) ; for ( Iterator < ? > valueElementsIt = valueElements . iterator ( ) ; valueElementsIt . hasNext ( ) ; ) { Element valueElement = ( Element ) valueElementsIt . next ( ) ; valueList . add ( DomUtils . getTextValue ( valueElement ) ) ; } controlResultSet . put ( validateElement . getAttribute ( "column" ) , valueList ) ; } else if ( validateElement . hasAttribute ( "value" ) ) { controlResultSet . put ( validateElement . getAttribute ( "column" ) , Collections . singletonList ( validateElement . getAttribute ( "value" ) ) ) ; } else { throw new BeanCreationException ( element . getLocalName ( ) , "Neither value attribute nor value list is set for column validation: " + validateElement . getAttribute ( "column" ) ) ; } } beanDefinition . addPropertyValue ( "controlResultSet" , controlResultSet ) ; Map < String , String > extractVariables = new HashMap < String , String > ( ) ; for ( Iterator < ? > iter = extractElements . iterator ( ) ; iter . hasNext ( ) ; ) { Element validate = ( Element ) iter . next ( ) ; extractVariables . put ( validate . getAttribute ( "column" ) , validate . getAttribute ( "variable" ) ) ; } beanDefinition . addPropertyValue ( "extractVariables" , extractVariables ) ; return beanDefinition ; }
Parses SQL query action with result set validation elements .
563
12
28,047
private ScriptValidationContext getScriptValidationContext ( Element scriptElement ) { String type = scriptElement . getAttribute ( "type" ) ; ScriptValidationContext validationContext = new ScriptValidationContext ( type ) ; String filePath = scriptElement . getAttribute ( "file" ) ; if ( StringUtils . hasText ( filePath ) ) { validationContext . setValidationScriptResourcePath ( filePath ) ; } else { validationContext . setValidationScript ( DomUtils . getTextValue ( scriptElement ) ) ; } return validationContext ; }
Constructs the script validation context .
119
7
28,048
public void stop ( ) { try { if ( CollectionUtils . isEmpty ( consumer . subscription ( ) ) ) { consumer . unsubscribe ( ) ; } } finally { consumer . close ( Duration . ofMillis ( 10 * 1000L ) ) ; } }
Stop message listener container .
55
5
28,049
private org . apache . kafka . clients . consumer . KafkaConsumer < Object , Object > createConsumer ( ) { Map < String , Object > consumerProps = new HashMap <> ( ) ; consumerProps . put ( ConsumerConfig . CLIENT_ID_CONFIG , Optional . ofNullable ( endpointConfiguration . getClientId ( ) ) . orElse ( KafkaMessageHeaders . KAFKA_PREFIX + "consumer_" + UUID . randomUUID ( ) . toString ( ) ) ) ; consumerProps . put ( ConsumerConfig . GROUP_ID_CONFIG , endpointConfiguration . getConsumerGroup ( ) ) ; consumerProps . put ( ConsumerConfig . BOOTSTRAP_SERVERS_CONFIG , Optional . ofNullable ( endpointConfiguration . getServer ( ) ) . orElse ( "localhost:9092" ) ) ; consumerProps . put ( ConsumerConfig . MAX_POLL_RECORDS_CONFIG , 1 ) ; consumerProps . put ( ConsumerConfig . ENABLE_AUTO_COMMIT_CONFIG , endpointConfiguration . isAutoCommit ( ) ) ; consumerProps . put ( ConsumerConfig . AUTO_COMMIT_INTERVAL_MS_CONFIG , endpointConfiguration . getAutoCommitInterval ( ) ) ; consumerProps . put ( ConsumerConfig . AUTO_OFFSET_RESET_CONFIG , endpointConfiguration . getOffsetReset ( ) ) ; consumerProps . put ( ConsumerConfig . KEY_DESERIALIZER_CLASS_CONFIG , endpointConfiguration . getKeyDeserializer ( ) ) ; consumerProps . put ( ConsumerConfig . VALUE_DESERIALIZER_CLASS_CONFIG , endpointConfiguration . getValueDeserializer ( ) ) ; consumerProps . putAll ( endpointConfiguration . getConsumerProperties ( ) ) ; return new org . apache . kafka . clients . consumer . KafkaConsumer <> ( consumerProps ) ; }
Create new Kafka consumer with given endpoint configuration .
424
9
28,050
public void setConsumer ( org . apache . kafka . clients . consumer . KafkaConsumer < Object , Object > consumer ) { this . consumer = consumer ; }
Sets the consumer .
35
5
28,051
public TemplateBuilder load ( ApplicationContext applicationContext ) { Template rootTemplate = applicationContext . getBean ( action . getName ( ) , Template . class ) ; action . setGlobalContext ( rootTemplate . isGlobalContext ( ) ) ; action . setActor ( rootTemplate . getActor ( ) ) ; action . setActions ( rootTemplate . getActions ( ) ) ; action . setParameter ( rootTemplate . getParameter ( ) ) ; return this ; }
Loads template bean from Spring bean application context and sets attributes .
98
13
28,052
protected MessageChannel getDestinationChannel ( TestContext context ) { if ( endpointConfiguration . getChannel ( ) != null ) { return endpointConfiguration . getChannel ( ) ; } else if ( StringUtils . hasText ( endpointConfiguration . getChannelName ( ) ) ) { return resolveChannelName ( endpointConfiguration . getChannelName ( ) , context ) ; } else { throw new CitrusRuntimeException ( "Neither channel name nor channel object is set - " + "please specify destination channel" ) ; } }
Get the destination channel depending on settings in this message sender . Either a direct channel object is set or a channel name which will be resolved to a channel .
106
31
28,053
protected String getDestinationChannelName ( ) { if ( endpointConfiguration . getChannel ( ) != null ) { return endpointConfiguration . getChannel ( ) . toString ( ) ; } else if ( StringUtils . hasText ( endpointConfiguration . getChannelName ( ) ) ) { return endpointConfiguration . getChannelName ( ) ; } else { throw new CitrusRuntimeException ( "Neither channel name nor channel object is set - " + "please specify destination channel" ) ; } }
Gets the channel name depending on what is set in this message sender . Either channel name is set directly or channel object is consulted for channel name .
101
30
28,054
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 ) ; // temporary quickfix for unwanted testcase namespace in target 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 .
194
9
28,055
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 .
93
10
28,056
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 .
125
12
28,057
public HttpComponentsClientHttpRequestFactory getObject ( ) throws Exception { Assert . notNull ( credentials , "User credentials not set properly!" ) ; HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory ( httpClient ) { @ Override protected HttpContext createHttpContext ( HttpMethod httpMethod , URI uri ) { // we have to use preemptive authentication // therefore add some basic auth cache to the local context 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 .
316
9
28,058
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 .
63
16
28,059
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 .
68
17
28,060
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 .
224
6
28,061
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 .
210
6
28,062
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 .
108
4
28,063
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 .
264
19
28,064
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 .
63
7
28,065
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 .
98
10
28,066
public void destroy ( ) { JmsUtils . closeSession ( session ) ; if ( connection != null ) { ConnectionFactoryUtils . releaseConnection ( connection , endpointConfiguration . getConnectionFactory ( ) , true ) ; } }
Destroy method closing JMS session and connection
48
8
28,067
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 .
60
8
28,068
public CamelControlBusActionBuilder controlBus ( ) { CamelControlBusAction camelControlBusAction = new CamelControlBusAction ( ) ; camelControlBusAction . setCamelContext ( getCamelContext ( ) ) ; action . setDelegate ( camelControlBusAction ) ; return new CamelControlBusActionBuilder ( camelControlBusAction ) ; }
Execute control bus Camel operations .
73
7
28,069
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 .
170
9
28,070
public void start ( String ... routes ) { StartCamelRouteAction camelRouteAction = new StartCamelRouteAction ( ) ; camelRouteAction . setRouteIds ( Arrays . asList ( routes ) ) ; camelRouteAction . setCamelContext ( getCamelContext ( ) ) ; action . setDelegate ( camelRouteAction ) ; }
Start these Camel routes .
75
5
28,071
public void stop ( String ... routes ) { StopCamelRouteAction camelRouteAction = new StopCamelRouteAction ( ) ; camelRouteAction . setRouteIds ( Arrays . asList ( routes ) ) ; camelRouteAction . setCamelContext ( getCamelContext ( ) ) ; action . setDelegate ( camelRouteAction ) ; }
Stop these Camel routes .
75
5
28,072
public void remove ( String ... routes ) { RemoveCamelRouteAction camelRouteAction = new RemoveCamelRouteAction ( ) ; camelRouteAction . setRouteIds ( Arrays . asList ( routes ) ) ; camelRouteAction . setCamelContext ( getCamelContext ( ) ) ; action . setDelegate ( camelRouteAction ) ; }
Remove these Camel routes .
75
5
28,073
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 .
114
17
28,074
private void replaceHeaders ( final Message from , final Message to ) { to . getHeaders ( ) . clear ( ) ; to . getHeaders ( ) . putAll ( from . getHeaders ( ) ) ; }
Replaces all headers
48
4
28,075
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 { // try to find attachment by its content id 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 .
237
42
28,076
protected void validateAttachmentContentId ( SoapAttachment receivedAttachment , SoapAttachment controlAttachment ) { //in case contentId was not set in test case, skip validation 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 .
318
8
28,077
protected void validateAttachmentContentType ( SoapAttachment receivedAttachment , SoapAttachment controlAttachment ) { //in case contentType was not set in test case, skip validation 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 .
318
8
28,078
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 .
156
19
28,079
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 .
458
21
28,080
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 .
91
11
28,081
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 .
97
12
28,082
public static String evaluateAsString ( Node node , String xPathExpression , NamespaceContext nsContext ) { String result = ( String ) evaluateExpression ( node , xPathExpression , nsContext , XPathConstants . STRING ) ; if ( ! StringUtils . hasText ( result ) ) { //result is empty so check if the expression node really exists //if node does not exist an exception is thrown evaluateAsNode ( node , xPathExpression , nsContext ) ; } return result ; }
Evaluate XPath expression with result type String .
108
11
28,083
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 .
54
12
28,084
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 .
51
11
28,085
public static Object evaluateAsObject ( Node node , String xPathExpression , NamespaceContext nsContext , QName resultType ) { return evaluateExpression ( node , xPathExpression , nsContext , resultType ) ; }
Evaluate XPath expression .
48
7
28,086
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 .
81
34
28,087
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 .
93
6
28,088
private synchronized static XPathFactory createXPathFactory ( ) { XPathFactory factory = null ; // read system property and see if there is a factory set 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 .
265
14
28,089
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 .
70
16
28,090
public File [ ] build ( ) { MavenStrategyStage maven = Maven . configureResolver ( ) . workOffline ( offline ) . resolve ( artifactCoordinates ) ; return applyTransitivity ( maven ) . asFile ( ) ; }
Resolve artifacts for given coordinates .
54
7
28,091
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 .
120
14
28,092
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
169
6
28,093
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 .
58
7
28,094
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 .
118
8
28,095
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 .
123
18
28,096
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 .
160
13
28,097
public io . fabric8 . kubernetes . client . KubernetesClient getKubernetesClient ( ) { if ( kubernetesClient == null ) { kubernetesClient = createKubernetesClient ( ) ; } return kubernetesClient ; }
Constructs or gets the kubernetes client implementation .
62
12
28,098
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 .
225
20
28,099
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 .
544
16