idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
39,700
public void copyTo ( String localPath , String remotePath ) throws Exception { FileInputStream fis = null ; String rfile = remotePath ; String localfile = localPath ; boolean ptimestamp = true ; String command = "scp " + ( ptimestamp ? "-p" : "" ) + " -d -t " + rfile ; Channel channel = session . openChannel ( "exec" ) ; ( ( ChannelExec ) channel ) . setCommand ( command ) ; OutputStream out = channel . getOutputStream ( ) ; InputStream in = channel . getInputStream ( ) ; channel . connect ( ) ; if ( checkAck ( in ) != 0 ) { return ; } File myFile = new File ( localfile ) ; List < String > files = new ArrayList < String > ( ) ; if ( myFile . isDirectory ( ) ) { File [ ] listFiles = myFile . listFiles ( ) ; for ( File file : listFiles ) { files . add ( file . getAbsolutePath ( ) ) ; } } else { files . add ( localfile ) ; } for ( String lfile : files ) { File _lfile = new File ( lfile ) ; if ( ptimestamp ) { command = "T" + ( _lfile . lastModified ( ) / 1000 ) + " 0" ; command += ( " " + ( _lfile . lastModified ( ) / 1000 ) + " 0\n" ) ; out . write ( command . getBytes ( ) ) ; out . flush ( ) ; if ( checkAck ( in ) != 0 ) { break ; } } long filesize = _lfile . length ( ) ; command = "C0644 " + filesize + " " ; if ( lfile . lastIndexOf ( '/' ) > 0 ) { command += lfile . substring ( lfile . lastIndexOf ( '/' ) + 1 ) ; } else { command += lfile ; } command += "\n" ; out . write ( command . getBytes ( ) ) ; out . flush ( ) ; if ( checkAck ( in ) != 0 ) { break ; } fis = new FileInputStream ( lfile ) ; byte [ ] buf = new byte [ 1024 ] ; while ( true ) { int len = fis . read ( buf , 0 , buf . length ) ; if ( len <= 0 ) { break ; } out . write ( buf , 0 , len ) ; } fis . close ( ) ; fis = null ; buf [ 0 ] = 0 ; out . write ( buf , 0 , 1 ) ; out . flush ( ) ; if ( checkAck ( in ) != 0 ) { break ; } } out . close ( ) ; channel . disconnect ( ) ; }
Copy localPath to remotePath using the session created
39,701
public void runCommand ( String command ) throws Exception { String result = "" ; String extras = "export PYTHONWARNINGS=\"ignore:Unverified HTTPS request\" && " ; Channel channel = session . openChannel ( "exec" ) ; ( ( ChannelExec ) channel ) . setCommand ( extras + command ) ; channel . setInputStream ( null ) ; ( ( ChannelExec ) channel ) . setErrStream ( System . err ) ; InputStream in = channel . getInputStream ( ) ; ( ( ChannelExec ) channel ) . setPty ( true ) ; channel . connect ( ) ; byte [ ] tmp = new byte [ 1024 ] ; while ( true ) { while ( in . available ( ) > 0 ) { int i = in . read ( tmp , 0 , 1024 ) ; if ( i < 0 ) { break ; } result = result + new String ( tmp , 0 , i ) ; } this . result = result ; this . setResult ( result ) ; if ( channel . isClosed ( ) ) { if ( in . available ( ) > 0 ) { continue ; } this . exitStatus = channel . getExitStatus ( ) ; break ; } try { Thread . sleep ( 1000 ) ; } catch ( Exception ee ) { } } channel . disconnect ( ) ; }
Execute the command in the session created
39,702
@ Given ( "^I authenticate to DCOS cluster '(.+?)' using email '(.+?)'( with user '(.+?)'( and password '(.+?)'| and pem file '(.+?)'))?$" ) public void authenticateDCOSpem ( String remoteHost , String email , String foo , String user , String bar , String password , String pemFile ) throws Exception { String DCOSsecret ; if ( foo == null ) { commonspec . setRemoteSSHConnection ( new RemoteSSHConnection ( "root" , "stratio" , remoteHost , null ) ) ; } else { commonspec . setRemoteSSHConnection ( new RemoteSSHConnection ( user , password , remoteHost , pemFile ) ) ; } commonspec . getRemoteSSHConnection ( ) . runCommand ( "sudo cat /var/lib/dcos/dcos-oauth/auth-token-secret" ) ; DCOSsecret = commonspec . getRemoteSSHConnection ( ) . getResult ( ) . trim ( ) ; setDCOSCookie ( DCOSsecret , email ) ; }
Authenticate in a DCOS cluster
39,703
@ Given ( "^I( do not)? set sso token using host '(.+?)' with user '(.+?)' and password '(.+?)'( and tenant '(.+?)')?$" ) public void setGoSecSSOCookie ( String set , String ssoHost , String userName , String passWord , String foo , String tenant ) throws Exception { if ( set == null ) { HashMap < String , String > ssoCookies = new GosecSSOUtils ( ssoHost , userName , passWord , tenant ) . ssoTokenGenerator ( ) ; String [ ] tokenList = { "user" , "dcos-acs-auth-cookie" } ; List < com . ning . http . client . cookie . Cookie > cookiesAtributes = addSsoToken ( ssoCookies , tokenList ) ; commonspec . setCookies ( cookiesAtributes ) ; } }
Generate token to authenticate in gosec SSO
39,704
@ Given ( "^I save the IP of an unused node in hosts '(.+?)' in the in environment variable '(.+?)'?$" ) public void getUnusedNode ( String hosts , String envVar ) throws Exception { Set < String > hostList = new HashSet ( Arrays . asList ( hosts . split ( "," ) ) ) ; commonspec . executeCommand ( "dcos task | awk '{print $2}'" , 0 , null ) ; String results = commonspec . getRemoteSSHConnection ( ) . getResult ( ) ; Set < String > usedHosts = new HashSet ( Arrays . asList ( results . replaceAll ( "\r" , "" ) . split ( "\n" ) ) ) ; hostList . removeAll ( usedHosts ) ; if ( hostList . size ( ) == 0 ) { throw new IllegalStateException ( "No unused nodes in the cluster." ) ; } else { ThreadProperty . set ( envVar , hostList . iterator ( ) . next ( ) ) ; } }
Checks if there are any unused nodes in the cluster and returns the IP of one of them . REQUIRES A PREVIOUSLY - ESTABLISHED SSH CONNECTION TO DCOS - CLI TO WORK
39,705
@ Given ( "^I convert jsonSchema '(.+?)' to json and save it in variable '(.+?)'" ) public void convertJSONSchemaToJSON ( String jsonSchema , String envVar ) throws Exception { String json = commonspec . parseJSONSchema ( new JSONObject ( jsonSchema ) ) . toString ( ) ; ThreadProperty . set ( envVar , json ) ; }
Convert jsonSchema to json
39,706
@ Given ( "^json (.+?) matches schema (.+?)$" ) public void jsonMatchesSchema ( String json , String schema ) throws Exception { JSONObject jsonschema = new JSONObject ( schema ) ; JSONObject jsondeploy = new JSONObject ( json ) ; commonspec . matchJsonToSchema ( jsonschema , jsondeploy ) ; }
Check if json is validated against a schema
39,707
@ Given ( "^I get service '(.+?)' health status in cluster '(.+?)' and save it in variable '(.+?)'" ) public void getServiceHealthStatus ( String service , String cluster , String envVar ) throws Exception { String health = commonspec . retrieveHealthServiceStatus ( service , cluster ) ; ThreadProperty . set ( envVar , health ) ; }
Get service health status
39,708
@ Given ( "^I destroy service '(.+?)' in cluster '(.+?)'" ) public void destroyService ( String service , String cluster ) throws Exception { String endPoint = "/service/deploy-api/deploy/uninstall?app=" + service ; Future response ; this . commonspec . setRestProtocol ( "https://" ) ; this . commonspec . setRestHost ( cluster ) ; this . commonspec . setRestPort ( ":443" ) ; response = this . commonspec . generateRequest ( "DELETE" , true , null , null , endPoint , null , "json" ) ; this . commonspec . setResponse ( "DELETE" , ( Response ) response . get ( ) ) ; assertThat ( this . commonspec . getResponse ( ) . getStatusCode ( ) ) . as ( "It hasn't been possible to destroy service: " + service ) . isIn ( Arrays . asList ( 200 , 202 ) ) ; }
Destroy specified service
39,709
@ When ( "^All resources from service '(.+?)' have been freed$" ) public void checkResources ( String service ) throws Exception { Future < Response > response = commonspec . generateRequest ( "GET" , true , null , null , "/mesos/state-summary" , null , null ) ; String json = "[" + response . get ( ) . getResponseBody ( ) + "]" ; String parsedElement = "$..frameworks[?(@.active==false)].name" ; String value = commonspec . getJSONPathString ( json , parsedElement , null ) ; Assertions . assertThat ( value ) . as ( "Inactive services" ) . doesNotContain ( service ) ; }
Check if resources are released after uninstall and framework doesn t appear as inactive on mesos
39,710
@ Then ( "^I add a new DCOS label with key '(.+?)' and value '(.+?)' to the service '(.+?)'?$" ) public void sendAppendRequest ( String key , String value , String service ) throws Exception { commonspec . runCommandAndGetResult ( "touch " + service + ".json && dcos marathon app show " + service + " > /dcos/" + service + ".json" ) ; commonspec . runCommandAndGetResult ( "cat /dcos/" + service + ".json" ) ; String configFile = commonspec . getRemoteSSHConnection ( ) . getResult ( ) ; String myValue = commonspec . getJSONPathString ( configFile , ".labels" , "0" ) ; String myJson = commonspec . updateMarathonJson ( commonspec . removeJSONPathElement ( configFile , "$.labels" ) ) ; String newValue = myValue . replaceFirst ( "\\{" , "{\"" + key + "\": \"" + value + "\", " ) ; newValue = "\"labels\":" + newValue ; String myFinalJson = myJson . replaceFirst ( "\\{" , "{" + newValue . replace ( "\\n" , "\\\\n" ) + "," ) ; if ( myFinalJson . contains ( "uris" ) ) { String test = myFinalJson . replaceAll ( "\"uris\"" , "\"none\"" ) ; commonspec . runCommandAndGetResult ( "echo '" + test + "' > /dcos/final" + service + ".json" ) ; } else { commonspec . runCommandAndGetResult ( "echo '" + myFinalJson + "' > /dcos/final" + service + ".json" ) ; } commonspec . runCommandAndGetResult ( "dcos marathon app update " + service + " < /dcos/final" + service + ".json" ) ; commonspec . setCommandExitStatus ( commonspec . getRemoteSSHConnection ( ) . getExitStatus ( ) ) ; }
A PUT request over the body value .
39,711
@ Then ( "^I modify marathon environment variable '(.+?)' with value '(.+?)' for service '(.+?)'?$" ) public void setMarathonProperty ( String key , String value , String service ) throws Exception { commonspec . runCommandAndGetResult ( "touch " + service + "-env.json && dcos marathon app show " + service + " > /dcos/" + service + "-env.json" ) ; commonspec . runCommandAndGetResult ( "cat /dcos/" + service + "-env.json" ) ; String configFile = commonspec . getRemoteSSHConnection ( ) . getResult ( ) ; String myJson1 = commonspec . replaceJSONPathElement ( configFile , key , value ) ; String myJson4 = commonspec . updateMarathonJson ( myJson1 ) ; String myJson = myJson4 . replaceAll ( "\"uris\"" , "\"none\"" ) ; commonspec . runCommandAndGetResult ( "echo '" + myJson + "' > /dcos/final" + service + "-env.json" ) ; commonspec . runCommandAndGetResult ( "dcos marathon app update " + service + " < /dcos/final" + service + "-env.json" ) ; commonspec . setCommandExitStatus ( commonspec . getRemoteSSHConnection ( ) . getExitStatus ( ) ) ; }
Set a environment variable in marathon and deploy again .
39,712
@ Then ( "^service '(.+?)' status in cluster '(.+?)' is '(suspended|running|deploying)'( in less than '(\\d+?)' seconds checking every '(\\d+?)' seconds)?" ) public void serviceStatusCheck ( String service , String cluster , String status , String foo , Integer totalWait , Integer interval ) throws Exception { String response ; Integer i = 0 ; boolean matched ; response = commonspec . retrieveServiceStatus ( service , cluster ) ; if ( foo != null ) { matched = status . matches ( response ) ; while ( ! matched && i < totalWait ) { this . commonspec . getLogger ( ) . info ( "Service status not found yet after " + i + " seconds" ) ; i = i + interval ; response = commonspec . retrieveServiceStatus ( service , cluster ) ; matched = status . matches ( response ) ; } } assertThat ( status ) . as ( "Expected status: " + status + " doesn't match obtained one: " + response ) . matches ( response ) ; }
Check service status has value specified
39,713
@ Then ( "^The role '(.+?)' of the service '(.+?)' with instance '(.+?)' complies the constraints '(.+?)'$" ) public void checkComponentConstraints ( String role , String service , String instance , String constraints ) throws Exception { checkComponentConstraint ( role , service , instance , constraints . split ( "," ) ) ; }
Check if a role of a service complies the established constraints
39,714
@ Given ( "^I open a ssh connection to '(.+?)'( in port '(.+?)')? with user '(.+?)'( and password '(.+?)')?( using pem file '(.+?)')?$" ) public void openSSHConnection ( String remoteHost , String tmp , String remotePort , String user , String foo , String password , String bar , String pemFile ) throws Exception { if ( ( pemFile == null ) || ( pemFile . equals ( "none" ) ) ) { if ( password == null ) { throw new Exception ( "You have to provide a password or a pem file to be used for connection" ) ; } commonspec . setRemoteSSHConnection ( new RemoteSSHConnection ( user , password , remoteHost , remotePort , null ) ) ; commonspec . getLogger ( ) . debug ( "Opening ssh connection with password: { " + password + "}" , commonspec . getRemoteSSHConnection ( ) ) ; } else { File pem = new File ( pemFile ) ; if ( ! pem . exists ( ) ) { throw new Exception ( "Pem file: " + pemFile + " does not exist" ) ; } commonspec . setRemoteSSHConnection ( new RemoteSSHConnection ( user , null , remoteHost , remotePort , pemFile ) ) ; commonspec . getLogger ( ) . debug ( "Opening ssh connection with pemFile: {}" , commonspec . getRemoteSSHConnection ( ) ) ; } }
Opens a ssh connection to remote host
39,715
@ Given ( "^I run '(.+?)' locally( with exit status '(.+?)')?( and save the value in environment variable '(.+?)')?$" ) public void executeLocalCommand ( String command , String foo , Integer exitStatus , String bar , String envVar ) throws Exception { if ( exitStatus == null ) { exitStatus = 0 ; } commonspec . runLocalCommand ( command ) ; commonspec . runCommandLoggerAndEnvVar ( exitStatus , envVar , Boolean . TRUE ) ; Assertions . assertThat ( commonspec . getCommandExitStatus ( ) ) . isEqualTo ( exitStatus ) ; }
Executes the command specified in local system
39,716
@ Then ( "^the command output contains '(.+?)'$" ) public void findShellOutput ( String search ) throws Exception { assertThat ( commonspec . getCommandResult ( ) ) . as ( "Contains " + search + "." ) . contains ( search ) ; }
Check the existence of a text at a command output
39,717
@ Then ( "^the command output does not contain '(.+?)'$" ) public void notFindShellOutput ( String search ) throws Exception { assertThat ( commonspec . getCommandResult ( ) ) . as ( "NotContains " + search + "." ) . doesNotContain ( search ) ; }
Check the non existence of a text at a command output
39,718
@ Then ( "^the command exit status is '(.+?)'$" ) public void checkShellExitStatus ( int expectedExitStatus ) throws Exception { assertThat ( commonspec . getCommandExitStatus ( ) ) . as ( "Is equal to " + expectedExitStatus + "." ) . isEqualTo ( expectedExitStatus ) ; }
Check the exitStatus of previous command execution matches the expected one
39,719
@ Given ( "^I create a Cassandra index named '(.+?)' in table '(.+?)' using magic_column '(.+?)' using keyspace '(.+?)'$" ) public void createBasicMapping ( String index_name , String table , String column , String keyspace ) throws Exception { String query = "CREATE INDEX " + index_name + " ON " + table + " (" + column + ");" ; commonspec . getCassandraClient ( ) . executeQuery ( query ) ; }
Create a basic Index .
39,720
@ Given ( "^I( securely)? connect to '(Cassandra|Mongo|Elasticsearch)' cluster at '(.+)'$" ) public void connect ( String secured , String clusterType , String url ) throws DBException , UnknownHostException { switch ( clusterType ) { case "Cassandra" : commonspec . getCassandraClient ( ) . setHost ( url ) ; commonspec . getCassandraClient ( ) . connect ( secured ) ; break ; case "Mongo" : commonspec . getMongoDBClient ( ) . connect ( ) ; break ; case "Elasticsearch" : LinkedHashMap < String , Object > settings_map = new LinkedHashMap < String , Object > ( ) ; settings_map . put ( "cluster.name" , System . getProperty ( "ES_CLUSTER" , ES_DEFAULT_CLUSTER_NAME ) ) ; commonspec . getElasticSearchClient ( ) . setSettings ( settings_map ) ; commonspec . getElasticSearchClient ( ) . connect ( ) ; break ; default : throw new DBException ( "Unknown cluster type" ) ; } }
Connect to cluster .
39,721
@ Given ( "^I connect to Elasticsearch cluster at host '(.+?)'( using native port '(.+?)')?( using cluster name '(.+?)')?$" ) public void connectToElasticSearch ( String host , String foo , String nativePort , String bar , String clusterName ) throws DBException , UnknownHostException , NumberFormatException { LinkedHashMap < String , Object > settings_map = new LinkedHashMap < String , Object > ( ) ; if ( clusterName != null ) { settings_map . put ( "cluster.name" , clusterName ) ; } else { settings_map . put ( "cluster.name" , ES_DEFAULT_CLUSTER_NAME ) ; } commonspec . getElasticSearchClient ( ) . setSettings ( settings_map ) ; if ( nativePort != null ) { commonspec . getElasticSearchClient ( ) . setNativePort ( Integer . valueOf ( nativePort ) ) ; } else { commonspec . getElasticSearchClient ( ) . setNativePort ( ES_DEFAULT_NATIVE_PORT ) ; } commonspec . getElasticSearchClient ( ) . setHost ( host ) ; commonspec . getElasticSearchClient ( ) . connect ( ) ; }
Connect to ElasticSearch using custom parameters
39,722
@ Given ( "^I obtain elasticsearch cluster name in '([^:]+?)(:.+?)?' and save it in variable '(.+?)'?$" ) public void saveElasticCluster ( String host , String port , String envVar ) throws Exception { commonspec . setRestProtocol ( "http://" ) ; commonspec . setRestHost ( host ) ; commonspec . setRestPort ( port ) ; Future < Response > response ; response = commonspec . generateRequest ( "GET" , false , null , null , "/" , "" , "json" , "" ) ; commonspec . setResponse ( "GET" , response . get ( ) ) ; String json ; String parsedElement ; json = commonspec . getResponse ( ) . getResponse ( ) ; parsedElement = "$..cluster_name" ; String json2 = "[" + json + "]" ; String value = commonspec . getJSONPathString ( json2 , parsedElement , "0" ) ; if ( value == null ) { throw new Exception ( "No cluster name is found" ) ; } else { ThreadProperty . set ( envVar , value ) ; } }
Save clustername of elasticsearch in an environment varible for future use .
39,723
@ Given ( "^I insert into a MongoDB database '(.+?)' and table '(.+?)' this values:$" ) public void insertOnMongoTable ( String dataBase , String tabName , DataTable table ) { commonspec . getMongoDBClient ( ) . connectToMongoDBDataBase ( dataBase ) ; commonspec . getMongoDBClient ( ) . insertIntoMongoDBCollection ( tabName , table ) ; }
Insert data in a MongoDB table .
39,724
@ Given ( "^I drop every document at a MongoDB database '(.+?)' and table '(.+?)'" ) public void truncateTableInMongo ( String database , String table ) { commonspec . getMongoDBClient ( ) . connectToMongoDBDataBase ( database ) ; commonspec . getMongoDBClient ( ) . dropAllDataMongoDBCollection ( table ) ; }
Truncate table in MongoDB .
39,725
@ Given ( "^I insert into MongoDB database '(.+?)' and collection '(.+?)' the document from schema '(.+?)'$" ) public void insertOnMongoTable ( String dataBase , String collection , String document ) throws Exception { String retrievedDoc = commonspec . retrieveData ( document , "json" ) ; commonspec . getMongoDBClient ( ) . connectToMongoDBDataBase ( dataBase ) ; commonspec . getMongoDBClient ( ) . insertDocIntoMongoDBCollection ( collection , retrievedDoc ) ; }
Insert document in a MongoDB table .
39,726
@ When ( "^I execute a query over fields '(.+?)' with schema '(.+?)' of type '(json|string)' with magic_column '(.+?)' from table: '(.+?)' using keyspace: '(.+?)' with:$" ) public void sendQueryOfType ( String fields , String schema , String type , String magic_column , String table , String keyspace , DataTable modifications ) { try { commonspec . setResultsType ( "cassandra" ) ; commonspec . getCassandraClient ( ) . useKeyspace ( keyspace ) ; commonspec . getLogger ( ) . debug ( "Starting a query of type " + commonspec . getResultsType ( ) ) ; String query = "" ; if ( schema . equals ( "empty" ) && magic_column . equals ( "empty" ) ) { query = "SELECT " + fields + " FROM " + table + ";" ; } else if ( ! schema . equals ( "empty" ) && magic_column . equals ( "empty" ) ) { String retrievedData = commonspec . retrieveData ( schema , type ) ; String modifiedData = commonspec . modifyData ( retrievedData , type , modifications ) . toString ( ) ; query = "SELECT " + fields + " FROM " + table + " WHERE " + modifiedData + ";" ; } else { String retrievedData = commonspec . retrieveData ( schema , type ) ; String modifiedData = commonspec . modifyData ( retrievedData , type , modifications ) . toString ( ) ; query = "SELECT " + fields + " FROM " + table + " WHERE " + magic_column + " = '" + modifiedData + "';" ; } commonspec . getLogger ( ) . debug ( "query: {}" , query ) ; com . datastax . driver . core . ResultSet results = commonspec . getCassandraClient ( ) . executeQuery ( query ) ; commonspec . setCassandraResults ( results ) ; } catch ( Exception e ) { commonspec . getLogger ( ) . debug ( "Exception captured" ) ; commonspec . getLogger ( ) . debug ( e . toString ( ) ) ; commonspec . getExceptions ( ) . add ( e ) ; } }
Execute a query with schema over a cluster
39,727
@ When ( "^I execute an elasticsearch query over index '(.*?)' and mapping '(.*?)' and column '(.*?)' with value '(.*?)' to '(.*?)'$" ) public void elasticSearchQueryWithFilter ( String indexName , String mappingName , String columnName , String filterType , String value ) { try { commonspec . setResultsType ( "elasticsearch" ) ; commonspec . setElasticsearchResults ( commonspec . getElasticSearchClient ( ) . searchSimpleFilterElasticsearchQuery ( indexName , mappingName , columnName , value , filterType ) ) ; } catch ( Exception e ) { commonspec . getLogger ( ) . debug ( "Exception captured" ) ; commonspec . getLogger ( ) . debug ( e . toString ( ) ) ; commonspec . getExceptions ( ) . add ( e ) ; } }
Execute query with filter over elasticsearch
39,728
@ When ( "^I create a Cassandra index named '(.+?)' with schema '(.+?)' of type '(json|string)' in table '(.+?)' using magic_column '(.+?)' using keyspace '(.+?)' with:$" ) public void createCustomMapping ( String index_name , String schema , String type , String table , String magic_column , String keyspace , DataTable modifications ) throws Exception { String retrievedData = commonspec . retrieveData ( schema , type ) ; String modifiedData = commonspec . modifyData ( retrievedData , type , modifications ) . toString ( ) ; String query = "CREATE CUSTOM INDEX " + index_name + " ON " + keyspace + "." + table + "(" + magic_column + ") " + "USING 'com.stratio.cassandra.lucene.Index' WITH OPTIONS = " + modifiedData ; commonspec . getLogger ( ) . debug ( "Will execute a cassandra query: {}" , query ) ; commonspec . getCassandraClient ( ) . executeQuery ( query ) ; }
Create a Cassandra index .
39,729
@ When ( "^I create an elasticsearch index named '(.+?)'( removing existing index if exist)?$" ) public void createElasticsearchIndex ( String index , String removeIndex ) { if ( removeIndex != null && commonspec . getElasticSearchClient ( ) . indexExists ( index ) ) { commonspec . getElasticSearchClient ( ) . dropSingleIndex ( index ) ; } commonspec . getElasticSearchClient ( ) . createSingleIndex ( index ) ; }
Create an elasticsearch index .
39,730
@ When ( "^I index a document in the index named '(.+?)' using the mapping named '(.+?)' with key '(.+?)' and value '(.+?)'$" ) public void indexElasticsearchDocument ( String indexName , String mappingName , String key , String value ) throws Exception { ArrayList < XContentBuilder > mappingsource = new ArrayList < XContentBuilder > ( ) ; XContentBuilder builder = jsonBuilder ( ) . startObject ( ) . field ( key , value ) . endObject ( ) ; mappingsource . add ( builder ) ; commonspec . getElasticSearchClient ( ) . createMapping ( indexName , mappingName , mappingsource ) ; }
Index a document within a mapping type .
39,731
@ Then ( "^a Cassandra keyspace '(.+?)' exists$" ) public void assertKeyspaceOnCassandraExists ( String keyspace ) { assertThat ( commonspec . getCassandraClient ( ) . getKeyspaces ( ) ) . as ( "The keyspace " + keyspace + " exists on cassandra" ) . contains ( keyspace ) ; }
Checks if a keyspaces exists in Cassandra .
39,732
@ Then ( "^a Cassandra keyspace '(.+?)' does not exist$" ) public void assertKeyspaceOnCassandraDoesNotExist ( String keyspace ) { assertThat ( commonspec . getCassandraClient ( ) . getKeyspaces ( ) ) . as ( "The keyspace " + keyspace + " does not exist on cassandra" ) . doesNotContain ( keyspace ) ; }
Checks a keyspace does not exist in Cassandra .
39,733
@ Then ( "^a Cassandra keyspace '(.+?)' contains a table '(.+?)'$" ) public void assertTableExistsOnCassandraKeyspace ( String keyspace , String tableName ) { assertThat ( commonspec . getCassandraClient ( ) . getTables ( keyspace ) ) . as ( "The table " + tableName + "exists on cassandra" ) . contains ( tableName ) ; }
Checks if a cassandra keyspace contains a table .
39,734
@ Then ( "^a Cassandra keyspace '(.+?)' does not contain a table '(.+?)'$" ) public void assertTableDoesNotExistOnCassandraKeyspace ( String keyspace , String tableName ) { assertThat ( commonspec . getCassandraClient ( ) . getTables ( keyspace ) ) . as ( "The table " + tableName + "exists on cassandra" ) . doesNotContain ( tableName ) ; }
Checks a cassandra keyspace does not contain a table .
39,735
@ Then ( "^a Cassandra keyspace '(.+?)' contains a table '(.+?)' with '(.+?)' rows$" ) public void assertRowNumberOfTableOnCassandraKeyspace ( String keyspace , String tableName , String numberRows ) { Long numberRowsLong = Long . parseLong ( numberRows ) ; commonspec . getCassandraClient ( ) . useKeyspace ( keyspace ) ; assertThat ( commonspec . getCassandraClient ( ) . executeQuery ( "SELECT COUNT(*) FROM " + tableName + ";" ) . all ( ) . get ( 0 ) . getLong ( 0 ) ) . as ( "The table " + tableName + "exists on cassandra" ) . isEqualTo ( numberRowsLong ) ; }
Checks the number of rows in a cassandra table .
39,736
@ Then ( "^a Cassandra keyspace '(.+?)' contains a table '(.+?)' with values:$" ) public void assertValuesOfTable ( String keyspace , String tableName , DataTable data ) throws InterruptedException { commonspec . getCassandraClient ( ) . useKeyspace ( keyspace ) ; Map < String , String > dataTableColumns = extractColumnNamesAndTypes ( data . raw ( ) . get ( 0 ) ) ; String query = "SELECT * FROM " + tableName + " LIMIT 1;" ; com . datastax . driver . core . ResultSet res = commonspec . getCassandraClient ( ) . executeQuery ( query ) ; equalsColumns ( res . getColumnDefinitions ( ) , dataTableColumns ) ; List < String > selectQueries = giveQueriesList ( data , tableName , columnNames ( data . raw ( ) . get ( 0 ) ) ) ; int index = 1 ; for ( String execQuery : selectQueries ) { res = commonspec . getCassandraClient ( ) . executeQuery ( execQuery ) ; List < Row > resAsList = res . all ( ) ; assertThat ( resAsList . size ( ) ) . as ( "The query " + execQuery + " not return any result on Cassandra" ) . isGreaterThan ( 0 ) ; assertThat ( resAsList . get ( 0 ) . toString ( ) . substring ( VALUE_SUBSTRING ) ) . as ( "The resultSet is not as expected" ) . isEqualTo ( data . raw ( ) . get ( index ) . toString ( ) . replace ( "'" , "" ) ) ; index ++ ; } }
Checks if a cassandra table contains the values of a DataTable .
39,737
@ Then ( "^a Mongo dataBase '(.+?)' contains a table '(.+?)' with values:" ) public void assertValuesOfTableMongo ( String dataBase , String tableName , DataTable data ) { commonspec . getMongoDBClient ( ) . connectToMongoDBDataBase ( dataBase ) ; ArrayList < DBObject > result = ( ArrayList < DBObject > ) commonspec . getMongoDBClient ( ) . readFromMongoDBCollection ( tableName , data ) ; DBObjectsAssert . assertThat ( result ) . containedInMongoDBResult ( data ) ; }
Checks the values of a MongoDB table .
39,738
@ Then ( "^a Mongo dataBase '(.+?)' doesnt contains a table '(.+?)'$" ) public void aMongoDataBaseContainsaTable ( String database , String tableName ) { commonspec . getMongoDBClient ( ) . connectToMongoDBDataBase ( database ) ; Set < String > collectionsNames = commonspec . getMongoDBClient ( ) . getMongoDBCollections ( ) ; assertThat ( collectionsNames ) . as ( "The Mongo dataBase contains the table" ) . doesNotContain ( tableName ) ; }
Checks if a MongoDB database contains a table .
39,739
@ Then ( "^There are results found with:$" ) public void resultsMustBe ( DataTable expectedResults ) throws Exception { String type = commonspec . getResultsType ( ) ; assertThat ( type ) . isNotEqualTo ( "" ) . overridingErrorMessage ( "It's necessary to define the result type" ) ; switch ( type ) { case "cassandra" : commonspec . resultsMustBeCassandra ( expectedResults ) ; break ; case "mongo" : commonspec . resultsMustBeMongo ( expectedResults ) ; break ; case "elasticsearch" : commonspec . resultsMustBeElasticsearch ( expectedResults ) ; break ; case "csv" : commonspec . resultsMustBeCSV ( expectedResults ) ; break ; default : commonspec . getLogger ( ) . warn ( "default switch branch on results check" ) ; } }
Checks the different results of a previous query
39,740
@ Then ( "^The Elasticsearch index named '(.+?)' and mapping '(.+?)' contains a column named '(.+?)' with the value '(.+?)'$" ) public void elasticSearchIndexContainsDocument ( String indexName , String mappingName , String columnName , String columnValue ) throws Exception { Assertions . assertThat ( ( commonspec . getElasticSearchClient ( ) . searchSimpleFilterElasticsearchQuery ( indexName , mappingName , columnName , columnValue , "equals" ) . size ( ) ) > 0 ) . isTrue ( ) . withFailMessage ( "The index does not contain that document" ) ; }
Check that an elasticsearch index contains a specific document
39,741
@ When ( "^I search in LDAP using the filter '(.+?)' and the baseDn '(.+?)'$" ) public void searchLDAP ( String filter , String baseDn ) throws Exception { this . commonspec . setPreviousLdapResults ( commonspec . getLdapUtils ( ) . search ( new SearchRequest ( baseDn , filter ) ) ) ; }
Search for a LDAP object
39,742
@ Then ( "^the LDAP entry contains the attribute '(.+?)' with the value '(.+?)'$" ) public void ldapEntryContains ( String attributeName , String expectedValue ) { if ( this . commonspec . getPreviousLdapResults ( ) . isPresent ( ) ) { Assertions . assertThat ( this . commonspec . getPreviousLdapResults ( ) . get ( ) . getEntry ( ) . getAttribute ( attributeName ) . getStringValues ( ) ) . contains ( expectedValue ) ; } else { fail ( "No previous LDAP results were stored in memory" ) ; } }
Checks if the previous LDAP search contained a single Entry with a specific attribute and an expected value
39,743
@ DataProvider ( parallel = true ) public static Iterator < String [ ] > availableBrowsers ( ITestContext context , Constructor < ? > testConstructor ) throws Exception { Map < String , String > map = new HashMap < String , String > ( ) ; List < String > browsers = gridBrowsers ( map ) ; return buildIterator ( browsers ) ; }
Get the browsers available in a selenium grid .
39,744
@ DataProvider ( parallel = true ) public static Iterator < String [ ] > availableUniqueBrowsers ( ITestContext context , Constructor < ? > testConstructor ) throws Exception { Map < String , String > map = new HashMap < String , String > ( ) ; List < String > browsers = gridBrowsers ( map ) ; HashSet < String > hs = new HashSet < String > ( ) ; hs . addAll ( browsers ) ; browsers . clear ( ) ; browsers . addAll ( hs ) ; return buildIterator ( browsers ) ; }
Get unique browsers available in a selenium grid .
39,745
private static Iterator < String [ ] > buildIterator ( List < String > browsers ) { List < String [ ] > lData = Lists . newArrayList ( ) ; for ( String s : browsers ) { lData . add ( new String [ ] { s } ) ; } if ( lData . size ( ) == 0 ) { lData . add ( new String [ ] { "" } ) ; } return lData . iterator ( ) ; }
Build an String Iterator from String List .
39,746
@ Around ( value = "availableBrowsersCallPointcut()" ) public Object availableBrowsersCalls ( ProceedingJoinPoint pjp ) throws Throwable { if ( pjp . getArgs ( ) . length > 0 ) { if ( pjp . getArgs ( ) [ 0 ] instanceof ITestContext ) { if ( Arrays . asList ( ( ( ITestContext ) pjp . getArgs ( ) [ 0 ] ) . getIncludedGroups ( ) ) . contains ( "mobile" ) ) { return pjp . proceed ( ) ; } } } if ( ! "" . equals ( System . getProperty ( "FORCE_BROWSER" , "" ) ) ) { List < String [ ] > lData = Lists . newArrayList ( ) ; lData . add ( new String [ ] { System . getProperty ( "FORCE_BROWSER" ) } ) ; logger . debug ( "Forcing browser to {}" , System . getProperty ( "FORCE_BROWSER" ) ) ; return lData . iterator ( ) ; } return pjp . proceed ( ) ; }
If a System property with FORCE_BROWSER exists then Methods in BrowsersDataProvider will return its value .
39,747
@ Given ( "^I connect to Zookeeper at '(.+)'$" ) public void connectToZk ( String zookeeperHosts ) throws InterruptedException { commonspec . getZookeeperSecClient ( ) . setZookeeperSecConnection ( zookeeperHosts , 3000 ) ; commonspec . getZookeeperSecClient ( ) . connectZk ( ) ; }
Connect to zookeeper .
39,748
@ When ( "^I create the zNode '(.+?)'( with content '(.+?)')? which (IS|IS NOT) ephemeral$" ) public void createZNode ( String path , String foo , String content , boolean ephemeral ) throws Exception { if ( content != null ) { commonspec . getZookeeperSecClient ( ) . zCreate ( path , content , ephemeral ) ; } else { commonspec . getZookeeperSecClient ( ) . zCreate ( path , ephemeral ) ; } }
Create zPath and domcument
39,749
public void connect ( String secured ) { buildCluster ( secured ) ; this . cassandraqueryUtils = new CassandraQueryUtils ( ) ; this . metadata = this . cluster . getMetadata ( ) ; LOGGER . debug ( "Connected to cluster (" + host + "): " + metadata . getClusterName ( ) + "\n" ) ; this . session = this . cluster . connect ( ) ; }
Connect to Cassandra host .
39,750
public void executeQueriesList ( List < String > queriesList ) { for ( String query : queriesList ) { this . session . execute ( query ) ; } }
Execute a list of queries over Cassandra .
39,751
public void reconnect ( ) { metadata = cluster . getMetadata ( ) ; LOGGER . debug ( "Connected to cluster (" + host + "): " + metadata . getClusterName ( ) + "\n" ) ; this . session = this . cluster . connect ( ) ; }
Reconnect to Cassandra host .
39,752
public void disconnect ( ) throws DBException { if ( this . session == null ) { throw new DBException ( "The Cassandra is null" ) ; } if ( this . cluster . isClosed ( ) ) { throw new DBException ( "The cluster has been closed" ) ; } this . session . close ( ) ; this . cluster . close ( ) ; }
Disconnect from Cassandra host .
39,753
public Metadata getMetadata ( ) throws DBException { if ( ! this . cluster . isClosed ( ) ) { this . metadata = cluster . getMetadata ( ) ; return this . metadata ; } else { throw new DBException ( "The cluster has been closed" ) ; } }
Get the metadata of the Cassandra Cluster .
39,754
public void buildCluster ( String secured ) { if ( secured == null ) { this . cluster = Cluster . builder ( ) . addContactPoint ( this . host ) . build ( ) ; this . cluster . getConfiguration ( ) . getQueryOptions ( ) . setConsistencyLevel ( ConsistencyLevel . ONE ) ; } else { try { this . cluster = Cluster . builder ( ) . addContactPoint ( this . host ) . withCredentials ( "user" , "pass" ) . withSSL ( ) . build ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } }
Build a Cassandra cluster .
39,755
public void createKeyspace ( String keyspace ) { Map < String , String > replicationSimpleOneExtra = new HashMap < > ( ) ; replicationSimpleOneExtra . put ( "'class'" , "'SimpleStrategy'" ) ; replicationSimpleOneExtra . put ( "'replication_factor'" , "1" ) ; String query = this . cassandraqueryUtils . createKeyspaceQuery ( true , keyspace , this . cassandraqueryUtils . createKeyspaceReplication ( replicationSimpleOneExtra ) , "" ) ; LOGGER . debug ( query ) ; executeQuery ( query ) ; }
Create a keyspace in Cassandra .
39,756
public void createTableWithData ( String table , Map < String , String > colums , ArrayList < String > pk ) { String query = this . cassandraqueryUtils . createTable ( table , colums , pk ) ; LOGGER . debug ( query ) ; executeQuery ( query ) ; }
Create a table in Cassandra .
39,757
public void insertData ( String table , Map < String , Object > fields ) { String query = this . cassandraqueryUtils . insertData ( table , fields ) ; LOGGER . debug ( query ) ; executeQuery ( query ) ; }
Insert data in a keyspace .
39,758
public boolean existsKeyspace ( String keyspace , boolean showLog ) { this . metadata = cluster . getMetadata ( ) ; if ( ! ( this . metadata . getKeyspaces ( ) . isEmpty ( ) ) ) { for ( KeyspaceMetadata k : metadata . getKeyspaces ( ) ) { if ( k . getName ( ) . equals ( keyspace ) ) { return true ; } } } return false ; }
Checks if a keyspace exists in Cassandra .
39,759
public List < String > getKeyspaces ( ) { ArrayList < String > result = new ArrayList < String > ( ) ; this . metadata = this . cluster . getMetadata ( ) ; if ( ! ( metadata . getKeyspaces ( ) . isEmpty ( ) ) ) { for ( KeyspaceMetadata k : this . metadata . getKeyspaces ( ) ) { result . add ( k . getName ( ) ) ; } } return result ; }
Get a list of the existing keyspaces in Cassandra .
39,760
public boolean existsTable ( String keyspace , String table , boolean showLog ) { this . metadata = this . cluster . getMetadata ( ) ; if ( ! ( this . metadata . getKeyspace ( keyspace ) . getTables ( ) . isEmpty ( ) ) ) { for ( TableMetadata t : this . metadata . getKeyspace ( keyspace ) . getTables ( ) ) { if ( t . getName ( ) . equals ( table ) ) { return true ; } } } return false ; }
Checks if a keyspace contains an especific table .
39,761
public List < String > getTables ( String keyspace ) { ArrayList < String > result = new ArrayList < String > ( ) ; this . metadata = this . cluster . getMetadata ( ) ; if ( ( ! existsKeyspace ( keyspace , false ) ) || ( this . metadata . getKeyspace ( keyspace ) . getTables ( ) . isEmpty ( ) ) ) { return result ; } for ( TableMetadata t : this . metadata . getKeyspace ( keyspace ) . getTables ( ) ) { result . add ( t . getName ( ) ) ; } return result ; }
Get tables of a keyspace .
39,762
public static List < String > loadScript ( String path ) { List < String > result = new ArrayList < String > ( ) ; URL url = CassandraUtils . class . getResource ( path ) ; LOGGER . debug ( url . toString ( ) ) ; LOGGER . info ( "Loading script from: " + url ) ; try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( url . openStream ( ) , "UTF8" ) ) ) { String line ; while ( ( line = br . readLine ( ) ) != null ) { if ( line . length ( ) > 0 && ! line . startsWith ( "#" ) ) { result . add ( line ) ; } } } catch ( IOException e ) { LOGGER . error ( "IO Exception loading a cql script" , e ) ; } return result ; }
Load the lines of a CQL script containing one statement per line into a list . l
39,763
public static Pattern matchesOrContains ( String expectedMessage ) { Pattern pattern ; if ( expectedMessage . startsWith ( "regex:" ) ) { String regex = expectedMessage . substring ( expectedMessage . indexOf ( "regex:" ) + 6 , expectedMessage . length ( ) ) ; pattern = Pattern . compile ( regex ) ; } else { pattern = Pattern . compile ( Pattern . quote ( expectedMessage ) ) ; } return pattern ; }
Checks if a given string matches a regular expression or contains a string
39,764
public String retrieveData ( String baseData , String type ) { String result ; InputStream stream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( baseData ) ; Writer writer = new StringWriter ( ) ; char [ ] buffer = new char [ 1024 ] ; Reader reader ; if ( stream == null ) { this . getLogger ( ) . error ( "File does not exist: {}" , baseData ) ; return "ERR! File not found: " + baseData ; } try { reader = new BufferedReader ( new InputStreamReader ( stream , "UTF-8" ) ) ; int n ; while ( ( n = reader . read ( buffer ) ) != - 1 ) { writer . write ( buffer , 0 , n ) ; } } catch ( Exception readerexception ) { this . getLogger ( ) . error ( readerexception . getMessage ( ) ) ; } finally { try { stream . close ( ) ; } catch ( Exception closeException ) { this . getLogger ( ) . error ( closeException . getMessage ( ) ) ; } } String text = writer . toString ( ) ; String std = text . replace ( "\r" , "" ) . replace ( "\n" , "" ) ; if ( "json" . equals ( type ) ) { result = JsonValue . readHjson ( std ) . asObject ( ) . toString ( ) ; } else { result = std ; } return result ; }
Returns the information contained in file passed as parameter
39,765
public JsonObject removeNulls ( JsonObject object ) { for ( int j = 0 ; j < object . names ( ) . size ( ) ; j ++ ) { if ( JsonType . OBJECT . equals ( object . get ( object . names ( ) . get ( j ) ) . getType ( ) ) ) { removeNulls ( object . get ( object . names ( ) . get ( j ) ) . asObject ( ) ) ; } else { if ( object . get ( object . names ( ) . get ( j ) ) . isNull ( ) ) { object . set ( object . names ( ) . get ( j ) , "TO_BE_NULL" ) ; } } } return object ; }
Eliminates null occurrences replacing them with TO_BE_NULL
39,766
public void setPreviousElement ( String element , String value ) throws NoSuchFieldException , SecurityException , IllegalArgumentException , IllegalAccessException , InstantiationException , ClassNotFoundException , NoSuchMethodException , InvocationTargetException { Reflections reflections = new Reflections ( "com.stratio" ) ; Set classes = reflections . getSubTypesOf ( CommonG . class ) ; Object pp = ( classes . toArray ( ) ) [ 0 ] ; String qq = ( pp . toString ( ) . split ( " " ) ) [ 1 ] ; Class < ? > c = Class . forName ( qq . toString ( ) ) ; Field ff = c . getDeclaredField ( element ) ; ff . setAccessible ( true ) ; ff . set ( null , value ) ; }
Saves the value in the attribute in class extending CommonG .
39,767
private boolean isUUID ( String uuid ) { try { UUID . fromString ( uuid ) ; return true ; } catch ( Exception ex ) { return false ; } }
Check if a string is a UUID
39,768
private boolean isThisDateValid ( String dateToValidate , String dateFromat ) { if ( dateToValidate == null ) { return false ; } SimpleDateFormat sdf = new SimpleDateFormat ( dateFromat ) ; sdf . setLenient ( false ) ; try { Date date = sdf . parse ( dateToValidate ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; return false ; } return true ; }
Check is a String is a valid timestamp format
39,769
public void resultsMustBeElasticsearch ( DataTable expectedResults ) throws Exception { if ( getElasticsearchResults ( ) != null ) { List < List < String > > expectedResultList = expectedResults . raw ( ) ; assertThat ( expectedResultList . size ( ) - 1 ) . overridingErrorMessage ( "Expected number of columns to be" + ( expectedResultList . size ( ) - 1 ) + "but was " + previousElasticsearchResults . size ( ) ) . isEqualTo ( previousElasticsearchResults . size ( ) ) ; List < String > columnNames = expectedResultList . get ( 0 ) ; for ( int i = 0 ; i < previousElasticsearchResults . size ( ) ; i ++ ) { for ( int j = 0 ; j < columnNames . size ( ) ; j ++ ) { assertThat ( expectedResultList . get ( i + 1 ) . get ( j ) ) . overridingErrorMessage ( "In row " + i + "and " + "column " + j + "have " + "been " + "found " + expectedResultList . get ( i + 1 ) . get ( j ) + " results and " + previousElasticsearchResults . get ( i ) . get ( columnNames . get ( j ) ) . toString ( ) + " were " + "expected" ) . isEqualTo ( previousElasticsearchResults . get ( i ) . get ( columnNames . get ( j ) ) . toString ( ) ) ; } } } else { throw new Exception ( "You must execute a query before trying to get results" ) ; } }
Checks the different results of a previous query to Elasticsearch database
39,770
public void runLocalCommand ( String command ) throws Exception { String result = "" ; String line ; Process p ; try { p = Runtime . getRuntime ( ) . exec ( new String [ ] { "/bin/sh" , "-c" , command } ) ; p . waitFor ( ) ; } catch ( java . io . IOException e ) { this . commandExitStatus = 1 ; this . commandResult = "Error" ; return ; } BufferedReader input = new BufferedReader ( new InputStreamReader ( p . getInputStream ( ) ) ) ; while ( ( line = input . readLine ( ) ) != null ) { result += line ; } input . close ( ) ; this . commandResult = result ; this . commandExitStatus = p . exitValue ( ) ; p . destroy ( ) ; if ( p . isAlive ( ) ) { p . destroyForcibly ( ) ; } }
Runs a command locally
39,771
public String removeJSONPathElement ( String jsonString , String expr ) { Configuration conf = Configuration . builder ( ) . jsonProvider ( new GsonJsonProvider ( ) ) . mappingProvider ( new GsonMappingProvider ( ) ) . build ( ) ; DocumentContext context = JsonPath . using ( conf ) . parse ( jsonString ) ; context . delete ( expr ) ; return context . jsonString ( ) ; }
Remove a subelement in a JsonPath
39,772
public String replaceJSONPathElement ( String jsonString , String key , String value ) { return JsonPath . parse ( jsonString ) . set ( key , value ) . jsonString ( ) ; }
The function searches over the array by certain field value and replaces occurences with the parameter provided .
39,773
public JSONObject parseJSONSchema ( JSONObject schema ) throws Exception { JSONObject json = new JSONObject ( ) ; String name = "" ; JSONObject properties = schema ; if ( schema . has ( "properties" ) ) { properties = schema . getJSONObject ( "properties" ) ; } Iterator < ? > keys = properties . keys ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) . toString ( ) ; JSONObject element = properties . getJSONObject ( key ) ; if ( ! element . has ( "properties" ) ) { if ( element . has ( "default" ) ) { json . put ( key , element . get ( "default" ) ) ; } else { switch ( element . getString ( "type" ) ) { case "string" : json . put ( key , "" ) ; break ; case "boolean" : json . put ( key , false ) ; break ; case "number" : case "integer" : json . put ( key , 0 ) ; break ; default : Assertions . fail ( "type not expected" ) ; } } } else { json . put ( key , parseJSONSchema ( element ) ) ; } } return json ; }
Generate deployment json from schema
39,774
public boolean matchJsonToSchema ( JSONObject schema , JSONObject json ) throws Exception { SchemaLoader . builder ( ) . useDefaults ( true ) . schemaJson ( schema ) . build ( ) . load ( ) . build ( ) . validate ( json ) ; return true ; }
Check json matches schema
39,775
public static SeleniumAssert assertThat ( CommonG commong , List < WebElement > actual ) { return new SeleniumAssert ( commong , actual ) ; }
Checks a selenium list of WebElements .
39,776
public SeleniumAssert contains ( CharSequence ... values ) { if ( actual instanceof WebDriver ) { Strings . instance ( ) . assertContains ( info , ( ( WebDriver ) actual ) . getPageSource ( ) , values ) ; } else if ( actual instanceof WebElement ) { Strings . instance ( ) . assertContains ( info , ( ( WebElement ) actual ) . getText ( ) , values ) ; } return this ; }
Checks if a webDriver or WebElement has values .
39,777
public SeleniumAssert isTextField ( Condition < WebElement > cond ) { if ( actual instanceof List ) { Conditions . instance ( ) . equals ( cond ) ; } return this ; }
Checks if a WebElement is a TextField .
39,778
@ When ( "^I read info from csv file '(.+?)' with separator '(.+?)'$" ) public void readFromCSV ( String csvFile , String separator ) throws Exception { char sep = ',' ; if ( separator . length ( ) > 1 ) { switch ( separator ) { case "\\t" : sep = '\t' ; break ; default : sep = ',' ; break ; } } else { sep = separator . charAt ( 0 ) ; } CsvReader rows = new CsvReader ( csvFile , sep ) ; String [ ] columns = null ; if ( rows . readRecord ( ) ) { columns = rows . getValues ( ) ; rows . setHeaders ( columns ) ; } List < Map < String , String > > results = new ArrayList < Map < String , String > > ( ) ; while ( rows . readRecord ( ) ) { Map < String , String > row = new HashMap < String , String > ( ) ; for ( String column : columns ) { row . put ( column , rows . get ( rows . getIndex ( column ) ) ) ; } results . add ( row ) ; } rows . close ( ) ; commonspec . setResultsType ( "csv" ) ; commonspec . setCSVResults ( results ) ; }
Read csv file and store result in list of maps
39,779
@ When ( "^I read file '(.+?)' as '(.+?)' and save it in environment variable '(.+?)' with:$" ) public void readFileToVariable ( String baseData , String type , String envVar , DataTable modifications ) throws Exception { String retrievedData = commonspec . retrieveData ( baseData , type ) ; commonspec . getLogger ( ) . debug ( "Modifying data {} as {}" , retrievedData , type ) ; String modifiedData = commonspec . modifyData ( retrievedData , type , modifications ) . toString ( ) ; ThreadProperty . set ( envVar , modifiedData ) ; }
Read the file passed as parameter perform the modifications specified and save the result in the environment variable passed as parameter .
39,780
@ When ( "^I read file '(.+?)' as '(.+?)' and save it in environment variable '(.+?)'$" ) public void readFileToVariableNoDataTable ( String baseData , String type , String envVar ) throws Exception { String retrievedData = commonspec . retrieveData ( baseData , type ) ; ThreadProperty . set ( envVar , retrievedData ) ; }
Read the file passed as parameter and save the result in the environment variable passed as parameter .
39,781
public static String getClipboardText ( final Context context ) { final ClipboardManager clipboard = ( ClipboardManager ) context . getSystemService ( Context . CLIPBOARD_SERVICE ) ; final ClipData clipData = clipboard . getPrimaryClip ( ) ; if ( clipData != null && clipData . getItemCount ( ) > 0 ) { final CharSequence clipboardText = clipData . getItemAt ( 0 ) . getText ( ) ; if ( clipboardText != null ) { return clipboardText . toString ( ) ; } } return null ; }
Get the current text from the clipboard .
39,782
public static void setClipboardText ( final Context context , final String text ) { if ( text != null ) { final ClipboardManager clipboard = ( ClipboardManager ) context . getSystemService ( Context . CLIPBOARD_SERVICE ) ; final ClipData clipData = ClipData . newPlainText ( text , text ) ; clipboard . setPrimaryClip ( clipData ) ; } }
Set the clipboard text .
39,783
public static void closeKeyboard ( Context context , View field ) { try { InputMethodManager imm = ( InputMethodManager ) context . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . hideSoftInputFromWindow ( field . getWindowToken ( ) , 0 ) ; } catch ( Exception ex ) { Log . e ( "Caffeine" , "Error occurred trying to hide the keyboard. Exception=" + ex ) ; } }
Go away keyboard nobody likes you .
39,784
public static void showKeyboard ( Context context , View field ) { try { field . requestFocus ( ) ; InputMethodManager imm = ( InputMethodManager ) context . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; imm . showSoftInput ( field , InputMethodManager . SHOW_IMPLICIT ) ; } catch ( Exception ex ) { Log . e ( "Caffeine" , "Error occurred trying to show the keyboard. Exception=" + ex ) ; } }
Show the pop - up keyboard
39,785
public static Bitmap viewToImage ( Context context , WebView viewToBeConverted ) { int extraSpace = 2000 ; int height = viewToBeConverted . getContentHeight ( ) + extraSpace ; Bitmap viewBitmap = Bitmap . createBitmap ( viewToBeConverted . getWidth ( ) , height , Bitmap . Config . ARGB_8888 ) ; Canvas canvas = new Canvas ( viewBitmap ) ; viewToBeConverted . draw ( canvas ) ; try { int scrollY = viewToBeConverted . getScrollY ( ) ; if ( scrollY > 0 ) { viewBitmap = Bitmap . createBitmap ( viewBitmap , 0 , scrollY , viewToBeConverted . getWidth ( ) , height - scrollY ) ; } } catch ( Exception ex ) { Log . e ( "Caffeine" , "Could not remove top part of the webview image. ex=" + ex ) ; } return viewBitmap ; }
Convert view to an image . Can be used to make animations smoother .
39,786
public static void launchWebBrowser ( final Context context , final String url ) { if ( context != null && url != null && ! "" . equals ( url ) ) { final Intent browserIntent = new Intent ( Intent . ACTION_VIEW , Uri . parse ( url ) ) ; if ( browserIntent . resolveActivity ( context . getPackageManager ( ) ) != null ) { context . startActivity ( browserIntent ) ; } else { ToastUtils . quickToast ( context , "Sorry, Could not open the link. You do not have an application installed to open it." ) ; Log . e ( "Caffeine" , "Failed to open link, because an application is not available to view it." ) ; } } else { ToastUtils . quickToast ( context , "Sorry, Could not open link. No URL provided." ) ; } }
Start Intent to launch web browser .
39,787
public static boolean isAppInstalled ( final Context context , final String packageName ) { try { context . getPackageManager ( ) . getPackageInfo ( packageName , 0 ) ; return true ; } catch ( Exception e ) { return false ; } }
Check if app for the given package name is installed on this device .
39,788
public static void launchCameraIntent ( final Activity context , final Uri outputDestination , final int requestCode ) { final Intent intent = new Intent ( MediaStore . ACTION_IMAGE_CAPTURE ) ; intent . putExtra ( MediaStore . EXTRA_OUTPUT , outputDestination ) ; if ( intent . resolveActivity ( context . getPackageManager ( ) ) != null ) { grantUriPermissionsForIntent ( context , outputDestination , intent ) ; context . startActivityForResult ( intent , requestCode ) ; } }
Launch camera on the device using android s ACTION_IMAGE_CAPTURE intent .
39,789
public static boolean launchAppForPackage ( final Context context , final String packageName ) { try { final PackageManager packageManager = context . getPackageManager ( ) ; final Intent intent = packageManager . getLaunchIntentForPackage ( packageName ) ; intent . addCategory ( Intent . CATEGORY_LAUNCHER ) ; context . startActivity ( intent ) ; return true ; } catch ( Exception ex ) { Log . e ( "Caffeine" , "Failed to launch application for package name [" + packageName + "]" , ex ) ; return false ; } }
Tries to launch the application for a given package name .
39,790
public static void launchActivity ( Activity context , Class < ? extends Activity > activity , boolean closeCurrentActivity , Map < String , String > params ) { Intent intent = new Intent ( context , activity ) ; if ( params != null ) { Bundle bundle = new Bundle ( ) ; for ( Entry < String , String > param : params . entrySet ( ) ) { bundle . putString ( param . getKey ( ) , param . getValue ( ) ) ; } intent . putExtras ( bundle ) ; } context . startActivity ( intent ) ; if ( closeCurrentActivity ) { context . finish ( ) ; } }
Launch an Activity .
39,791
public static void turnScreenOn ( Activity context ) { try { Window window = context . getWindow ( ) ; window . addFlags ( WindowManager . LayoutParams . FLAG_DISMISS_KEYGUARD ) ; window . addFlags ( WindowManager . LayoutParams . FLAG_SHOW_WHEN_LOCKED ) ; window . addFlags ( WindowManager . LayoutParams . FLAG_TURN_SCREEN_ON ) ; } catch ( Exception ex ) { Log . e ( "Caffeine" , "Unable to turn on screen for activity " + context ) ; } }
Force screen to turn on if the phone is asleep .
39,792
public final static boolean isValidEmail ( String email ) { if ( email == null ) { return false ; } else { return android . util . Patterns . EMAIL_ADDRESS . matcher ( email ) . matches ( ) ; } }
Uses androids android . util . Patterns . EMAIL_ADDRESS to check if an email address is valid .
39,793
public final static boolean isValidURL ( String url ) { if ( url == null ) { return false ; } else { return Patterns . WEB_URL . matcher ( url ) . matches ( ) ; } }
Uses androids android . util . Patterns . WEB_URL to check if an url is valid .
39,794
public static Toast quickToast ( Context context , String message , boolean longLength ) { final Toast toast ; if ( longLength ) { toast = Toast . makeText ( context , message , Toast . LENGTH_LONG ) ; } else { toast = Toast . makeText ( context , message , Toast . LENGTH_SHORT ) ; } toast . show ( ) ; return toast ; }
Display a toast with the given message .
39,795
public Server onpublish ( Action < Map < String , Object > > action ) { publishActions . add ( action ) ; return this ; }
Adds an action to be called with a message to be published to every node in the cluster .
39,796
public static ServerSocketPredicate tag ( String ... tags ) { return socket -> socket . tags ( ) . containsAll ( Arrays . asList ( tags ) ) ; }
Returns a predicate that tests the socket tags against the given tags .
39,797
public static void addRoute ( MangooRoute route ) { Objects . requireNonNull ( route , Required . ROUTE . toString ( ) ) ; Preconditions . checkArgument ( routes . size ( ) <= MAX_ROUTES , "Maximum of " + MAX_ROUTES + " routes reached" ) ; routes . add ( route ) ; if ( route instanceof RequestRoute ) { RequestRoute requestRoute = ( RequestRoute ) route ; if ( requestRoute . getControllerClass ( ) != null && StringUtils . isNotBlank ( requestRoute . getControllerMethod ( ) ) ) { reverseRoutes . put ( ( requestRoute . getControllerClass ( ) . getSimpleName ( ) . toLowerCase ( Locale . ENGLISH ) + ":" + requestRoute . getControllerMethod ( ) ) . toLowerCase ( Locale . ENGLISH ) , requestRoute ) ; } } }
Adds a new route to the router
39,798
public static RequestRoute getReverseRoute ( String key ) { Objects . requireNonNull ( key , Required . KEY . toString ( ) ) ; return reverseRoutes . get ( key . toLowerCase ( Locale . ENGLISH ) ) ; }
Retrieves a reverse route by its controller class and controller method
39,799
public void addChannel ( WebSocketChannel channel ) { Objects . requireNonNull ( channel , Required . CHANNEL . toString ( ) ) ; final String url = RequestUtils . getWebSocketURL ( channel ) ; Set < WebSocketChannel > channels = getChannels ( url ) ; if ( channels == null ) { channels = new HashSet < > ( ) ; channels . add ( channel ) ; } else { channels . add ( channel ) ; } setChannels ( url , channels ) ; }
Adds a new channel to the manager