idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
28,200 | public Endpoint getOrCreateEndpoint ( TestContext context ) { if ( endpoint != null ) { return endpoint ; } else if ( StringUtils . hasText ( endpointUri ) ) { endpoint = context . getEndpointFactory ( ) . create ( endpointUri , context ) ; return endpoint ; } else { throw new CitrusRuntimeException ( "Neither endpoint nor endpoint uri is set properly!" ) ; } } | Creates or gets the endpoint instance . |
28,201 | public boolean shouldExecute ( String suiteName , String [ ] includedGroups ) { String baseErrorMessage = "Suite container restrictions did not match %s - do not execute container '%s'" ; if ( StringUtils . hasText ( suiteName ) && ! CollectionUtils . isEmpty ( suiteNames ) && ! suiteNames . contains ( suiteName ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( baseErrorMessage , "suite name" , getName ( ) ) ) ; } return false ; } if ( ! checkTestGroups ( includedGroups ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( baseErrorMessage , "test groups" , getName ( ) ) ) ; } return false ; } for ( Map . Entry < String , String > envEntry : env . entrySet ( ) ) { if ( ! System . getenv ( ) . containsKey ( envEntry . getKey ( ) ) || ( StringUtils . hasText ( envEntry . getValue ( ) ) && ! System . getenv ( ) . get ( envEntry . getKey ( ) ) . equals ( envEntry . getValue ( ) ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( baseErrorMessage , "env properties" , getName ( ) ) ) ; } return false ; } } for ( Map . Entry < String , String > systemProperty : systemProperties . entrySet ( ) ) { if ( ! System . getProperties ( ) . containsKey ( systemProperty . getKey ( ) ) || ( StringUtils . hasText ( systemProperty . getValue ( ) ) && ! System . getProperties ( ) . get ( systemProperty . getKey ( ) ) . equals ( systemProperty . getValue ( ) ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( baseErrorMessage , "system properties" , getName ( ) ) ) ; } return false ; } } return true ; } | Checks if this suite actions should execute according to suite name and included test groups . |
28,202 | public CamelControlBusActionBuilder route ( String id , String action ) { super . action . setRouteId ( id ) ; super . action . setAction ( action ) ; return this ; } | Sets route action to execute . |
28,203 | public CamelControlBusActionBuilder language ( String language , String expression ) { action . setLanguageType ( language ) ; action . setLanguageExpression ( expression ) ; return this ; } | Sets a language expression to execute . |
28,204 | public void handleRequest ( String request ) { if ( messageListener != null ) { log . debug ( "Received Http request" ) ; messageListener . onInboundMessage ( new RawMessage ( request ) , null ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Received Http request:" + NEWLINE + request ) ; } } } | Handle request message and write request to logger . |
28,205 | public void handleResponse ( String response ) { if ( messageListener != null ) { log . debug ( "Sending Http response" ) ; messageListener . onOutboundMessage ( new RawMessage ( response ) , null ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( "Sending Http response:" + NEWLINE + response ) ; } } } | Handle response message and write content to logger . |
28,206 | private String getRequestContent ( HttpServletRequest request ) throws IOException { StringBuilder builder = new StringBuilder ( ) ; builder . append ( request . getProtocol ( ) ) ; builder . append ( " " ) ; builder . append ( request . getMethod ( ) ) ; builder . append ( " " ) ; builder . append ( request . getRequestURI ( ) ) ; builder . append ( NEWLINE ) ; Enumeration < ? > headerNames = request . getHeaderNames ( ) ; while ( headerNames . hasMoreElements ( ) ) { String headerName = headerNames . nextElement ( ) . toString ( ) ; builder . append ( headerName ) ; builder . append ( ":" ) ; Enumeration < ? > headerValues = request . getHeaders ( headerName ) ; if ( headerValues . hasMoreElements ( ) ) { builder . append ( headerValues . nextElement ( ) ) ; } while ( headerValues . hasMoreElements ( ) ) { builder . append ( "," ) ; builder . append ( headerValues . nextElement ( ) ) ; } builder . append ( NEWLINE ) ; } builder . append ( NEWLINE ) ; builder . append ( FileUtils . readToString ( request . getInputStream ( ) ) ) ; return builder . toString ( ) ; } | Builds raw request message content from Http servlet request . |
28,207 | private javax . jms . Message receive ( String destinationName , String selector ) { javax . jms . Message receivedJmsMessage ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Receiving JMS message on destination: '" + destinationName + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; } if ( StringUtils . hasText ( selector ) ) { receivedJmsMessage = endpointConfiguration . getJmsTemplate ( ) . receiveSelected ( destinationName , selector ) ; } else { receivedJmsMessage = endpointConfiguration . getJmsTemplate ( ) . receive ( destinationName ) ; } if ( receivedJmsMessage == null ) { throw new ActionTimeoutException ( "Action timed out while receiving JMS message on '" + destinationName + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; } log . info ( "Received JMS message on destination: '" + destinationName + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; return receivedJmsMessage ; } | Receive message from destination name . |
28,208 | private javax . jms . Message receive ( Destination destination , String selector ) { javax . jms . Message receivedJmsMessage ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Receiving JMS message on destination: '" + endpointConfiguration . getDestinationName ( destination ) + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; } if ( StringUtils . hasText ( selector ) ) { receivedJmsMessage = endpointConfiguration . getJmsTemplate ( ) . receiveSelected ( destination , selector ) ; } else { receivedJmsMessage = endpointConfiguration . getJmsTemplate ( ) . receive ( destination ) ; } if ( receivedJmsMessage == null ) { throw new ActionTimeoutException ( "Action timed out while receiving JMS message on '" + endpointConfiguration . getDestinationName ( destination ) + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; } log . info ( "Received JMS message on destination: '" + endpointConfiguration . getDestinationName ( destination ) + ( StringUtils . hasText ( selector ) ? "(" + selector + ")" : "" ) + "'" ) ; return receivedJmsMessage ; } | Receive message from destination . |
28,209 | public String convert ( String messagePayload ) { initialize ( ) ; if ( messagePayload . contains ( XHTML_DOCTYPE_DEFINITION ) ) { return messagePayload ; } else { String xhtmlPayload ; StringWriter xhtmlWriter = new StringWriter ( ) ; tidyInstance . parse ( new StringReader ( messagePayload ) , xhtmlWriter ) ; xhtmlPayload = xhtmlWriter . toString ( ) ; xhtmlPayload = xhtmlPayload . replaceFirst ( W3_XHTML1_URL , "org/w3/xhtml/" ) ; return xhtmlPayload ; } } | Converts message to XHTML conform representation . |
28,210 | public void initialize ( ) { try { if ( tidyInstance == null ) { tidyInstance = new Tidy ( ) ; tidyInstance . setXHTML ( true ) ; tidyInstance . setShowWarnings ( false ) ; tidyInstance . setQuiet ( true ) ; tidyInstance . setEscapeCdata ( true ) ; tidyInstance . setTidyMark ( false ) ; if ( tidyConfiguration != null ) { tidyInstance . setConfigurationFromFile ( tidyConfiguration . getFile ( ) . getAbsolutePath ( ) ) ; } } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to initialize XHTML tidy instance" ) ; } } | Initialize tidy from configuration . |
28,211 | public void start ( ) { if ( kafkaServer != null ) { log . warn ( "Found instance of Kafka server - avoid duplicate Kafka server startup" ) ; return ; } File logDir = createLogDir ( ) ; zookeeper = createZookeeperServer ( logDir ) ; serverFactory = createServerFactory ( ) ; try { serverFactory . startup ( zookeeper ) ; } catch ( InterruptedException | IOException e ) { throw new CitrusRuntimeException ( "Failed to start embedded zookeeper server" , e ) ; } Properties brokerConfigProperties = createBrokerProperties ( "localhost:" + zookeeperPort , kafkaServerPort , logDir ) ; brokerConfigProperties . setProperty ( KafkaConfig . ReplicaSocketTimeoutMsProp ( ) , "1000" ) ; brokerConfigProperties . setProperty ( KafkaConfig . ControllerSocketTimeoutMsProp ( ) , "1000" ) ; brokerConfigProperties . setProperty ( KafkaConfig . OffsetsTopicReplicationFactorProp ( ) , "1" ) ; brokerConfigProperties . setProperty ( KafkaConfig . ReplicaHighWatermarkCheckpointIntervalMsProp ( ) , String . valueOf ( Long . MAX_VALUE ) ) ; if ( brokerProperties != null ) { brokerProperties . forEach ( brokerConfigProperties :: put ) ; } kafkaServer = new KafkaServer ( new KafkaConfig ( brokerConfigProperties ) , Time . SYSTEM , scala . Option . apply ( null ) , scala . collection . JavaConversions . asScalaBuffer ( Collections . < KafkaMetricsReporter > emptyList ( ) ) . toList ( ) ) ; kafkaServer . startup ( ) ; kafkaServer . boundPort ( ListenerName . forSecurityProtocol ( SecurityProtocol . PLAINTEXT ) ) ; createKafkaTopics ( StringUtils . commaDelimitedListToSet ( topics ) ) ; } | Start embedded server instances for Kafka and Zookeeper . |
28,212 | public void stop ( ) { if ( kafkaServer != null ) { try { if ( kafkaServer . brokerState ( ) . currentState ( ) != ( NotRunning . state ( ) ) ) { kafkaServer . shutdown ( ) ; kafkaServer . awaitShutdown ( ) ; } } catch ( Exception e ) { log . warn ( "Failed to shutdown Kafka embedded server" , e ) ; } try { CoreUtils . delete ( kafkaServer . config ( ) . logDirs ( ) ) ; } catch ( Exception e ) { log . warn ( "Failed to remove logs on Kafka embedded server" , e ) ; } } if ( serverFactory != null ) { try { serverFactory . shutdown ( ) ; } catch ( Exception e ) { log . warn ( "Failed to shutdown Zookeeper instance" , e ) ; } } } | Shutdown embedded Kafka and Zookeeper server instances |
28,213 | protected ZooKeeperServer createZookeeperServer ( File logDir ) { try { return new ZooKeeperServer ( logDir , logDir , 2000 ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to create embedded zookeeper server" , e ) ; } } | Creates new embedded Zookeeper server . |
28,214 | protected File createLogDir ( ) { File logDir = Optional . ofNullable ( logDirPath ) . map ( Paths :: get ) . map ( Path :: toFile ) . orElse ( new File ( System . getProperty ( "java.io.tmpdir" ) ) ) ; if ( ! logDir . exists ( ) ) { if ( ! logDir . mkdirs ( ) ) { log . warn ( "Unable to create log directory: " + logDir . getAbsolutePath ( ) ) ; logDir = new File ( System . getProperty ( "java.io.tmpdir" ) ) ; log . info ( "Using default log directory: " + logDir . getAbsolutePath ( ) ) ; } } File logs = new File ( logDir , "zookeeper" + System . currentTimeMillis ( ) ) . getAbsoluteFile ( ) ; if ( autoDeleteLogs ) { logs . deleteOnExit ( ) ; } return logs ; } | Creates Zookeeper log directory . By default logs are created in Java temp directory . By default directory is automatically deleted on exit . |
28,215 | protected ServerCnxnFactory createServerFactory ( ) { try { ServerCnxnFactory serverFactory = new NIOServerCnxnFactory ( ) ; serverFactory . configure ( new InetSocketAddress ( zookeeperPort ) , 5000 ) ; return serverFactory ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to create default zookeeper server factory" , e ) ; } } | Create server factory for embedded Zookeeper server instance . |
28,216 | protected void createKafkaTopics ( Set < String > topics ) { Map < String , Object > adminConfigs = new HashMap < > ( ) ; adminConfigs . put ( AdminClientConfig . BOOTSTRAP_SERVERS_CONFIG , "localhost:" + kafkaServerPort ) ; try ( AdminClient admin = AdminClient . create ( adminConfigs ) ) { List < NewTopic > newTopics = topics . stream ( ) . map ( t -> new NewTopic ( t , partitions , ( short ) 1 ) ) . collect ( Collectors . toList ( ) ) ; CreateTopicsResult createTopics = admin . createTopics ( newTopics ) ; try { createTopics . all ( ) . get ( ) ; } catch ( Exception e ) { log . warn ( "Failed to create Kafka topics" , e ) ; } } } | Create topics on embedded Kafka server . |
28,217 | protected Properties createBrokerProperties ( String zooKeeperConnect , int kafkaServerPort , File logDir ) { Properties props = new Properties ( ) ; props . put ( KafkaConfig . BrokerIdProp ( ) , "0" ) ; props . put ( KafkaConfig . ZkConnectProp ( ) , zooKeeperConnect ) ; props . put ( KafkaConfig . ZkConnectionTimeoutMsProp ( ) , "10000" ) ; props . put ( KafkaConfig . ReplicaSocketTimeoutMsProp ( ) , "1500" ) ; props . put ( KafkaConfig . ControllerSocketTimeoutMsProp ( ) , "1500" ) ; props . put ( KafkaConfig . ControlledShutdownEnableProp ( ) , "false" ) ; props . put ( KafkaConfig . DeleteTopicEnableProp ( ) , "true" ) ; props . put ( KafkaConfig . LogDeleteDelayMsProp ( ) , "1000" ) ; props . put ( KafkaConfig . ControlledShutdownRetryBackoffMsProp ( ) , "100" ) ; props . put ( KafkaConfig . LogCleanerDedupeBufferSizeProp ( ) , "2097152" ) ; props . put ( KafkaConfig . LogMessageTimestampDifferenceMaxMsProp ( ) , Long . MAX_VALUE ) ; props . put ( KafkaConfig . OffsetsTopicReplicationFactorProp ( ) , "1" ) ; props . put ( KafkaConfig . OffsetsTopicPartitionsProp ( ) , "5" ) ; props . put ( KafkaConfig . GroupInitialRebalanceDelayMsProp ( ) , "0" ) ; props . put ( KafkaConfig . LogDirProp ( ) , logDir . getAbsolutePath ( ) ) ; props . put ( KafkaConfig . ListenersProp ( ) , SecurityProtocol . PLAINTEXT . name + "://localhost:" + kafkaServerPort ) ; props . forEach ( ( key , value ) -> log . debug ( String . format ( "Using default Kafka broker property %s='%s'" , key , value ) ) ) ; return props ; } | Creates Kafka broker properties . |
28,218 | public void doWithMessage ( WebServiceMessage responseMessage ) throws IOException , TransformerException { response = endpointConfiguration . getMessageConverter ( ) . convertInbound ( responseMessage , endpointConfiguration , context ) ; } | Callback method called with actual web service response message . Method constructs a Spring Integration message from this web service message for further processing . |
28,219 | public void saveReplyDestination ( Message receivedMessage , TestContext context ) { if ( receivedMessage . getHeader ( CitrusVertxMessageHeaders . VERTX_REPLY_ADDRESS ) != null ) { String correlationKeyName = endpointConfiguration . getCorrelator ( ) . getCorrelationKeyName ( getName ( ) ) ; String correlationKey = endpointConfiguration . getCorrelator ( ) . getCorrelationKey ( receivedMessage ) ; correlationManager . saveCorrelationKey ( correlationKeyName , correlationKey , context ) ; correlationManager . store ( correlationKey , receivedMessage . getHeader ( CitrusVertxMessageHeaders . VERTX_REPLY_ADDRESS ) . toString ( ) ) ; } else { log . warn ( "Unable to retrieve reply address for message \n" + receivedMessage + "\n - no reply address found in message headers!" ) ; } } | Store the reply address either straight forward or with a given message correlation key . |
28,220 | private ZooKeeper createZooKeeperClient ( ) throws IOException { ZooClientConfig config = getZookeeperClientConfig ( ) ; return new ZooKeeper ( config . getUrl ( ) , config . getTimeout ( ) , getConnectionWatcher ( ) ) ; } | Creates a new Zookeeper client instance with configuration . |
28,221 | public ZooKeeper getZooKeeperClient ( ) { if ( zookeeper == null ) { try { zookeeper = createZooKeeperClient ( ) ; int retryAttempts = 5 ; while ( ! zookeeper . getState ( ) . isConnected ( ) && retryAttempts > 0 ) { LOG . debug ( "connecting..." ) ; retryAttempts -- ; Thread . sleep ( 1000 ) ; } } catch ( IOException | InterruptedException e ) { throw new CitrusRuntimeException ( e ) ; } } return zookeeper ; } | Constructs or gets the zookeeper client implementation . |
28,222 | private void loadEndpointComponentProperties ( ) { try { endpointComponentProperties = PropertiesLoaderUtils . loadProperties ( new ClassPathResource ( "com/consol/citrus/endpoint/endpoint.components" ) ) ; } catch ( IOException e ) { log . warn ( "Unable to laod default endpoint components from resource '%s'" , e ) ; } } | Loads property file from classpath holding default endpoint component definitions in Citrus . |
28,223 | private void loadEndpointParserProperties ( ) { try { endpointParserProperties = PropertiesLoaderUtils . loadProperties ( new ClassPathResource ( "com/consol/citrus/endpoint/endpoint.parser" ) ) ; } catch ( IOException e ) { log . warn ( "Unable to laod default endpoint annotation parsers from resource '%s'" , e ) ; } } | Loads property file from classpath holding default endpoint annotation parser definitions in Citrus . |
28,224 | public void setAction ( String action ) { try { this . action = new URI ( action ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid action uri" , e ) ; } } | Sets the action from uri string . |
28,225 | public void setTo ( String to ) { try { this . to = new URI ( to ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid to uri" , e ) ; } } | Sets the to uri by string . |
28,226 | public void setMessageId ( String messageId ) { try { this . messageId = new URI ( messageId ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid messageId uri" , e ) ; } } | Sets the message id from uri string . |
28,227 | public void setFrom ( String from ) { try { this . from = new EndpointReference ( new URI ( from ) ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid from uri" , e ) ; } } | Sets the from endpoint reference by string . |
28,228 | public void setReplyTo ( String replyTo ) { try { this . replyTo = new EndpointReference ( new URI ( replyTo ) ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid replyTo uri" , e ) ; } } | Sets the reply to endpoint reference by string . |
28,229 | public void setFaultTo ( String faultTo ) { try { this . faultTo = new EndpointReference ( new URI ( faultTo ) ) ; } catch ( URISyntaxException e ) { throw new CitrusRuntimeException ( "Invalid faultTo uri" , e ) ; } } | Sets the fault to endpoint reference by string . |
28,230 | private void createHtmlDoc ( ) throws PrompterException { HtmlDocConfiguration configuration = new HtmlDocConfiguration ( ) ; String heading = prompter . prompt ( "Enter overview title:" , configuration . getHeading ( ) ) ; String columns = prompter . prompt ( "Enter number of columns in overview:" , configuration . getColumns ( ) ) ; String pageTitle = prompter . prompt ( "Enter page title:" , configuration . getPageTitle ( ) ) ; String outputFile = prompter . prompt ( "Enter output file name:" , configuration . getOutputFile ( ) ) ; String logo = prompter . prompt ( "Enter file path to logo:" , configuration . getLogo ( ) ) ; String confirm = prompter . prompt ( "Confirm HTML documentation: outputFile='target/" + outputFile + ( outputFile . endsWith ( ".html" ) ? "" : ".html" ) + "'\n" , Arrays . asList ( "y" , "n" ) , "y" ) ; if ( confirm . equalsIgnoreCase ( "n" ) ) { return ; } HtmlTestDocsGenerator generator = getHtmlTestDocsGenerator ( ) ; generator . withOutputFile ( outputFile + ( outputFile . endsWith ( ".html" ) ? "" : ".html" ) ) . withPageTitle ( pageTitle ) . withOverviewTitle ( heading ) . withColumns ( columns ) . useSrcDirectory ( getTestSrcDirectory ( ) ) . withLogo ( logo ) ; generator . generateDoc ( ) ; getLog ( ) . info ( "Successfully created HTML documentation: outputFile='target/" + outputFile + ( outputFile . endsWith ( ".html" ) ? "" : ".html" ) + "'" ) ; } | Create HTML documentation in interactive mode . |
28,231 | private void createExcelDoc ( ) throws PrompterException { ExcelDocConfiguration configuration = new ExcelDocConfiguration ( ) ; String company = prompter . prompt ( "Enter company:" , configuration . getCompany ( ) ) ; String author = prompter . prompt ( "Enter author:" , configuration . getAuthor ( ) ) ; String pageTitle = prompter . prompt ( "Enter page title:" , configuration . getPageTitle ( ) ) ; String outputFile = prompter . prompt ( "Enter output file name:" , configuration . getOutputFile ( ) ) ; String headers = prompter . prompt ( "Enter custom headers:" , configuration . getHeaders ( ) ) ; String confirm = prompter . prompt ( "Confirm Excel documentation: outputFile='target/" + outputFile + ( outputFile . endsWith ( ".xls" ) ? "" : ".xls" ) + "'\n" , Arrays . asList ( "y" , "n" ) , "y" ) ; if ( confirm . equalsIgnoreCase ( "n" ) ) { return ; } ExcelTestDocsGenerator generator = getExcelTestDocsGenerator ( ) ; generator . withOutputFile ( outputFile + ( outputFile . endsWith ( ".xls" ) ? "" : ".xls" ) ) . withPageTitle ( pageTitle ) . withAuthor ( author ) . withCompany ( company ) . useSrcDirectory ( getTestSrcDirectory ( ) ) . withCustomHeaders ( headers ) ; generator . generateDoc ( ) ; getLog ( ) . info ( "Successfully created Excel documentation: outputFile='target/" + outputFile + ( outputFile . endsWith ( ".xls" ) ? "" : ".xls" ) + "'" ) ; } | Create Excel documentation in interactive mode . |
28,232 | public static String changeDate ( String date , String dateOffset , String dateFormat , TestContext context ) { return new ChangeDateFunction ( ) . execute ( Arrays . asList ( date , dateOffset , dateFormat ) , context ) ; } | Runs change date function with arguments . |
28,233 | public static String createCDataSection ( String content , TestContext context ) { return new CreateCDataSectionFunction ( ) . execute ( Collections . singletonList ( content ) , context ) ; } | Runs create CData section function with arguments . |
28,234 | public static String digestAuthHeader ( String username , String password , String realm , String noncekey , String method , String uri , String opaque , String algorithm , TestContext context ) { return new DigestAuthHeaderFunction ( ) . execute ( Arrays . asList ( username , password , realm , noncekey , method , uri , opaque , algorithm ) , context ) ; } | Runs create digest auth header function with arguments . |
28,235 | public static String randomUUID ( TestContext context ) { return new RandomUUIDFunction ( ) . execute ( Collections . < String > emptyList ( ) , context ) ; } | Runs random UUID function with arguments . |
28,236 | public static String escapeXml ( String content , TestContext context ) { return new EscapeXmlFunction ( ) . execute ( Collections . singletonList ( content ) , context ) ; } | Runs escape XML function with arguments . |
28,237 | public static String readFile ( String filePath , TestContext context ) { return new ReadFileResourceFunction ( ) . execute ( Collections . singletonList ( filePath ) , context ) ; } | Reads the file resource and returns the complete file content . |
28,238 | public static void parseJsonPathElements ( Element validateElement , Map < String , Object > validateJsonPathExpressions ) { List < ? > jsonPathElements = DomUtils . getChildElementsByTagName ( validateElement , "json-path" ) ; if ( jsonPathElements . size ( ) > 0 ) { for ( Iterator < ? > jsonPathIterator = jsonPathElements . iterator ( ) ; jsonPathIterator . hasNext ( ) ; ) { Element jsonPathElement = ( Element ) jsonPathIterator . next ( ) ; String expression = jsonPathElement . getAttribute ( "expression" ) ; if ( StringUtils . hasText ( expression ) ) { validateJsonPathExpressions . put ( expression , jsonPathElement . getAttribute ( "value" ) ) ; } } } } | Parses validate element containing nested json - path elements . |
28,239 | public static String readToString ( Resource resource , Charset charset ) throws IOException { if ( simulationMode ) { if ( resource instanceof ClassPathResource ) { return ( ( ClassPathResource ) resource ) . getPath ( ) ; } else if ( resource instanceof FileSystemResource ) { return ( ( FileSystemResource ) resource ) . getPath ( ) ; } else { return resource . getFilename ( ) ; } } if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Reading file resource: '%s' (encoding is '%s')" , resource . getFilename ( ) , charset . displayName ( ) ) ) ; } return readToString ( resource . getInputStream ( ) , charset ) ; } | Read file resource to string value . |
28,240 | public static String readToString ( InputStream inputStream , Charset charset ) throws IOException { return new String ( FileCopyUtils . copyToByteArray ( inputStream ) , charset ) ; } | Read file input stream to string value . |
28,241 | public static void writeToFile ( InputStream inputStream , File file ) { try ( InputStreamReader inputStreamReader = new InputStreamReader ( inputStream ) ) { writeToFile ( FileCopyUtils . copyToString ( inputStreamReader ) , file , getDefaultCharset ( ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to write file" , e ) ; } } | Writes inputStream content to file . Uses default charset encoding . |
28,242 | public static void writeToFile ( String content , File file , Charset charset ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Writing file resource: '%s' (encoding is '%s')" , file . getName ( ) , charset . displayName ( ) ) ) ; } if ( ! file . getParentFile ( ) . exists ( ) ) { if ( ! file . getParentFile ( ) . mkdirs ( ) ) { throw new CitrusRuntimeException ( "Unable to create folder structure for file: " + file . getPath ( ) ) ; } } try ( OutputStream fos = new BufferedOutputStream ( new FileOutputStream ( file ) ) ) { fos . write ( content . getBytes ( charset ) ) ; fos . flush ( ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to write file" , e ) ; } } | Writes String content to file with given charset encoding . Automatically closes file output streams when done . |
28,243 | public static List < File > findFiles ( final String startDir , final Set < String > fileNamePatterns ) { final List < File > files = new ArrayList < File > ( ) ; final Stack < File > dirs = new Stack < File > ( ) ; final File startdir = new File ( startDir ) ; if ( ! startdir . exists ( ) ) { throw new CitrusRuntimeException ( "Test directory " + startdir . getAbsolutePath ( ) + " does not exist" ) ; } if ( startdir . isDirectory ( ) ) { dirs . push ( startdir ) ; } while ( dirs . size ( ) > 0 ) { final File file = dirs . pop ( ) ; File [ ] foundFiles = file . listFiles ( ( dir , name ) -> { File tmp = new File ( dir . getPath ( ) + File . separator + name ) ; boolean accepted = tmp . isDirectory ( ) ; for ( String fileNamePattern : fileNamePatterns ) { if ( fileNamePattern . contains ( "/" ) ) { fileNamePattern = fileNamePattern . substring ( fileNamePattern . lastIndexOf ( '/' ) + 1 ) ; } fileNamePattern = fileNamePattern . replace ( "." , "\\." ) . replace ( "*" , ".*" ) ; if ( name . matches ( fileNamePattern ) ) { accepted = true ; } } return accepted && ! name . startsWith ( "CVS" ) && ! name . startsWith ( ".svn" ) && ! name . startsWith ( ".git" ) ; } ) ; for ( File found : Optional . ofNullable ( foundFiles ) . orElse ( new File [ ] { } ) ) { if ( found . isDirectory ( ) ) { dirs . push ( found ) ; } else { files . add ( found ) ; } } } return files ; } | Method to retrieve all files with given file name pattern in given directory . Hierarchy of folders is supported . |
28,244 | @ SuppressWarnings ( "unchecked" ) public static ClientServerEndpointBuilder < DockerClientBuilder , DockerClientBuilder > docker ( ) { return new ClientServerEndpointBuilder ( new DockerClientBuilder ( ) , new DockerClientBuilder ( ) ) { public EndpointBuilder < ? extends Endpoint > server ( ) { throw new UnsupportedOperationException ( "Citrus Docker stack has no support for server implementation" ) ; } } ; } | Creates new DockerClient builder . |
28,245 | @ SuppressWarnings ( "unchecked" ) public static ClientServerEndpointBuilder < KubernetesClientBuilder , KubernetesClientBuilder > kubernetes ( ) { return new ClientServerEndpointBuilder ( new KubernetesClientBuilder ( ) , new KubernetesClientBuilder ( ) ) { public EndpointBuilder < ? extends Endpoint > server ( ) { throw new UnsupportedOperationException ( "Citrus Kubernetes stack has no support for server implementation" ) ; } } ; } | Creates new KubernetesClient builder . |
28,246 | protected void validateFaultDetailString ( String receivedDetailString , String controlDetailString , TestContext context , ValidationContext validationContext ) throws ValidationException { XmlMessageValidationContext xmlMessageValidationContext ; if ( validationContext instanceof XmlMessageValidationContext ) { xmlMessageValidationContext = ( XmlMessageValidationContext ) validationContext ; } else { xmlMessageValidationContext = new XmlMessageValidationContext ( ) ; } messageValidator . validateMessage ( new DefaultMessage ( receivedDetailString ) , new DefaultMessage ( controlDetailString ) , context , xmlMessageValidationContext ) ; } | Delegates to XML message validator for validation of fault detail . |
28,247 | public void start ( ) { if ( ! isStarted ( ) ) { if ( getEndpointConfiguration ( ) . getWebDriver ( ) != null ) { webDriver = getEndpointConfiguration ( ) . getWebDriver ( ) ; } else if ( StringUtils . hasText ( getEndpointConfiguration ( ) . getRemoteServerUrl ( ) ) ) { webDriver = createRemoteWebDriver ( getEndpointConfiguration ( ) . getBrowserType ( ) , getEndpointConfiguration ( ) . getRemoteServerUrl ( ) ) ; } else { webDriver = createLocalWebDriver ( getEndpointConfiguration ( ) . getBrowserType ( ) ) ; } if ( ! CollectionUtils . isEmpty ( getEndpointConfiguration ( ) . getEventListeners ( ) ) ) { EventFiringWebDriver wrapper = new EventFiringWebDriver ( webDriver ) ; log . info ( "Add event listeners to web driver: " + getEndpointConfiguration ( ) . getEventListeners ( ) . size ( ) ) ; for ( WebDriverEventListener listener : getEndpointConfiguration ( ) . getEventListeners ( ) ) { wrapper . register ( listener ) ; } } } else { log . warn ( "Browser already started" ) ; } } | Starts the browser and create local or remote web driver . |
28,248 | public void stop ( ) { if ( isStarted ( ) ) { log . info ( "Stopping browser " + webDriver . getCurrentUrl ( ) ) ; try { log . info ( "Trying to close the browser " + webDriver + " ..." ) ; webDriver . quit ( ) ; } catch ( UnreachableBrowserException e ) { log . warn ( "Browser is unreachable" , e ) ; } catch ( WebDriverException e ) { log . error ( "Failed to close browser" , e ) ; } webDriver = null ; } else { log . warn ( "Browser already stopped" ) ; } } | Stop the browser when started . |
28,249 | public String storeFile ( Resource file ) { try { File newFile = new File ( temporaryStorage . toFile ( ) , file . getFilename ( ) ) ; log . info ( "Store file " + file + " to " + newFile ) ; FileUtils . copyFile ( file . getFile ( ) , newFile ) ; return newFile . getCanonicalPath ( ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to store file: " + file , e ) ; } } | Deploy resource object from resource folder and return path of deployed file |
28,250 | public String getStoredFile ( String filename ) { try { File stored = new File ( temporaryStorage . toFile ( ) , filename ) ; if ( ! stored . exists ( ) ) { throw new CitrusRuntimeException ( "Failed to access stored file: " + stored . getCanonicalPath ( ) ) ; } return stored . getCanonicalPath ( ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to retrieve file: " + filename , e ) ; } } | Retrieve resource object |
28,251 | private WebDriver createLocalWebDriver ( String browserType ) { switch ( browserType ) { case BrowserType . FIREFOX : FirefoxProfile firefoxProfile = getEndpointConfiguration ( ) . getFirefoxProfile ( ) ; firefoxProfile . setPreference ( "browser.download.dir" , temporaryStorage . toFile ( ) . getAbsolutePath ( ) ) ; DesiredCapabilities defaults = DesiredCapabilities . firefox ( ) ; defaults . setCapability ( FirefoxDriver . PROFILE , firefoxProfile ) ; return new FirefoxDriver ( defaults ) ; case BrowserType . IE : return new InternetExplorerDriver ( ) ; case BrowserType . EDGE : return new EdgeDriver ( ) ; case BrowserType . SAFARI : return new SafariDriver ( ) ; case BrowserType . CHROME : return new ChromeDriver ( ) ; case BrowserType . GOOGLECHROME : return new ChromeDriver ( ) ; case BrowserType . HTMLUNIT : BrowserVersion browserVersion = null ; if ( getEndpointConfiguration ( ) . getVersion ( ) . equals ( "FIREFOX" ) ) { browserVersion = BrowserVersion . FIREFOX_45 ; } else if ( getEndpointConfiguration ( ) . getVersion ( ) . equals ( "INTERNET_EXPLORER" ) ) { browserVersion = BrowserVersion . INTERNET_EXPLORER ; } else if ( getEndpointConfiguration ( ) . getVersion ( ) . equals ( "EDGE" ) ) { browserVersion = BrowserVersion . EDGE ; } else if ( getEndpointConfiguration ( ) . getVersion ( ) . equals ( "CHROME" ) ) { browserVersion = BrowserVersion . CHROME ; } HtmlUnitDriver htmlUnitDriver ; if ( browserVersion != null ) { htmlUnitDriver = new HtmlUnitDriver ( browserVersion ) ; } else { htmlUnitDriver = new HtmlUnitDriver ( ) ; } htmlUnitDriver . setJavascriptEnabled ( getEndpointConfiguration ( ) . isJavaScript ( ) ) ; return htmlUnitDriver ; default : throw new CitrusRuntimeException ( "Unsupported local browser type: " + browserType ) ; } } | Creates local web driver . |
28,252 | private RemoteWebDriver createRemoteWebDriver ( String browserType , String serverAddress ) { try { switch ( browserType ) { case BrowserType . FIREFOX : DesiredCapabilities defaultsFF = DesiredCapabilities . firefox ( ) ; defaultsFF . setCapability ( FirefoxDriver . PROFILE , getEndpointConfiguration ( ) . getFirefoxProfile ( ) ) ; return new RemoteWebDriver ( new URL ( serverAddress ) , defaultsFF ) ; case BrowserType . IE : DesiredCapabilities defaultsIE = DesiredCapabilities . internetExplorer ( ) ; defaultsIE . setCapability ( CapabilityType . ACCEPT_SSL_CERTS , true ) ; return new RemoteWebDriver ( new URL ( serverAddress ) , defaultsIE ) ; case BrowserType . CHROME : DesiredCapabilities defaultsChrome = DesiredCapabilities . chrome ( ) ; defaultsChrome . setCapability ( CapabilityType . ACCEPT_SSL_CERTS , true ) ; return new RemoteWebDriver ( new URL ( serverAddress ) , defaultsChrome ) ; case BrowserType . GOOGLECHROME : DesiredCapabilities defaultsGoogleChrome = DesiredCapabilities . chrome ( ) ; defaultsGoogleChrome . setCapability ( CapabilityType . ACCEPT_SSL_CERTS , true ) ; return new RemoteWebDriver ( new URL ( serverAddress ) , defaultsGoogleChrome ) ; default : throw new CitrusRuntimeException ( "Unsupported remote browser type: " + browserType ) ; } } catch ( MalformedURLException e ) { throw new CitrusRuntimeException ( "Failed to access remote server" , e ) ; } } | Creates remote web driver . |
28,253 | private Path createTemporaryStorage ( ) { try { Path tempDir = Files . createTempDirectory ( "selenium" ) ; tempDir . toFile ( ) . deleteOnExit ( ) ; log . info ( "Download storage location is: " + tempDir . toString ( ) ) ; return tempDir ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Could not create temporary storage" , e ) ; } } | Creates temporary storage . |
28,254 | protected void sendClientRequest ( HttpMessage request ) { BuilderSupport < HttpActionBuilder > action = builder -> { HttpClientActionBuilder . HttpClientSendActionBuilder sendBuilder = builder . client ( httpClient ) . send ( ) ; HttpClientRequestActionBuilder requestBuilder ; if ( request . getRequestMethod ( ) == null || request . getRequestMethod ( ) . equals ( HttpMethod . POST ) ) { requestBuilder = sendBuilder . post ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . GET ) ) { requestBuilder = sendBuilder . get ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . PUT ) ) { requestBuilder = sendBuilder . put ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . DELETE ) ) { requestBuilder = sendBuilder . delete ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . HEAD ) ) { requestBuilder = sendBuilder . head ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . TRACE ) ) { requestBuilder = sendBuilder . trace ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . PATCH ) ) { requestBuilder = sendBuilder . patch ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . OPTIONS ) ) { requestBuilder = sendBuilder . options ( ) . message ( request ) ; } else { requestBuilder = sendBuilder . post ( ) . message ( request ) ; } if ( StringUtils . hasText ( url ) ) { requestBuilder . uri ( url ) ; } } ; runner . http ( action ) ; } | Sends client request . |
28,255 | protected void receiveClientResponse ( HttpMessage response ) { runner . http ( action -> { HttpClientResponseActionBuilder responseBuilder = action . client ( httpClient ) . receive ( ) . response ( response . getStatusCode ( ) ) . message ( response ) ; for ( Map . Entry < String , String > headerEntry : pathValidations . entrySet ( ) ) { responseBuilder . validate ( headerEntry . getKey ( ) , headerEntry . getValue ( ) ) ; } pathValidations . clear ( ) ; } ) ; } | Receives client response . |
28,256 | protected void receiveServerRequest ( HttpMessage request ) { BuilderSupport < HttpActionBuilder > action = builder -> { HttpServerActionBuilder . HttpServerReceiveActionBuilder receiveBuilder = builder . server ( httpServer ) . receive ( ) ; HttpServerRequestActionBuilder requestBuilder ; if ( request . getRequestMethod ( ) == null || request . getRequestMethod ( ) . equals ( HttpMethod . POST ) ) { requestBuilder = receiveBuilder . post ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . GET ) ) { requestBuilder = receiveBuilder . get ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . PUT ) ) { requestBuilder = receiveBuilder . put ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . DELETE ) ) { requestBuilder = receiveBuilder . delete ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . HEAD ) ) { requestBuilder = receiveBuilder . head ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . TRACE ) ) { requestBuilder = receiveBuilder . trace ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . PATCH ) ) { requestBuilder = receiveBuilder . patch ( ) . message ( request ) ; } else if ( request . getRequestMethod ( ) . equals ( HttpMethod . OPTIONS ) ) { requestBuilder = receiveBuilder . options ( ) . message ( request ) ; } else { requestBuilder = receiveBuilder . post ( ) . message ( request ) ; } for ( Map . Entry < String , String > headerEntry : pathValidations . entrySet ( ) ) { requestBuilder . validate ( headerEntry . getKey ( ) , headerEntry . getValue ( ) ) ; } pathValidations . clear ( ) ; } ; runner . http ( action ) ; } | Receives server request . |
28,257 | Cookie [ ] convertCookies ( HttpEntity < ? > httpEntity ) { final List < Cookie > cookies = new LinkedList < > ( ) ; List < String > inboundCookies = httpEntity . getHeaders ( ) . get ( HttpHeaders . SET_COOKIE ) ; if ( inboundCookies != null ) { for ( String cookieString : inboundCookies ) { Cookie cookie = convertCookieString ( cookieString ) ; cookies . add ( cookie ) ; } } return cookies . toArray ( new Cookie [ 0 ] ) ; } | Converts cookies from a HttpEntity into Cookie objects |
28,258 | String getCookieString ( Cookie cookie ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( cookie . getName ( ) ) ; builder . append ( "=" ) ; builder . append ( cookie . getValue ( ) ) ; if ( cookie . getVersion ( ) > 0 ) { builder . append ( ";" + VERSION + "=" ) . append ( cookie . getVersion ( ) ) ; } if ( StringUtils . hasText ( cookie . getPath ( ) ) ) { builder . append ( ";" + PATH + "=" ) . append ( cookie . getPath ( ) ) ; } if ( StringUtils . hasText ( cookie . getDomain ( ) ) ) { builder . append ( ";" + DOMAIN + "=" ) . append ( cookie . getDomain ( ) ) ; } if ( cookie . getMaxAge ( ) > 0 ) { builder . append ( ";" + MAX_AGE + "=" ) . append ( cookie . getMaxAge ( ) ) ; } if ( StringUtils . hasText ( cookie . getComment ( ) ) ) { builder . append ( ";" + COMMENT + "=" ) . append ( cookie . getComment ( ) ) ; } if ( cookie . getSecure ( ) ) { builder . append ( ";" + SECURE ) ; } if ( cookie . isHttpOnly ( ) ) { builder . append ( ";" + HTTP_ONLY ) ; } return builder . toString ( ) ; } | Converts a given cookie into a HTTP conform cookie String |
28,259 | private Cookie convertCookieString ( String cookieString ) { Cookie cookie = new Cookie ( getCookieParam ( NAME , cookieString ) , getCookieParam ( VALUE , cookieString ) ) ; if ( cookieString . contains ( COMMENT ) ) { cookie . setComment ( getCookieParam ( COMMENT , cookieString ) ) ; } if ( cookieString . contains ( PATH ) ) { cookie . setPath ( getCookieParam ( PATH , cookieString ) ) ; } if ( cookieString . contains ( DOMAIN ) ) { cookie . setDomain ( getCookieParam ( DOMAIN , cookieString ) ) ; } if ( cookieString . contains ( MAX_AGE ) ) { cookie . setMaxAge ( Integer . valueOf ( getCookieParam ( MAX_AGE , cookieString ) ) ) ; } if ( cookieString . contains ( SECURE ) ) { cookie . setSecure ( Boolean . valueOf ( getCookieParam ( SECURE , cookieString ) ) ) ; } if ( cookieString . contains ( VERSION ) ) { cookie . setVersion ( Integer . valueOf ( getCookieParam ( VERSION , cookieString ) ) ) ; } if ( cookieString . contains ( HTTP_ONLY ) ) { cookie . setHttpOnly ( Boolean . valueOf ( getCookieParam ( HTTP_ONLY , cookieString ) ) ) ; } return cookie ; } | Converts a cookie string from a http header value into a Cookie object |
28,260 | private String getCookieParam ( String param , String cookieString ) { if ( param . equals ( NAME ) ) { return cookieString . substring ( 0 , cookieString . indexOf ( '=' ) ) ; } if ( param . equals ( VALUE ) ) { if ( cookieString . contains ( ";" ) ) { return cookieString . substring ( cookieString . indexOf ( '=' ) + 1 , cookieString . indexOf ( ';' ) ) ; } else { return cookieString . substring ( cookieString . indexOf ( '=' ) + 1 ) ; } } if ( containsFlag ( SECURE , param , cookieString ) || containsFlag ( HTTP_ONLY , param , cookieString ) ) { return String . valueOf ( true ) ; } if ( cookieString . contains ( param + '=' ) ) { final int endParam = cookieString . indexOf ( ';' , cookieString . indexOf ( param + '=' ) ) ; final int beginIndex = cookieString . indexOf ( param + '=' ) + param . length ( ) + 1 ; if ( endParam > 0 ) { return cookieString . substring ( beginIndex , endParam ) ; } else { return cookieString . substring ( beginIndex ) ; } } throw new CitrusRuntimeException ( String . format ( "Unable to get cookie argument '%s' from cookie String: %s" , param , cookieString ) ) ; } | Extract cookie param from cookie string as it was provided by Set - Cookie header . |
28,261 | protected void parseEndpointConfiguration ( BeanDefinitionBuilder endpointConfigurationBuilder , Element element , ParserContext parserContext ) { BeanDefinitionParserUtils . setPropertyValue ( endpointConfigurationBuilder , element . getAttribute ( "timeout" ) , "timeout" ) ; } | Subclasses can override this parsing method in order to provide proper endpoint configuration bean definition properties . |
28,262 | public InputActionBuilder answers ( String ... answers ) { if ( answers . length == 0 ) { throw new CitrusRuntimeException ( "Please specify proper answer possibilities for input action" ) ; } StringBuilder validAnswers = new StringBuilder ( ) ; for ( String answer : answers ) { validAnswers . append ( InputAction . ANSWER_SEPARATOR ) ; validAnswers . append ( answer ) ; } action . setValidAnswers ( validAnswers . toString ( ) . substring ( 1 ) ) ; return this ; } | Sets the valid answers . |
28,263 | public void beforeSuite ( String suiteName , String ... testGroups ) { testSuiteListener . onStart ( ) ; if ( ! CollectionUtils . isEmpty ( beforeSuite ) ) { for ( SequenceBeforeSuite sequenceBeforeSuite : beforeSuite ) { try { if ( sequenceBeforeSuite . shouldExecute ( suiteName , testGroups ) ) { sequenceBeforeSuite . execute ( createTestContext ( ) ) ; } } catch ( Exception e ) { testSuiteListener . onStartFailure ( e ) ; afterSuite ( suiteName , testGroups ) ; throw new AssertionError ( "Before suite failed with errors" , e ) ; } } testSuiteListener . onStartSuccess ( ) ; } else { testSuiteListener . onStartSuccess ( ) ; } } | Performs before suite test actions . |
28,264 | public void afterSuite ( String suiteName , String ... testGroups ) { testSuiteListener . onFinish ( ) ; if ( ! CollectionUtils . isEmpty ( afterSuite ) ) { for ( SequenceAfterSuite sequenceAfterSuite : afterSuite ) { try { if ( sequenceAfterSuite . shouldExecute ( suiteName , testGroups ) ) { sequenceAfterSuite . execute ( createTestContext ( ) ) ; } } catch ( Exception e ) { testSuiteListener . onFinishFailure ( e ) ; throw new AssertionError ( "After suite failed with errors" , e ) ; } } testSuiteListener . onFinishSuccess ( ) ; } else { testSuiteListener . onFinishSuccess ( ) ; } } | Performs after suite test actions . |
28,265 | public JmxMessage attribute ( String name , Object value ) { return attribute ( name , value , value . getClass ( ) ) ; } | Sets attribute for write operation . |
28,266 | public JmxMessage attribute ( String name , Object value , Class < ? > valueType ) { if ( mbeanInvocation == null ) { throw new CitrusRuntimeException ( "Invalid access to attribute for JMX message" ) ; } ManagedBeanInvocation . Attribute attribute = new ManagedBeanInvocation . Attribute ( ) ; attribute . setName ( name ) ; if ( value != null ) { attribute . setValueObject ( value ) ; attribute . setType ( valueType . getName ( ) ) ; } mbeanInvocation . setAttribute ( attribute ) ; return this ; } | Sets attribute for write operation with custom value type . |
28,267 | public JmxMessage operation ( String name ) { if ( mbeanInvocation == null ) { throw new CitrusRuntimeException ( "Invalid access to operation for JMX message" ) ; } ManagedBeanInvocation . Operation operation = new ManagedBeanInvocation . Operation ( ) ; operation . setName ( name ) ; mbeanInvocation . setOperation ( operation ) ; return this ; } | Sets operation for read write access . |
28,268 | public JmxMessage parameter ( Object arg , Class < ? > argType ) { if ( mbeanInvocation == null ) { throw new CitrusRuntimeException ( "Invalid access to operation parameter for JMX message" ) ; } if ( mbeanInvocation . getOperation ( ) == null ) { throw new CitrusRuntimeException ( "Invalid access to operation parameter before operation was set for JMX message" ) ; } if ( mbeanInvocation . getOperation ( ) . getParameter ( ) == null ) { mbeanInvocation . getOperation ( ) . setParameter ( new ManagedBeanInvocation . Parameter ( ) ) ; } OperationParam operationParam = new OperationParam ( ) ; operationParam . setValueObject ( arg ) ; operationParam . setType ( argType . getName ( ) ) ; mbeanInvocation . getOperation ( ) . getParameter ( ) . getParameter ( ) . add ( operationParam ) ; return this ; } | Adds operation parameter with custom parameter type . |
28,269 | public Message dispatchMessage ( Message request , String mappingKey ) { return mappingStrategy . getEndpointAdapter ( mappingKey ) . handleMessage ( request ) ; } | Consolidate mapping strategy in order to find dispatch incoming request to endpoint adapter according to mapping key that was extracted before from message content . |
28,270 | protected void enrichEndpointConfiguration ( EndpointConfiguration endpointConfiguration , Map < String , String > parameters , TestContext context ) { for ( Map . Entry < String , String > parameterEntry : parameters . entrySet ( ) ) { Field field = ReflectionUtils . findField ( endpointConfiguration . getClass ( ) , parameterEntry . getKey ( ) ) ; if ( field == null ) { throw new CitrusRuntimeException ( String . format ( "Unable to find parameter field on endpoint configuration '%s'" , parameterEntry . getKey ( ) ) ) ; } Method setter = ReflectionUtils . findMethod ( endpointConfiguration . getClass ( ) , "set" + parameterEntry . getKey ( ) . substring ( 0 , 1 ) . toUpperCase ( ) + parameterEntry . getKey ( ) . substring ( 1 ) , field . getType ( ) ) ; if ( setter == null ) { throw new CitrusRuntimeException ( String . format ( "Unable to find parameter setter on endpoint configuration '%s'" , "set" + parameterEntry . getKey ( ) . substring ( 0 , 1 ) . toUpperCase ( ) + parameterEntry . getKey ( ) . substring ( 1 ) ) ) ; } if ( parameterEntry . getValue ( ) != null ) { ReflectionUtils . invokeMethod ( setter , endpointConfiguration , TypeConversionUtils . convertStringToType ( parameterEntry . getValue ( ) , field . getType ( ) , context ) ) ; } else { ReflectionUtils . invokeMethod ( setter , endpointConfiguration , field . getType ( ) . cast ( null ) ) ; } } } | Sets properties on endpoint configuration using method reflection . |
28,271 | protected Map < String , String > getEndpointConfigurationParameters ( Map < String , String > parameters , Class < ? extends EndpointConfiguration > endpointConfigurationType ) { Map < String , String > params = new HashMap < String , String > ( ) ; for ( Map . Entry < String , String > parameterEntry : parameters . entrySet ( ) ) { Field field = ReflectionUtils . findField ( endpointConfigurationType , parameterEntry . getKey ( ) ) ; if ( field != null ) { params . put ( parameterEntry . getKey ( ) , parameterEntry . getValue ( ) ) ; } } return params ; } | Removes non config parameters from list of endpoint parameters according to given endpoint configuration type . All parameters that do not reside to a endpoint configuration setting are removed so the result is a qualified list of endpoint configuration parameters . |
28,272 | protected String getParameterString ( Map < String , String > parameters , Class < ? extends EndpointConfiguration > endpointConfigurationType ) { StringBuilder paramString = new StringBuilder ( ) ; for ( Map . Entry < String , String > parameterEntry : parameters . entrySet ( ) ) { Field field = ReflectionUtils . findField ( endpointConfigurationType , parameterEntry . getKey ( ) ) ; if ( field == null ) { if ( paramString . length ( ) == 0 ) { paramString . append ( "?" ) . append ( parameterEntry . getKey ( ) ) ; if ( parameterEntry . getValue ( ) != null ) { paramString . append ( "=" ) . append ( parameterEntry . getValue ( ) ) ; } } else { paramString . append ( "&" ) . append ( parameterEntry . getKey ( ) ) ; if ( parameterEntry . getValue ( ) != null ) { paramString . append ( "=" ) . append ( parameterEntry . getValue ( ) ) ; } } } } return paramString . toString ( ) ; } | Filters non endpoint configuration parameters from parameter list and puts them together as parameters string . According to given endpoint configuration type only non endpoint configuration settings are added to parameter string . |
28,273 | private com . github . dockerjava . api . DockerClient createDockerClient ( ) { return DockerClientImpl . getInstance ( getDockerClientConfig ( ) ) . withDockerCmdExecFactory ( new JerseyDockerCmdExecFactory ( ) ) ; } | Creates new Docker client instance with configuration . |
28,274 | public com . github . dockerjava . api . DockerClient getDockerClient ( ) { if ( dockerClient == null ) { dockerClient = createDockerClient ( ) ; } return dockerClient ; } | Constructs or gets the docker client implementation . |
28,275 | private void purgeQueue ( String queueName , Session session ) throws JMSException { purgeDestination ( getDestination ( session , queueName ) , session , queueName ) ; } | Purges a queue destination identified by its name . |
28,276 | private void purgeQueue ( Queue queue , Session session ) throws JMSException { purgeDestination ( queue , session , queue . getQueueName ( ) ) ; } | Purges a queue destination . |
28,277 | private void purgeDestination ( Destination destination , Session session , String destinationName ) throws JMSException { if ( log . isDebugEnabled ( ) ) { log . debug ( "Try to purge destination " + destinationName ) ; } int messagesPurged = 0 ; MessageConsumer messageConsumer = session . createConsumer ( destination ) ; try { javax . jms . Message message ; do { message = ( receiveTimeout >= 0 ) ? messageConsumer . receive ( receiveTimeout ) : messageConsumer . receive ( ) ; if ( message != null ) { log . debug ( "Removed message from destination " + destinationName ) ; messagesPurged ++ ; try { Thread . sleep ( sleepTime ) ; } catch ( InterruptedException e ) { log . warn ( "Interrupted during wait" , e ) ; } } } while ( message != null ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Purged " + messagesPurged + " messages from destination" ) ; } } finally { JmsUtils . closeMessageConsumer ( messageConsumer ) ; } } | Purge destination by receiving all available messages . |
28,278 | private Destination getDestination ( Session session , String queueName ) throws JMSException { return new DynamicDestinationResolver ( ) . resolveDestinationName ( session , queueName , false ) ; } | Resolves destination by given name . |
28,279 | protected Connection createConnection ( ) throws JMSException { if ( connectionFactory instanceof QueueConnectionFactory ) { return ( ( QueueConnectionFactory ) connectionFactory ) . createQueueConnection ( ) ; } return connectionFactory . createConnection ( ) ; } | Create queue connection . |
28,280 | protected Session createSession ( Connection connection ) throws JMSException { if ( connection instanceof QueueConnection ) { return ( ( QueueConnection ) connection ) . createQueueSession ( false , Session . AUTO_ACKNOWLEDGE ) ; } return connection . createSession ( false , Session . AUTO_ACKNOWLEDGE ) ; } | Create queue session . |
28,281 | public SecurityHandler getObject ( ) throws Exception { ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler ( ) ; securityHandler . setAuthenticator ( authenticator ) ; securityHandler . setRealmName ( realm ) ; for ( Entry < String , Constraint > constraint : constraints . entrySet ( ) ) { ConstraintMapping constraintMapping = new ConstraintMapping ( ) ; constraintMapping . setConstraint ( constraint . getValue ( ) ) ; constraintMapping . setPathSpec ( constraint . getKey ( ) ) ; securityHandler . addConstraintMapping ( constraintMapping ) ; } securityHandler . setLoginService ( loginService ) ; return securityHandler ; } | Construct new security handler for basic authentication . |
28,282 | public void afterPropertiesSet ( ) throws Exception { if ( loginService == null ) { loginService = new SimpleLoginService ( ) ; ( ( SimpleLoginService ) loginService ) . setName ( realm ) ; } } | Initialize member variables if not set by user in application context . |
28,283 | private void writeFtpReply ( FtpSession session , FtpMessage response ) { try { CommandResultType commandResult = response . getPayload ( CommandResultType . class ) ; FtpReply reply = new DefaultFtpReply ( Integer . valueOf ( commandResult . getReplyCode ( ) ) , commandResult . getReplyString ( ) ) ; session . write ( reply ) ; } catch ( FtpException e ) { throw new CitrusRuntimeException ( "Failed to write ftp reply" , e ) ; } } | Construct ftp reply from response message and write reply to given session . |
28,284 | public static List < String > getParameterList ( String parameterString ) { List < String > parameterList = new ArrayList < > ( ) ; StringTokenizer tok = new StringTokenizer ( parameterString , "," ) ; while ( tok . hasMoreElements ( ) ) { String param = tok . nextToken ( ) . trim ( ) ; parameterList . add ( cutOffSingleQuotes ( param ) ) ; } List < String > postProcessed = new ArrayList < > ( ) ; for ( int i = 0 ; i < parameterList . size ( ) ; i ++ ) { int next = i + 1 ; String processed = parameterList . get ( i ) ; if ( processed . startsWith ( "'" ) && ! processed . endsWith ( "'" ) ) { while ( next < parameterList . size ( ) ) { if ( parameterString . contains ( processed + ", " + parameterList . get ( next ) ) ) { processed += ", " + parameterList . get ( next ) ; } else if ( parameterString . contains ( processed + "," + parameterList . get ( next ) ) ) { processed += "," + parameterList . get ( next ) ; } else if ( parameterString . contains ( processed + " , " + parameterList . get ( next ) ) ) { processed += " , " + parameterList . get ( next ) ; } else { processed += parameterList . get ( next ) ; } i ++ ; if ( parameterList . get ( next ) . endsWith ( "'" ) ) { break ; } else { next ++ ; } } } postProcessed . add ( cutOffSingleQuotes ( processed ) ) ; } return postProcessed ; } | Convert a parameter string to a list of parameters . |
28,285 | protected void executeActions ( TestContext context ) { context . setVariable ( indexName , String . valueOf ( index ) ) ; for ( TestAction action : actions ) { setActiveAction ( action ) ; action . execute ( context ) ; } } | Executes the nested test actions . |
28,286 | protected boolean checkCondition ( TestContext context ) { if ( conditionExpression != null ) { return conditionExpression . evaluate ( index , context ) ; } String conditionString = condition ; if ( conditionString . indexOf ( Citrus . VARIABLE_PREFIX + indexName + Citrus . VARIABLE_SUFFIX ) != - 1 ) { Properties props = new Properties ( ) ; props . put ( indexName , String . valueOf ( index ) ) ; conditionString = new PropertyPlaceholderHelper ( Citrus . VARIABLE_PREFIX , Citrus . VARIABLE_SUFFIX ) . replacePlaceholders ( conditionString , props ) ; } conditionString = context . replaceDynamicContentInString ( conditionString ) ; if ( ValidationMatcherUtils . isValidationMatcherExpression ( conditionString ) ) { try { ValidationMatcherUtils . resolveValidationMatcher ( "iteratingCondition" , String . valueOf ( index ) , conditionString , context ) ; return true ; } catch ( AssertionError e ) { return false ; } } if ( conditionString . indexOf ( indexName ) != - 1 ) { conditionString = conditionString . replaceAll ( indexName , String . valueOf ( index ) ) ; } return BooleanExpressionParser . evaluate ( conditionString ) ; } | Check aborting condition . |
28,287 | private ObjectFactory getObjectFactory ( ) throws IllegalAccessException { if ( Env . INSTANCE . get ( ObjectFactory . class . getName ( ) ) . equals ( CitrusObjectFactory . class . getName ( ) ) ) { return CitrusObjectFactory . instance ( ) ; } else if ( Env . INSTANCE . get ( ObjectFactory . class . getName ( ) ) . equals ( CitrusSpringObjectFactory . class . getName ( ) ) ) { return CitrusSpringObjectFactory . instance ( ) ; } return ObjectFactoryLoader . loadObjectFactory ( new ResourceLoaderClassFinder ( resourceLoader , Thread . currentThread ( ) . getContextClassLoader ( ) ) , Env . INSTANCE . get ( ObjectFactory . class . getName ( ) ) ) ; } | Gets the object factory instance that is configured in environment . |
28,288 | public static void initializeCitrus ( ApplicationContext applicationContext ) { if ( citrus != null ) { if ( ! citrus . getApplicationContext ( ) . equals ( applicationContext ) ) { log . warn ( "Citrus instance has already been initialized - creating new instance and shutting down current instance" ) ; if ( citrus . getApplicationContext ( ) instanceof ConfigurableApplicationContext ) { ( ( ConfigurableApplicationContext ) citrus . getApplicationContext ( ) ) . stop ( ) ; } } else { return ; } } citrus = Citrus . newInstance ( applicationContext ) ; } | Initializes Citrus instance with given application context . |
28,289 | protected void executeStatements ( TestContext context ) { for ( String stmt : statements ) { try { final String toExecute ; if ( stmt . trim ( ) . endsWith ( ";" ) ) { toExecute = context . replaceDynamicContentInString ( stmt . trim ( ) . substring ( 0 , stmt . trim ( ) . length ( ) - 1 ) ) ; } else { toExecute = context . replaceDynamicContentInString ( stmt . trim ( ) ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Executing SQL statement: " + toExecute ) ; } getJdbcTemplate ( ) . execute ( toExecute ) ; log . info ( "SQL statement execution successful" ) ; } catch ( Exception e ) { if ( ignoreErrors ) { log . error ( "Ignoring error while executing SQL statement: " + e . getLocalizedMessage ( ) ) ; continue ; } else { throw new CitrusRuntimeException ( e ) ; } } } } | Run all SQL statements . |
28,290 | private void dispatch ( final ProcessingMessage message ) throws ProcessingException { final LogLevel level = message . getLogLevel ( ) ; if ( level . compareTo ( exceptionThreshold ) >= 0 ) throw message . asException ( ) ; if ( level . compareTo ( currentLevel ) > 0 ) currentLevel = level ; if ( level . compareTo ( logLevel ) >= 0 ) log ( message ) ; } | Main dispatch method |
28,291 | private void addRequestCachingFilter ( ) { FilterMapping filterMapping = new FilterMapping ( ) ; filterMapping . setFilterName ( "request-caching-filter" ) ; filterMapping . setPathSpec ( "/*" ) ; FilterHolder filterHolder = new FilterHolder ( new RequestCachingServletFilter ( ) ) ; filterHolder . setName ( "request-caching-filter" ) ; servletHandler . addFilter ( filterHolder , filterMapping ) ; } | Adds request caching filter used for not using request data when logging incoming requests |
28,292 | private void addGzipFilter ( ) { FilterMapping filterMapping = new FilterMapping ( ) ; filterMapping . setFilterName ( "gzip-filter" ) ; filterMapping . setPathSpec ( "/*" ) ; FilterHolder filterHolder = new FilterHolder ( new GzipServletFilter ( ) ) ; filterHolder . setName ( "gzip-filter" ) ; servletHandler . addFilter ( filterHolder , filterMapping ) ; } | Adds gzip filter for automatic response messages compressing . |
28,293 | private boolean containsNode ( NodeList findings , Node node ) { for ( int i = 0 ; i < findings . getLength ( ) ; i ++ ) { if ( findings . item ( i ) . equals ( node ) ) { return true ; } } return false ; } | Checks if given node set contains node . |
28,294 | private NamespaceContext buildNamespaceContext ( Node node ) { SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext ( ) ; Map < String , String > namespaces = XMLUtils . lookupNamespaces ( node . getOwnerDocument ( ) ) ; namespaces . putAll ( namespaceContextBuilder . getNamespaceMappings ( ) ) ; simpleNamespaceContext . setBindings ( namespaces ) ; return simpleNamespaceContext ; } | Builds namespace context with dynamic lookup on received node document and global namespace mappings from namespace context builder . |
28,295 | public Delete delete ( String path ) { Delete command = new Delete ( ) ; command . path ( path ) ; command . version ( DEFAULT_VERSION ) ; action . setCommand ( command ) ; return command ; } | Adds a delete command . |
28,296 | public GetData get ( String path ) { GetData command = new GetData ( ) ; command . path ( path ) ; action . setCommand ( command ) ; return command ; } | Adds a get - data command . |
28,297 | public SetData set ( String path , String data ) { SetData command = new SetData ( ) ; command . path ( path ) ; command . data ( data ) ; command . version ( 0 ) ; action . setCommand ( command ) ; return command ; } | Adds a set - data command . |
28,298 | public boolean handleRequest ( MessageContext messageContext ) throws WebServiceClientException { try { logRequest ( "Sending SOAP request" , messageContext , false ) ; } catch ( SoapEnvelopeException e ) { log . warn ( "Unable to write SOAP request to logger" , e ) ; } catch ( TransformerException e ) { log . warn ( "Unable to write SOAP request to logger" , e ) ; } return true ; } | Write SOAP request to logger before sending . |
28,299 | public boolean handleResponse ( MessageContext messageContext ) throws WebServiceClientException { try { logResponse ( "Received SOAP response" , messageContext , true ) ; } catch ( SoapEnvelopeException e ) { log . warn ( "Unable to write SOAP response to logger" , e ) ; } catch ( TransformerException e ) { log . warn ( "Unable to write SOAP response to logger" , e ) ; } return true ; } | Write SOAP response to logger . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.