idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
3,500
public void addChangelogFile ( File changelogFile ) throws IOException , ChangelogParseException { new ChangelogHandler ( this . format . getHeader ( ) ) . addChangeLog ( changelogFile ) ; }
Adds the supplied Changelog file as a Changelog to the header
3,501
public String build ( final File directory ) throws NoSuchAlgorithmException , IOException { final String rpm = format . getLead ( ) . getName ( ) + "." + format . getLead ( ) . getArch ( ) . toString ( ) . toLowerCase ( ) + ".rpm" ; final File file = new File ( directory , rpm ) ; if ( file . exists ( ) ) file . delete ( ) ; RandomAccessFile raFile = new RandomAccessFile ( file , "rw" ) ; build ( raFile . getChannel ( ) ) ; raFile . close ( ) ; return rpm ; }
Generates an RPM with a standard name consisting of the RPM package name version release and type in the given directory .
3,502
protected byte [ ] getSpecial ( final int tag , final int count ) { final ByteBuffer buffer = ByteBuffer . allocate ( 16 ) ; buffer . putInt ( tag ) ; buffer . putInt ( 0x00000007 ) ; buffer . putInt ( count * - 16 ) ; buffer . putInt ( 0x00000010 ) ; return buffer . array ( ) ; }
Returns the special header expected by RPM for a particular header .
3,503
protected int [ ] convert ( final Integer [ ] ints ) { int [ ] array = new int [ ints . length ] ; int count = 0 ; for ( int i : ints ) array [ count ++ ] = i ; return array ; }
Converts an array of Integer objects into an equivalent array of int primitives .
3,504
private Object toActualNumber ( Double value , Type type ) { if ( type . equals ( Byte . class ) ) return value . byteValue ( ) ; if ( type . equals ( Short . class ) ) return value . shortValue ( ) ; if ( type . equals ( Integer . class ) ) return value . intValue ( ) ; if ( type . equals ( Long . class ) ) return value . longValue ( ) ; if ( type . equals ( Float . class ) ) return value . floatValue ( ) ; if ( type . equals ( Double . class ) ) return value ; if ( type . equals ( BigInteger . class ) ) return BigInteger . valueOf ( value . longValue ( ) ) ; if ( type . equals ( BigDecimal . class ) ) return BigDecimal . valueOf ( value ) ; return value ; }
but I m going to rely on the user to not do anything silly
3,505
public void setHandler ( Object handler ) { if ( handler instanceof ContentHandler ) setContentHandler ( ( ContentHandler ) handler ) ; if ( handler instanceof EntityResolver ) setEntityResolver ( ( EntityResolver ) handler ) ; if ( handler instanceof ErrorHandler ) setErrorHandler ( ( ErrorHandler ) handler ) ; if ( handler instanceof DTDHandler ) setDTDHandler ( ( DTDHandler ) handler ) ; if ( handler instanceof LexicalHandler ) setLexicalHandler ( ( LexicalHandler ) handler ) ; if ( handler instanceof DeclHandler ) setDeclHandler ( ( DeclHandler ) handler ) ; }
Registers given handler with all its implementing interfaces . This would be handy if you want to register to all interfaces implemented by given handler object
3,506
public static void redirectStreams ( Process process , OutputStream output , OutputStream error ) { if ( output != null ) new Thread ( new IOPump ( process . getInputStream ( ) , output , false , false ) . asRunnable ( ) ) . start ( ) ; if ( error != null ) new Thread ( new IOPump ( process . getErrorStream ( ) , error , false , false ) . asRunnable ( ) ) . start ( ) ; }
Redirects given process s input and error streams to the specified streams . the streams specified are not closed automatically . The streams passed can be null if you don t want to redirect them .
3,507
public static Object [ ] concat ( Object array1 [ ] , Object array2 [ ] ) { Class < ? > class1 = array1 . getClass ( ) . getComponentType ( ) ; Class < ? > class2 = array2 . getClass ( ) . getComponentType ( ) ; Class < ? > commonClass = class1 . isAssignableFrom ( class2 ) ? class1 : ( class2 . isAssignableFrom ( class1 ) ? class2 : Object . class ) ; return concat ( array1 , array2 , commonClass ) ; }
Returns new array which has all values from array1 and array2 in order . The componentType for the new array is determined by the componentTypes of two arrays .
3,508
public static Transformer setOutputProperties ( Transformer transformer , boolean omitXMLDeclaration , int indentAmount , String encoding ) { transformer . setOutputProperty ( OutputKeys . OMIT_XML_DECLARATION , omitXMLDeclaration ? "yes" : "no" ) ; if ( indentAmount > 0 ) { transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( OUTPUT_KEY_INDENT_AMOUT , String . valueOf ( indentAmount ) ) ; } if ( ! StringUtil . isWhitespace ( encoding ) ) transformer . setOutputProperty ( OutputKeys . ENCODING , encoding . trim ( ) ) ; return transformer ; }
to set various output properties on given transformer .
3,509
public boolean consume ( int ch ) { offset ++ ; if ( ch == 0x0D ) { skipLF = true ; line ++ ; col = 0 ; return true ; } else if ( ch == 0x0A ) { if ( skipLF ) { skipLF = false ; return false ; } else { line ++ ; col = 0 ; return true ; } } else { skipLF = false ; col ++ ; return true ; } }
return value tells whether the given character has been included in location or not
3,510
public static String [ ] getTokens ( String str , String delim , boolean trim ) { StringTokenizer stok = new StringTokenizer ( str , delim ) ; String tokens [ ] = new String [ stok . countTokens ( ) ] ; for ( int i = 0 ; i < tokens . length ; i ++ ) { tokens [ i ] = stok . nextToken ( ) ; if ( trim ) tokens [ i ] = tokens [ i ] . trim ( ) ; } return tokens ; }
Splits given string into tokens with delimiters specified . It uses StringTokenizer for tokenizing .
3,511
public static String ordinalize ( int number ) { int modulo = number % 100 ; if ( modulo >= 11 && modulo <= 13 ) return number + "th" ; switch ( number % 10 ) { case 1 : return number + "st" ; case 2 : return number + "nd" ; case 3 : return number + "rd" ; default : return number + "th" ; } }
Turns a non - negative number into an ordinal string used to denote the position in an ordered sequence such as 1st 2nd 3rd 4th
3,512
public static String getText ( ) { Transferable contents = clipboard ( ) . getContents ( null ) ; try { if ( contents != null && contents . isDataFlavorSupported ( DataFlavor . stringFlavor ) ) return ( String ) contents . getTransferData ( DataFlavor . stringFlavor ) ; else return null ; } catch ( UnsupportedFlavorException ex ) { throw new ImpossibleException ( ex ) ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } }
returns the current text contents of clipboard . If clipboard has no text contents or has no content it returns null
3,513
public static void clear ( ) { clipboard ( ) . setContents ( new Transferable ( ) { public DataFlavor [ ] getTransferDataFlavors ( ) { return new DataFlavor [ 0 ] ; } public boolean isDataFlavorSupported ( DataFlavor flavor ) { return false ; } public Object getTransferData ( DataFlavor flavor ) throws UnsupportedFlavorException { throw new UnsupportedFlavorException ( flavor ) ; } } , null ) ; }
clears contents of clipboard
3,514
public void set ( byte [ ] buff , int offset , int length ) { if ( offset < 0 ) throw new IndexOutOfBoundsException ( "ByteSequence index out of range: " + offset ) ; if ( length < 0 ) throw new IndexOutOfBoundsException ( "ByteSequence index out of range: " + length ) ; if ( offset > buff . length - length ) throw new StringIndexOutOfBoundsException ( "ByteSequence index out of range: " + ( offset + length ) ) ; this . buff = buff ; this . offset = offset ; this . length = length ; }
replaces the internal byte buffer with the given byte array .
3,515
public static Class getClassingClass ( int offset ) { Class [ ] context = ClassContext . INSTANCE . getClassContext ( ) ; offset += 2 ; return context . length > offset ? context [ offset ] : null ; }
returns the calling class .
3,516
public static String [ ] split ( String fileName ) { int dot = fileName . lastIndexOf ( '.' ) ; if ( dot == - 1 ) return new String [ ] { fileName , null } ; else return new String [ ] { fileName . substring ( 0 , dot ) , fileName . substring ( dot + 1 ) } ; }
splits given fileName into name and extension .
3,517
public static String getName ( String fileName ) { int dot = fileName . lastIndexOf ( '.' ) ; return dot == - 1 ? fileName : fileName . substring ( 0 , dot ) ; }
Returns name of the file without extension
3,518
public static String getExtension ( String fileName ) { int dot = fileName . lastIndexOf ( '.' ) ; return dot == - 1 ? null : fileName . substring ( dot + 1 ) ; }
Returns extension of the file . Returns null if there is no extension
3,519
public static void mkdir ( File dir ) throws IOException { if ( ! dir . exists ( ) && ! dir . mkdir ( ) ) throw new IOException ( "couldn't create directory: " + dir ) ; }
create specified directory if doesn t exist .
3,520
public XSModel parseString ( String schema , String baseURI ) { return xsLoader . load ( new DOMInputImpl ( null , null , baseURI , schema , null ) ) ; }
Parse an XML Schema document from String specified
3,521
public String findPrefix ( String uri ) { if ( uri == null ) uri = "" ; String prefix = getPrefix ( uri ) ; if ( prefix == null ) { String defaultURI = getURI ( "" ) ; if ( defaultURI == null ) defaultURI = "" ; if ( Util . equals ( uri , defaultURI ) ) prefix = "" ; } return prefix ; }
Return one of the prefixes mapped to a Namespace URI .
3,522
public String declarePrefix ( String uri ) { String prefix = findPrefix ( uri ) ; if ( prefix == null ) { if ( uri . isEmpty ( ) ) prefix = "" ; else { prefix = suggested . getProperty ( uri , suggestPrefix ) ; if ( getURI ( prefix ) != null ) { if ( prefix . isEmpty ( ) ) prefix = "ns" ; int i = 1 ; String _prefix ; while ( true ) { _prefix = prefix + i ; if ( getURI ( _prefix ) == null ) { prefix = _prefix ; break ; } i ++ ; } } } declarePrefix ( prefix , uri ) ; } return prefix ; }
generated a new prefix and binds it to given uri .
3,523
@ SuppressWarnings ( { "unchecked" , "ManualArrayToCollectionCopy" } ) public static < E , T extends E > Collection < E > addAll ( Collection < E > c , T ... array ) { for ( T obj : array ) c . add ( obj ) ; return c ; }
Adds objects in array to the given collection
3,524
@ SuppressWarnings ( "unchecked" ) public static < E , T extends E > Collection < E > removeAll ( Collection < E > c , T ... array ) { for ( T obj : array ) c . remove ( obj ) ; return c ; }
Removes objects in array to the given collection
3,525
public static < T > List < T > filter ( Collection < T > c , Filter < T > filter ) { if ( c . size ( ) == 0 ) return Collections . emptyList ( ) ; List < T > filteredList = new ArrayList < T > ( c . size ( ) ) ; for ( T element : c ) { if ( filter . select ( element ) ) filteredList . add ( element ) ; } return filteredList ; }
Returns List with elements from given collections which are selected by specified filter
3,526
public String [ ] command ( ) throws IOException { List < String > cmd = new ArrayList < String > ( ) ; String executable = javaHome . getCanonicalPath ( ) + FileUtil . SEPARATOR + "bin" + FileUtil . SEPARATOR + "java" ; if ( OS . get ( ) . isWindows ( ) ) executable += ".exe" ; cmd . add ( executable ) ; String path = toString ( workingDir , prependBootClasspath ) ; if ( path . length ( ) > 0 ) cmd . add ( "-Xbootclasspath/p:" + path ) ; path = toString ( workingDir , bootClasspath ) ; if ( path . length ( ) > 0 ) cmd . add ( "-Xbootclasspath:" + path ) ; path = toString ( workingDir , appendBootClasspath ) ; if ( path . length ( ) > 0 ) cmd . add ( "-Xbootclasspath/a:" + path ) ; path = toString ( workingDir , classpath ) ; if ( path . length ( ) > 0 ) { cmd . add ( "-classpath" ) ; cmd . add ( path ) ; } path = toString ( workingDir , extDirs ) ; if ( path . length ( ) > 0 ) cmd . add ( "-Djava.ext.dirs=" + path ) ; path = toString ( workingDir , endorsedDirs ) ; if ( path . length ( ) > 0 ) cmd . add ( "-Djava.endorsed.dirs=" + path ) ; path = toString ( workingDir , libraryPath ) ; if ( path . length ( ) > 0 ) cmd . add ( "-Djava.library.path=" + path ) ; for ( Map . Entry < String , String > prop : systemProperties . entrySet ( ) ) { if ( prop . getValue ( ) == null ) cmd . add ( "-D" + prop . getKey ( ) ) ; else cmd . add ( "-D" + prop . getKey ( ) + "=" + prop . getValue ( ) ) ; } if ( initialHeap != null ) cmd . add ( "-Xms" + initialHeap ) ; if ( maxHeap != null ) cmd . add ( "-Xmx" + maxHeap ) ; if ( vmType != null ) cmd . add ( vmType ) ; if ( debugPort != - 1 ) { cmd . add ( "-Xdebug" ) ; cmd . add ( "-Xnoagent" ) ; cmd . add ( "-Xrunjdwp:transport=dt_socket,server=y,suspend=" + ( debugSuspend ? 'y' : 'n' ) + ",address=" + debugPort ) ; } cmd . addAll ( jvmArgs ) ; if ( mainClass != null ) { cmd . add ( mainClass ) ; cmd . addAll ( args ) ; } return cmd . toArray ( new String [ cmd . size ( ) ] ) ; }
Returns command with all its arguments
3,527
public Process launch ( OutputStream output , OutputStream error ) throws IOException { Process process = Runtime . getRuntime ( ) . exec ( command ( ) , null , workingDir ) ; RuntimeUtil . redirectStreams ( process , output , error ) ; return process ; }
launches jvm with current configuration .
3,528
public static void setInitialFocus ( Window window , final Component comp ) { window . addWindowFocusListener ( new WindowAdapter ( ) { public void windowGainedFocus ( WindowEvent we ) { comp . requestFocusInWindow ( ) ; we . getWindow ( ) . removeWindowFocusListener ( this ) ; } } ) ; }
sets intial focus in window to the specified component
3,529
public static void doAction ( JTextField textField ) { String command = null ; if ( textField . getAction ( ) != null ) command = ( String ) textField . getAction ( ) . getValue ( Action . ACTION_COMMAND_KEY ) ; ActionEvent event = null ; for ( ActionListener listener : textField . getActionListeners ( ) ) { if ( event == null ) event = new ActionEvent ( textField , ActionEvent . ACTION_PERFORMED , command , System . currentTimeMillis ( ) , 0 ) ; listener . actionPerformed ( event ) ; } }
Programmatically perform action on textfield . This does the same thing as if the user had pressed enter key in textfield .
3,530
public static void setText ( JTextComponent textComp , String text ) { if ( text == null ) text = "" ; if ( textComp . getCaret ( ) instanceof DefaultCaret ) { DefaultCaret caret = ( DefaultCaret ) textComp . getCaret ( ) ; int updatePolicy = caret . getUpdatePolicy ( ) ; caret . setUpdatePolicy ( DefaultCaret . NEVER_UPDATE ) ; try { textComp . setText ( text ) ; } finally { caret . setUpdatePolicy ( updatePolicy ) ; } } else { int mark = textComp . getCaret ( ) . getMark ( ) ; int dot = textComp . getCaretPosition ( ) ; try { textComp . setText ( text ) ; } finally { int len = textComp . getDocument ( ) . getLength ( ) ; if ( mark > len ) mark = len ; if ( dot > len ) dot = len ; textComp . setCaretPosition ( mark ) ; if ( dot != mark ) textComp . moveCaretPosition ( dot ) ; } } }
sets text of textComp without moving its caret .
3,531
public boolean merge ( ResourceMetadata other ) { boolean modified = m_metrics . addAll ( other . m_metrics ) ; if ( ! modified ) { modified = ! m_attributes . equals ( other . m_attributes ) ; } m_attributes . putAll ( other . m_attributes ) ; return modified ; }
Merges the metrics and attributes from the given instance to the current instance .
3,532
protected Result check ( ) throws Exception { m_repository . select ( Context . DEFAULT_CONTEXT , new Resource ( "notreal" ) , Optional . of ( Timestamp . fromEpochMillis ( 0 ) ) , Optional . of ( Timestamp . fromEpochMillis ( 0 ) ) ) ; return Result . healthy ( ) ; }
Perform simple query ; Establishes only that we can go to the database without excepting .
3,533
public Set < String > getSourceNames ( ) { return Sets . newHashSet ( Iterables . transform ( getDatasources ( ) . values ( ) , new Function < Datasource , String > ( ) { public String apply ( Datasource input ) { return input . getSource ( ) ; } } ) ) ; }
Returns the set of unique source names ; The names of the underlying samples used as the source of aggregations .
3,534
public void breadthFirstSearch ( Context context , SearchResultVisitor visitor , Resource root ) { Queue < Resource > queue = Lists . newLinkedList ( ) ; queue . add ( root ) ; while ( ! queue . isEmpty ( ) ) { Resource r = queue . remove ( ) ; for ( SearchResults . Result result : m_searcher . search ( context , matchKeyAndValue ( Constants . PARENT_TERM_FIELD , r . getId ( ) ) ) ) { if ( ! visitor . visit ( result ) ) { return ; } queue . add ( result . getResource ( ) ) ; } } }
Visits all nodes in the resource tree bellow the given resource using breadth - first search .
3,535
public void depthFirstSearch ( Context context , SearchResultVisitor visitor , Resource root ) { ArrayDeque < SearchResults . Result > stack = Queues . newArrayDeque ( ) ; boolean skipFirstVisit = true ; SearchResults initialResults = new SearchResults ( ) ; initialResults . addResult ( root , new ArrayList < String > ( 0 ) ) ; stack . add ( initialResults . iterator ( ) . next ( ) ) ; while ( ! stack . isEmpty ( ) ) { SearchResults . Result r = stack . pop ( ) ; if ( skipFirstVisit ) { skipFirstVisit = false ; } else { if ( ! visitor . visit ( r ) ) { return ; } } ImmutableList < SearchResults . Result > results = ImmutableList . copyOf ( m_searcher . search ( context , matchKeyAndValue ( Constants . PARENT_TERM_FIELD , r . getResource ( ) . getId ( ) ) ) ) ; for ( SearchResults . Result result : results . reverse ( ) ) { stack . push ( result ) ; } } }
Visits all nodes in the resource tree bellow the given resource using depth - first search .
3,536
private Set < String > searchForIds ( Context context , TermQuery query , ConsistencyLevel readConsistency ) { Set < String > ids = Sets . newTreeSet ( ) ; BoundStatement bindStatement = m_searchStatement . bind ( ) ; bindStatement . setString ( Schema . C_TERMS_CONTEXT , context . getId ( ) ) ; bindStatement . setString ( Schema . C_TERMS_FIELD , query . getTerm ( ) . getField ( Constants . DEFAULT_TERM_FIELD ) ) ; bindStatement . setString ( Schema . C_TERMS_VALUE , query . getTerm ( ) . getValue ( ) ) ; bindStatement . setConsistencyLevel ( readConsistency ) ; for ( Row row : m_session . execute ( bindStatement ) ) { ids . add ( row . getString ( Constants . Schema . C_TERMS_RESOURCE ) ) ; } return ids ; }
Returns the set of resource ids that match the given term query .
3,537
private Set < String > searchForIds ( Context context , BooleanQuery query , ConsistencyLevel readConsistency ) { Set < String > ids = Sets . newTreeSet ( ) ; for ( BooleanClause clause : query . getClauses ( ) ) { Set < String > subQueryIds ; Query subQuery = clause . getQuery ( ) ; if ( subQuery instanceof BooleanQuery ) { subQueryIds = searchForIds ( context , ( BooleanQuery ) subQuery , readConsistency ) ; } else if ( subQuery instanceof TermQuery ) { subQueryIds = searchForIds ( context , ( TermQuery ) subQuery , readConsistency ) ; } else { throw new IllegalStateException ( "Unsupported query: " + subQuery ) ; } switch ( clause . getOperator ( ) ) { case AND : ids . retainAll ( subQueryIds ) ; break ; case OR : ids . addAll ( subQueryIds ) ; break ; default : throw new IllegalStateException ( "Unsupported operator: " + clause . getOperator ( ) ) ; } } return ids ; }
Returns the set of resource ids that match the given boolean query .
3,538
public List < String > splitIdIntoElements ( String id ) { Preconditions . checkNotNull ( id , "id argument" ) ; List < String > elements = Lists . newArrayList ( ) ; int startOfNextElement = 0 ; int numConsecutiveEscapeCharacters = 0 ; char [ ] idChars = id . toCharArray ( ) ; for ( int i = 0 ; i < idChars . length ; i ++ ) { if ( idChars [ i ] == SEPARATOR && numConsecutiveEscapeCharacters % 2 == 0 ) { maybeAddSanitizedElement ( new String ( idChars , startOfNextElement , i - startOfNextElement ) , elements ) ; startOfNextElement = i + 1 ; } if ( idChars [ i ] == '\\' ) { numConsecutiveEscapeCharacters ++ ; } else { numConsecutiveEscapeCharacters = 0 ; } } maybeAddSanitizedElement ( new String ( idChars , startOfNextElement , idChars . length - startOfNextElement ) , elements ) ; return elements ; }
Splits a resource id into a list of elements .
3,539
private static void maybeAddSanitizedElement ( final String element , final List < String > elements ) { String sanitizedElement = element . trim ( ) ; if ( sanitizedElement . length ( ) == 0 ) { return ; } sanitizedElement = MATCH_ESCAPED_COLON . matcher ( sanitizedElement ) . replaceAll ( ":" ) ; sanitizedElement = MATCH_ESCAPED_BACKSLASH . matcher ( sanitizedElement ) . replaceAll ( "\\\\" ) ; elements . add ( sanitizedElement ) ; }
Maybe adds to element to the list after being sanitized .
3,540
public String joinElementsToId ( List < String > elements ) { Preconditions . checkNotNull ( elements , "elements argument" ) ; StringBuilder sb = new StringBuilder ( ) ; for ( String el : elements ) { if ( el == null ) { continue ; } String trimmedEl = el . trim ( ) ; if ( trimmedEl . length ( ) < 1 ) { continue ; } trimmedEl = MATCH_BACKSLASH . matcher ( trimmedEl ) . replaceAll ( "\\\\\\\\" ) ; trimmedEl = MATCH_COLON . matcher ( trimmedEl ) . replaceAll ( "\\\\:" ) ; if ( sb . length ( ) > 0 ) { sb . append ( SEPARATOR ) ; } sb . append ( trimmedEl ) ; } return sb . toString ( ) ; }
Joins a list of elements into a resource id escaping special characters if required .
3,541
private Double aggregate ( Datasource ds , Collection < Double > values ) { return ( ( values . size ( ) / m_intervalsPer ) > ds . getXff ( ) ) ? ds . getAggregationFuction ( ) . apply ( values ) : Double . NaN ; }
is within XFF otherwise return NaN .
3,542
private boolean inRange ( ) { if ( m_working == null || m_nextOut == null ) { return false ; } Timestamp rangeUpper = m_nextOut . getTimestamp ( ) ; Timestamp rangeLower = m_nextOut . getTimestamp ( ) . minus ( m_resolution ) ; return m_working . getTimestamp ( ) . lte ( rangeUpper ) && m_working . getTimestamp ( ) . gt ( rangeLower ) ; }
true if the working input Row is within the Range of the next output Row ; false otherwise
3,543
public Class < ? > getBody ( String message ) { final Set < IdentifierLine > identifierLines = this . definitions . keySet ( ) ; final IdentifierLine messageId = new IdentifierLine ( ) ; for ( IdentifierLine id : identifierLines ) { final Map < Integer , String > mapIds = id . getMapIds ( ) ; final Set < Integer > keys = mapIds . keySet ( ) ; for ( Integer startPosition : keys ) { final String textId = mapIds . get ( startPosition ) ; int sizeText = textId . length ( ) ; int finalPosition = startPosition + sizeText ; if ( finalPosition > message . length ( ) ) { break ; } messageId . putId ( startPosition , message . substring ( startPosition , finalPosition ) ) ; } if ( id . equals ( messageId ) ) { this . body = this . definitions . get ( messageId ) ; break ; } else { messageId . getMapIds ( ) . clear ( ) ; } } if ( this . body == null ) { throw new FFPojoException ( String . format ( "No class matches with the line starting with: %s " , getStartWithText ( message ) ) ) ; } return this . body ; }
GETTERS AND SETTERS
3,544
public static ExpectedCondition < List < WebElement > > presenceOfNbElementsLocatedBy ( final By locator , final int nb ) { return new ExpectedCondition < List < WebElement > > ( ) { public List < WebElement > apply ( WebDriver driver ) { final List < WebElement > elements = driver . findElements ( locator ) ; return elements . size ( ) == nb ? elements : null ; } } ; }
An expectation for checking that nb elements that match the locator are present on the web page .
3,545
public static ExpectedCondition < List < WebElement > > visibilityOfNbElementsLocatedBy ( final By locator , final int nb ) { return new ExpectedCondition < List < WebElement > > ( ) { public List < WebElement > apply ( WebDriver driver ) { int nbElementIsDisplayed = 0 ; final List < WebElement > elements = driver . findElements ( locator ) ; for ( final WebElement element : elements ) { if ( element . isDisplayed ( ) ) { nbElementIsDisplayed ++ ; } } return nbElementIsDisplayed == nb ? elements : null ; } } ; }
An expectation for checking that nb elements present on the web page that match the locator are visible . Visibility means that the elements are not only displayed but also have a height and width that is greater than 0 .
3,546
public static ExpectedCondition < Boolean > waitForLoad ( ) { return new ExpectedCondition < Boolean > ( ) { public Boolean apply ( WebDriver driver ) { return ( ( JavascriptExecutor ) driver ) . executeScript ( "return document.readyState" ) . equals ( "complete" ) ; } } ; }
Expects that the target page is completely loaded .
3,547
public static String format ( String templateMessage , Object ... args ) throws TechnicalException { if ( null != templateMessage && countWildcardsOccurrences ( templateMessage , "%s" ) == args . length ) { try { return String . format ( templateMessage , args ) ; } catch ( final Exception e ) { throw new TechnicalException ( getMessage ( FAIL_MESSAGE_FORMAT_STRING ) , e ) ; } } else { throw new TechnicalException ( getMessage ( FAIL_MESSAGE_FORMAT_STRING ) ) ; } }
Format given message with provided arguments
3,548
public static String getMessage ( String key , String bundle ) { if ( ! messagesBundles . containsKey ( bundle ) ) { if ( Context . getLocale ( ) == null ) { messagesBundles . put ( bundle , ResourceBundle . getBundle ( "i18n/" + bundle , Locale . getDefault ( ) ) ) ; } else { messagesBundles . put ( bundle , ResourceBundle . getBundle ( "i18n/" + bundle , Context . getLocale ( ) ) ) ; } } return messagesBundles . get ( bundle ) . getString ( key ) ; }
Gets a message by key using the resources bundle given in parameters .
3,549
private static int countWildcardsOccurrences ( String templateMessage , String occurrence ) { if ( templateMessage != null && occurrence != null ) { final Pattern pattern = Pattern . compile ( occurrence ) ; final Matcher matcher = pattern . matcher ( templateMessage ) ; int count = 0 ; while ( matcher . find ( ) ) { count ++ ; } return count ; } else { return 0 ; } }
Count the number of occurrences of a given wildcard .
3,550
public void writeFailedResult ( int line , String value ) { logger . debug ( "Write Failed result => line:{} value:{}" , line , value ) ; writeValue ( resultColumnName , line , value ) ; }
Writes a fail result
3,551
public void writeSuccessResult ( int line ) { logger . debug ( "Write Success result => line:{}" , line ) ; writeValue ( resultColumnName , line , Messages . getMessage ( Messages . SUCCESS_MESSAGE ) ) ; }
Writes a success result
3,552
public void writeWarningResult ( int line , String value ) { logger . debug ( "Write Warning result => line:{} value:{}" , line , value ) ; writeValue ( resultColumnName , line , value ) ; }
Writes a warning result
3,553
public void writeDataResult ( String column , int line , String value ) { logger . debug ( "Write Data result => column:{} line:{} value:{}" , column , line , value ) ; writeValue ( column , line , value ) ; }
Writes some data as result .
3,554
private void displayMessageAtTheBeginningOfMethod ( String methodName , List < GherkinStepCondition > conditions ) { logger . debug ( "{} with {} contition(s)" , methodName , conditions . size ( ) ) ; displayConditionsAtTheBeginningOfMethod ( conditions ) ; }
Display a message at the beginning of method .
3,555
public boolean checkConditions ( List < GherkinStepCondition > conditions ) { for ( GherkinStepCondition gherkinCondition : conditions ) { logger . debug ( "checkConditions {} in context is " , gherkinCondition . getActual ( ) , Context . getValue ( gherkinCondition . getActual ( ) ) ) ; if ( ! gherkinCondition . checkCondition ( ) ) { return false ; } } return true ; }
Check all conditions .
3,556
@ Et ( "Je sauvegarde la valeur de cette API REST '(.*)' '(.*)' '(.*)' dans '(.*)' du contexte[\\.|\\?]" ) @ And ( "I save the value of REST API '(.*)' '(.*)' '(.*)' in '(.*)' context key[\\.|\\?]" ) public void saveValue ( String method , String pageKey , String uri , String targetKey , List < GherkinStepCondition > conditions ) throws TechnicalException , FailureException { logger . debug ( "saveValue of REST API with method [{}]." , method ) ; logger . debug ( "saveValue of REST API with pageKey [{}]." , pageKey ) ; logger . debug ( "saveValue of REST API with uri [{}]." , uri ) ; logger . debug ( "saveValue of REST API in targetKey [{}]." , targetKey ) ; String json = null ; try { json = httpService . get ( Context . getUrlByPagekey ( pageKey ) , uri ) ; } catch ( HttpServiceException e ) { logger . error ( Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_CALL_API_REST ) , e ) ; new Result . Failure < > ( Context . getApplicationByPagekey ( pageKey ) , Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_CALL_API_REST ) , true , Context . getCallBack ( Callbacks . RESTART_WEB_DRIVER ) ) ; } Context . saveValue ( targetKey , json ) ; }
Save result of REST API in memory if all expected parameters equals actual parameters in conditions .
3,557
@ Experimental ( name = "validActivationEmail" ) @ RetryOnFailure ( attempts = 3 , delay = 60 ) @ Et ( "Je valide le mail d'activation '(.*)'[\\.|\\?]" ) @ And ( "I valid activation email '(.*)'[\\.|\\?]" ) public void validActivationEmail ( String mailHost , String mailUser , String mailPassword , String senderMail , String subjectMail , String firstCssQuery , List < GherkinStepCondition > conditions ) throws FailureException , TechnicalException { try { final Properties props = System . getProperties ( ) ; props . setProperty ( "mail.store.protocol" , "imap" ) ; final Session session = Session . getDefaultInstance ( props , null ) ; final Store store = session . getStore ( "imaps" ) ; store . connect ( mailHost , mailUser , mailPassword ) ; final Folder inbox = store . getFolder ( "Inbox" ) ; inbox . open ( Folder . READ_ONLY ) ; final SearchTerm filterA = new FlagTerm ( new Flags ( Flags . Flag . SEEN ) , false ) ; final SearchTerm filterB = new FromTerm ( new InternetAddress ( senderMail ) ) ; final SearchTerm filterC = new SubjectTerm ( subjectMail ) ; final SearchTerm [ ] filters = { filterA , filterB , filterC } ; final SearchTerm searchTerm = new AndTerm ( filters ) ; final Message [ ] messages = inbox . search ( searchTerm ) ; for ( final Message message : messages ) { validateActivationLink ( subjectMail , firstCssQuery , message ) ; } } catch ( final Exception e ) { new Result . Failure < > ( "" , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_MAIL_ACTIVATION ) , subjectMail ) , false , Context . getCallBack ( Callbacks . RESTART_WEB_DRIVER ) ) ; } }
Valid activation email .
3,558
@ Times ( { @ Time ( name = "AM" ) , @ Time ( name = "{pageKey}" ) } ) @ Lorsque ( "'(.*)' est ouvert[\\.|\\?]" ) @ Given ( "'(.*)' is opened[\\.|\\?]" ) public void openUrlIfDifferent ( @ TimeName ( "pageKey" ) String pageKey , List < GherkinStepCondition > conditions ) throws TechnicalException , FailureException { goToUrl ( pageKey , false ) ; }
Open Url if different with conditions .
3,559
@ Et ( "Je retourne vers '(.*)'" ) @ And ( "I go back to '(.*)'" ) public void goToUrl ( String pageKey ) throws TechnicalException , FailureException { goToUrl ( pageKey , true ) ; }
Go to Url .
3,560
private void navigateTo ( String pageKey , String urlToOpen , String windowHandle ) { Context . addWindow ( pageKey , windowHandle ) ; Context . setMainWindow ( pageKey ) ; Context . getDriver ( ) . navigate ( ) . to ( urlToOpen ) ; }
navigateTo change url on the same window .
3,561
private void switchToWindow ( String key , String handleToKeep ) { Context . addWindow ( key , handleToKeep ) ; Context . setMainWindow ( key ) ; Context . getDriver ( ) . switchTo ( ) . window ( handleToKeep ) ; }
switchToWindow switch to an other Window .
3,562
protected void clickOn ( PageElement toClick , Object ... args ) throws TechnicalException , FailureException { displayMessageAtTheBeginningOfMethod ( "clickOn: %s in %s" , toClick . toString ( ) , toClick . getPage ( ) . getApplication ( ) ) ; try { Context . waitUntil ( ExpectedConditions . elementToBeClickable ( Utilities . getLocator ( toClick , args ) ) ) . click ( ) ; } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_OPEN_ON_CLICK ) , toClick , toClick . getPage ( ) . getApplication ( ) ) , true , toClick . getPage ( ) . getCallBack ( ) ) ; } }
Click on html element .
3,563
protected boolean checkInputText ( PageElement pageElement , String textOrKey ) throws FailureException , TechnicalException { WebElement inputText = null ; String value = getTextOrKey ( textOrKey ) ; try { inputText = Context . waitUntil ( ExpectedConditions . presenceOfElementLocated ( Utilities . getLocator ( pageElement ) ) ) ; } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } return ! ( inputText == null || value == null || inputText . getAttribute ( VALUE ) == null || ! value . equals ( inputText . getAttribute ( VALUE ) . trim ( ) ) ) ; }
Checks if input text contains expected value .
3,564
protected void expectText ( PageElement pageElement , String textOrKey ) throws FailureException , TechnicalException { WebElement element = null ; String value = getTextOrKey ( textOrKey ) ; try { element = Context . waitUntil ( ExpectedConditions . presenceOfElementLocated ( Utilities . getLocator ( pageElement ) ) ) ; } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } try { Context . waitUntil ( ExpectSteps . textToBeEqualsToExpectedValue ( Utilities . getLocator ( pageElement ) , value ) ) ; } catch ( final Exception e ) { logger . error ( "error in expectText. element is [{}]" , element == null ? null : element . getText ( ) ) ; new Result . Failure < > ( element == null ? null : element . getText ( ) , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_WRONG_EXPECTED_VALUE ) , pageElement , textOrKey . startsWith ( cryptoService . getPrefix ( ) ) ? SECURE_MASK : value , pageElement . getPage ( ) . getApplication ( ) ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } }
Expects that an element contains expected value .
3,565
protected boolean checkMandatoryTextField ( PageElement pageElement ) throws FailureException { WebElement inputText = null ; try { inputText = Context . waitUntil ( ExpectedConditions . presenceOfElementLocated ( Utilities . getLocator ( pageElement ) ) ) ; } catch ( final Exception e ) { new Result . Failure < > ( pageElement , Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } return ! ( inputText == null || "" . equals ( inputText . getAttribute ( VALUE ) . trim ( ) ) ) ; }
Checks mandatory text field .
3,566
protected void checkText ( PageElement pageElement , String textOrKey ) throws TechnicalException , FailureException { WebElement webElement = null ; String value = getTextOrKey ( textOrKey ) ; try { webElement = Context . waitUntil ( ExpectedConditions . presenceOfElementLocated ( Utilities . getLocator ( pageElement ) ) ) ; } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } final String innerText = webElement == null ? null : webElement . getText ( ) ; logger . info ( "checkText() expected [{}] and found [{}]." , textOrKey . startsWith ( cryptoService . getPrefix ( ) ) ? SECURE_MASK : value , innerText ) ; if ( ! value . equals ( innerText ) ) { new Result . Failure < > ( innerText , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_WRONG_EXPECTED_VALUE ) , pageElement , textOrKey . startsWith ( cryptoService . getPrefix ( ) ) ? SECURE_MASK : value , pageElement . getPage ( ) . getApplication ( ) ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } }
Checks if HTML text contains expected value .
3,567
protected void updateList ( PageElement pageElement , String textOrKey ) throws TechnicalException , FailureException { String value = getTextOrKey ( textOrKey ) ; try { setDropDownValue ( pageElement , value ) ; } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_ERROR_ON_INPUT ) , pageElement , pageElement . getPage ( ) . getApplication ( ) ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } }
Update a html select with a text value .
3,568
protected void updateDateValidated ( PageElement pageElement , String dateType , String date ) throws TechnicalException , FailureException { logger . debug ( "updateDateValidated with elementName={}, dateType={} and date={}" , pageElement , dateType , date ) ; final DateFormat formatter = new SimpleDateFormat ( Constants . DATE_FORMAT ) ; final Date today = Calendar . getInstance ( ) . getTime ( ) ; try { final Date valideDate = formatter . parse ( date ) ; if ( "any" . equals ( dateType ) ) { logger . debug ( "update Date with any date: {}" , date ) ; updateText ( pageElement , date ) ; } else if ( formatter . format ( today ) . equals ( date ) && ( "future" . equals ( dateType ) || "today" . equals ( dateType ) ) ) { logger . debug ( "update Date with today" ) ; updateText ( pageElement , date ) ; } else if ( valideDate . after ( Calendar . getInstance ( ) . getTime ( ) ) && ( "future" . equals ( dateType ) || "future_strict" . equals ( dateType ) ) ) { logger . debug ( "update Date with a date after today: {}" , date ) ; updateText ( pageElement , date ) ; } else { new Result . Failure < > ( date , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_UNEXPECTED_DATE ) , Messages . getMessage ( Messages . DATE_GREATER_THAN_TODAY ) ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } } catch ( final ParseException e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_WRONG_DATE_FORMAT ) , pageElement , date ) , false , pageElement . getPage ( ) . getCallBack ( ) ) ; } }
Update a html input text value with a date .
3,569
protected void saveElementValue ( String field , String targetKey , Page page ) throws TechnicalException , FailureException { logger . debug ( "saveValueInStep: {} to {} in {}." , field , targetKey , page . getApplication ( ) ) ; String txt = "" ; try { final WebElement elem = Utilities . findElement ( page , field ) ; txt = elem . getAttribute ( VALUE ) != null ? elem . getAttribute ( VALUE ) : elem . getText ( ) ; } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT ) , true , page . getCallBack ( ) ) ; } try { Context . saveValue ( targetKey , txt ) ; Context . getCurrentScenario ( ) . write ( "SAVE " + targetKey + "=" + txt ) ; } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_RETRIEVE_VALUE ) , page . getPageElementByKey ( field ) , page . getApplication ( ) ) , true , page . getCallBack ( ) ) ; } }
Save value in memory .
3,570
protected boolean checkRadioList ( PageElement pageElement , String value ) throws FailureException { try { final List < WebElement > radioButtons = Context . waitUntil ( ExpectedConditions . presenceOfAllElementsLocatedBy ( Utilities . getLocator ( pageElement ) ) ) ; for ( final WebElement button : radioButtons ) { if ( button . getAttribute ( VALUE ) . equalsIgnoreCase ( value ) && button . isSelected ( ) ) { return true ; } } } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } return false ; }
Checks that given value is matching the selected radio list button .
3,571
protected void updateRadioList ( PageElement pageElement , String valueOrKey ) throws TechnicalException , FailureException { final String value = Context . getValue ( valueOrKey ) != null ? Context . getValue ( valueOrKey ) : valueOrKey ; try { final List < WebElement > radioButtons = Context . waitUntil ( ExpectedConditions . presenceOfAllElementsLocatedBy ( Utilities . getLocator ( pageElement ) ) ) ; for ( final WebElement button : radioButtons ) { if ( button . getAttribute ( VALUE ) . contains ( value ) ) { button . click ( ) ; break ; } } } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_SELECT_RADIO_BUTTON ) , pageElement ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } }
Update html radio button by text input .
3,572
protected void passOver ( PageElement element ) throws TechnicalException , FailureException { try { final String javascript = "var evObj = document.createEvent('MouseEvents');" + "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);" + "arguments[0].dispatchEvent(evObj);" ; ( ( JavascriptExecutor ) getDriver ( ) ) . executeScript ( javascript , Context . waitUntil ( ExpectedConditions . presenceOfElementLocated ( Utilities . getLocator ( element ) ) ) ) ; } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_PASS_OVER_ELEMENT ) , element , element . getPage ( ) . getApplication ( ) ) , true , element . getPage ( ) . getCallBack ( ) ) ; } }
Passes over a specific page element triggering mouseover js event .
3,573
protected void selectCheckbox ( PageElement element , boolean checked , Object ... args ) throws TechnicalException , FailureException { try { final WebElement webElement = Context . waitUntil ( ExpectedConditions . elementToBeClickable ( Utilities . getLocator ( element , args ) ) ) ; if ( webElement . isSelected ( ) != checked ) { webElement . click ( ) ; } } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_CHECK_ELEMENT ) , element , element . getPage ( ) . getApplication ( ) ) , true , element . getPage ( ) . getCallBack ( ) ) ; } }
Checks a checkbox type element .
3,574
protected void switchFrame ( PageElement element , Object ... args ) throws FailureException , TechnicalException { try { Context . waitUntil ( ExpectedConditions . frameToBeAvailableAndSwitchToIt ( Utilities . getLocator ( element , args ) ) ) ; } catch ( final Exception e ) { new Result . Failure < > ( element , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_UNABLE_TO_SWITCH_FRAME ) , element , element . getPage ( ) . getApplication ( ) ) , true , element . getPage ( ) . getCallBack ( ) ) ; } }
Switches to the given frame .
3,575
protected void uploadFile ( PageElement pageElement , String fileOrKey , Object ... args ) throws TechnicalException , FailureException { final String path = Context . getValue ( fileOrKey ) != null ? Context . getValue ( fileOrKey ) : System . getProperty ( USER_DIR ) + File . separator + DOWNLOADED_FILES_FOLDER + File . separator + fileOrKey ; if ( ! "" . equals ( path ) ) { try { final WebElement element = Context . waitUntil ( ExpectedConditions . presenceOfElementLocated ( Utilities . getLocator ( pageElement , args ) ) ) ; element . clear ( ) ; if ( DriverFactory . IE . equals ( Context . getBrowser ( ) ) ) { final String javascript = "arguments[0].value='" + path + "';" ; ( ( JavascriptExecutor ) getDriver ( ) ) . executeScript ( javascript , element ) ; } else { element . sendKeys ( path ) ; } } catch ( final Exception e ) { new Result . Failure < > ( e . getMessage ( ) , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_UPLOADING_FILE ) , path ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } } else { logger . debug ( "Empty data provided. No need to update file upload path. If you want clear data, you need use: \"I clear text in ...\"" ) ; } }
Updates a html file input with the path of the file to upload .
3,576
public static Map < String , Method > getAllCucumberMethods ( Class < ? > clazz ) { final Map < String , Method > result = new HashMap < > ( ) ; final CucumberOptions co = clazz . getAnnotation ( CucumberOptions . class ) ; final Set < Class < ? > > classes = getClasses ( co . glue ( ) ) ; classes . add ( BrowserSteps . class ) ; for ( final Class < ? > c : classes ) { final Method [ ] methods = c . getDeclaredMethods ( ) ; for ( final Method method : methods ) { for ( final Annotation stepAnnotation : method . getAnnotations ( ) ) { if ( stepAnnotation . annotationType ( ) . isAnnotationPresent ( StepDefAnnotation . class ) ) { result . put ( stepAnnotation . toString ( ) , method ) ; } } } } return result ; }
Gets all Cucumber methods .
3,577
public static Cookie getAuthenticationCookie ( String domainUrl ) throws TechnicalException { if ( getInstance ( ) . authCookie == null ) { final String cookieStr = System . getProperty ( SESSION_COOKIE ) ; try { if ( cookieStr != null && ! "" . equals ( cookieStr ) ) { final int indexValue = cookieStr . indexOf ( '=' ) ; final int indexPath = cookieStr . indexOf ( ",path=" ) ; final String cookieName = cookieStr . substring ( 0 , indexValue ) ; final String cookieValue = cookieStr . substring ( indexValue + 1 , indexPath ) ; final String cookieDomain = new URI ( domainUrl ) . getHost ( ) . replaceAll ( "self." , "" ) ; final String cookiePath = cookieStr . substring ( indexPath + 6 ) ; getInstance ( ) . authCookie = new Cookie . Builder ( cookieName , cookieValue ) . domain ( cookieDomain ) . path ( cookiePath ) . build ( ) ; logger . debug ( "New cookie created: {}={} on domain {}{}" , cookieName , cookieValue , cookieDomain , cookiePath ) ; } } catch ( final URISyntaxException e ) { throw new TechnicalException ( Messages . getMessage ( WRONG_URI_SYNTAX ) , e ) ; } } return getInstance ( ) . authCookie ; }
Returns a Cookie object by retrieving data from - Dcookie maven parameter .
3,578
public static String usingAuthentication ( String url ) { if ( authenticationTypes . BASIC . toString ( ) . equals ( getInstance ( ) . authenticationType ) ) { return url . replace ( "://" , "://" + getLogin ( ) + ":" + getPassword ( ) + "@" ) ; } return url ; }
Process a given url using the current authentication mode .
3,579
public static WebElement isElementPresentAndGetFirstOne ( By element ) { final WebDriver webDriver = Context . getDriver ( ) ; webDriver . manage ( ) . timeouts ( ) . implicitlyWait ( DriverFactory . IMPLICIT_WAIT * 2 , TimeUnit . MICROSECONDS ) ; final List < WebElement > foundElements = webDriver . findElements ( element ) ; final boolean exists = ! foundElements . isEmpty ( ) ; webDriver . manage ( ) . timeouts ( ) . implicitlyWait ( DriverFactory . IMPLICIT_WAIT , TimeUnit . MICROSECONDS ) ; if ( exists ) { return foundElements . get ( 0 ) ; } else { return null ; } }
Check if element present and get first one .
3,580
@ Lorsque ( "Je patiente '(.*)' secondes[\\.|\\?]" ) @ Then ( "I wait '(.*)' seconds[\\.|\\?]" ) public void wait ( int time , List < GherkinStepCondition > conditions ) throws InterruptedException { Thread . sleep ( ( long ) time * 1000 ) ; }
Waits a time in second .
3,581
@ Lorsque ( "Je patiente la disparition de '(.*)-(.*)' avec un timeout de '(.*)' secondes[\\.|\\?]" ) @ Then ( "I wait staleness of '(.*)-(.*)' with timeout of '(.*)' seconds[\\.|\\?]" ) public void waitStalenessOf ( String page , String element , int time , List < GherkinStepCondition > conditions ) throws TechnicalException { final WebElement we = Utilities . findElement ( Page . getInstance ( page ) . getPageElementByKey ( '-' + element ) ) ; Context . waitUntil ( ExpectedConditions . stalenessOf ( we ) , time ) ; }
Waits staleness of element with timeout of x seconds .
3,582
@ Lorsque ( "Si '(.*)' vérifie '(.*)', je fais '(.*)' fois:") @ Then ( "If '(.*)' matches '(.*)', I do '(.*)' times:" ) public void loop ( String actual , String expected , int times , List < GherkinConditionedLoopedStep > steps ) { try { if ( new GherkinStepCondition ( "loopKey" , expected , actual ) . checkCondition ( ) ) { for ( int i = 0 ; i < times ; i ++ ) { runAllStepsInLoop ( steps ) ; } } } catch ( final TechnicalException e ) { throw new AssertError ( Messages . getMessage ( TechnicalException . TECHNICAL_SUBSTEP_ERROR_MESSAGE ) + e . getMessage ( ) ) ; } }
Loops on steps execution for a specific number of times .
3,583
@ Lorsque ( "Je vérifie les champs obligatoires:") @ Given ( "I check mandatory fields:" ) public void checkMandatoryFields ( Map < String , String > mandatoryFields ) throws TechnicalException , FailureException { final List < String > errors = new ArrayList < > ( ) ; for ( final Entry < String , String > element : mandatoryFields . entrySet ( ) ) { if ( "" . equals ( element . getValue ( ) ) ) { errors . add ( element . getKey ( ) ) ; } } if ( ! errors . isEmpty ( ) ) { final StringBuilder errorMessage = new StringBuilder ( ) ; int index = errorMessage . length ( ) ; for ( int j = 0 ; j < errors . size ( ) ; j ++ ) { errorMessage . append ( Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_EMPTY_DATA ) , errors . get ( j ) ) ) ; if ( j == 0 ) { errorMessage . setCharAt ( index , Character . toUpperCase ( errorMessage . charAt ( index ) ) ) ; } else { errorMessage . setCharAt ( index , Character . toLowerCase ( errorMessage . charAt ( index ) ) ) ; } if ( '.' == errorMessage . charAt ( errorMessage . length ( ) - 1 ) ) { errorMessage . deleteCharAt ( errorMessage . length ( ) - 1 ) ; } errorMessage . append ( ", " ) ; index = errorMessage . length ( ) ; } errorMessage . delete ( errorMessage . length ( ) - 2 , errorMessage . length ( ) ) ; errorMessage . append ( '.' ) ; new Result . Failure < > ( mandatoryFields , errorMessage . toString ( ) , false , Context . getCallBack ( Callbacks . RESTART_WEB_DRIVER ) ) ; } }
Check all mandatory fields .
3,584
@ Et ( "Je sauvegarde la valeur de '(.*)-(.*)' dans la clé '(.*)' du contexte[\\.|\\?]") @ And ( "I save the value of '(.*)-(.*)' in '(.*)' context key[\\.|\\?]" ) public void saveValue ( String page , String field , String targetKey , List < GherkinStepCondition > conditions ) throws TechnicalException , FailureException { saveElementValue ( '-' + field , targetKey , Page . getInstance ( page ) ) ; }
Save field in memory if all expected parameters equals actual parameters in conditions . The value is saved directly into the Context targetKey .
3,585
@ Quand ( "Je clique sur '(.*)-(.*)'[\\.|\\?]" ) @ When ( "I click on '(.*)-(.*)'[\\.|\\?]" ) public void clickOn ( String page , String toClick , List < GherkinStepCondition > conditions ) throws TechnicalException , FailureException { logger . debug ( "{} clickOn: {}" , page , toClick ) ; clickOn ( Page . getInstance ( page ) . getPageElementByKey ( '-' + toClick ) ) ; }
Click on html element if all expected parameters equals actual parameters in conditions .
3,586
@ Quand ( "Je clique via js sur xpath '(.*)' de '(.*)' page[\\.|\\?]" ) @ When ( "I click by js on xpath '(.*)' from '(.*)' page[\\.|\\?]" ) public void clickOnXpathByJs ( String xpath , String page , List < GherkinStepCondition > conditions ) throws TechnicalException , FailureException { logger . debug ( "clickOnByJs with xpath {} on {} page" , xpath , page ) ; clickOnByJs ( Page . getInstance ( page ) , xpath ) ; }
Click on html element using Javascript if all expected parameters equals actual parameters in conditions .
3,587
@ Quand ( "Je passe au dessus de '(.*)-(.*)'[\\.|\\?]" ) @ When ( "I pass over '(.*)-(.*)'[\\.|\\?]" ) public void passOver ( String page , String elementName , List < GherkinStepCondition > conditions ) throws TechnicalException , FailureException { passOver ( Page . getInstance ( page ) . getPageElementByKey ( '-' + elementName ) ) ; }
Simulates the mouse over a html element
3,588
@ Quand ( "Je mets à jour la date '(.*)-(.*)' avec une '(.*)' date '(.*)'[\\.|\\?]") @ When ( "I update date '(.*)-(.*)' with a '(.*)' date '(.*)'[\\.|\\?]" ) public void updateDate ( String page , String elementName , String dateType , String dateOrKey , List < GherkinStepCondition > conditions ) throws TechnicalException , FailureException { final String date = Context . getValue ( dateOrKey ) != null ? Context . getValue ( dateOrKey ) : dateOrKey ; if ( ! "" . equals ( date ) ) { final PageElement pageElement = Page . getInstance ( page ) . getPageElementByKey ( '-' + elementName ) ; if ( date . matches ( Constants . DATE_FORMAT_REG_EXP ) ) { updateDateValidated ( pageElement , dateType , date ) ; } else { new Result . Failure < > ( date , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_WRONG_DATE_FORMAT ) , date , elementName ) , false , pageElement . getPage ( ) . getCallBack ( ) ) ; } } }
Update a html input text with a date .
3,589
@ Lorsque ( "Je vérifie le champ obligatoire '(.*)-(.*)' de type '(.*)'[\\.|\\?]") @ Then ( "I check mandatory field '(.*)-(.*)' of type '(.*)'[\\.|\\?]" ) public void checkMandatoryField ( String page , String fieldName , String type , List < GherkinStepCondition > conditions ) throws TechnicalException , FailureException { final PageElement pageElement = Page . getInstance ( page ) . getPageElementByKey ( '-' + fieldName ) ; if ( "text" . equals ( type ) ) { if ( ! checkMandatoryTextField ( pageElement ) ) { new Result . Failure < > ( pageElement , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_EMPTY_MANDATORY_FIELD ) , pageElement , pageElement . getPage ( ) . getApplication ( ) ) , true , pageElement . getPage ( ) . getCallBack ( ) ) ; } } else { new Result . Failure < > ( type , Messages . format ( Messages . getMessage ( Messages . SCENARIO_ERROR_MESSAGE_TYPE_NOT_IMPLEMENTED ) , type , "checkMandatoryField" ) , false , pageElement . getPage ( ) . getCallBack ( ) ) ; } }
Checks that mandatory field is no empty with conditions .
3,590
@ Et ( "Je vérifie le texte '(.*)-(.*)' avec '(.*)'[\\.|\\?]") @ And ( "I check text '(.*)-(.*)' with '(.*)'[\\.|\\?]" ) public void checkInputText ( String page , String elementName , String textOrKey , List < GherkinStepCondition > conditions ) throws FailureException , TechnicalException { if ( ! checkInputText ( Page . getInstance ( page ) . getPageElementByKey ( '-' + elementName ) , textOrKey ) ) { checkText ( Page . getInstance ( page ) . getPageElementByKey ( '-' + elementName ) , textOrKey ) ; } }
Checks if html input text contains expected value .
3,591
@ Et ( "Je vérifie que '(.*)-(.*)' est visible[\\.|\\?]") @ And ( "I check that '(.*)-(.*)' is visible[\\.|\\?]" ) public void checkElementVisible ( String page , String elementName , List < GherkinStepCondition > conditions ) throws FailureException , TechnicalException { checkElementVisible ( Page . getInstance ( page ) . getPageElementByKey ( '-' + elementName ) , true ) ; }
Checks if an html element is visible .
3,592
@ Et ( "Je vérifie le message '(.*)' sur l'alerte") @ And ( "I check message '(.*)' on alert" ) public void checkAlert ( String messageOrKey ) throws TechnicalException , FailureException { final String message = Context . getValue ( messageOrKey ) != null ? Context . getValue ( messageOrKey ) : messageOrKey ; final String msg = getAlertMessage ( ) ; if ( msg == null || ! msg . equals ( message ) ) { new Result . Failure < > ( msg , Messages . format ( Messages . getMessage ( Messages . FAIL_MESSAGE_NOT_FOUND_ON_ALERT ) , message ) , false , Context . getCallBack ( Callbacks . RESTART_WEB_DRIVER ) ) ; } }
Checks that a given page displays a html alert with a message .
3,593
@ Et ( "Je mets à jour la liste radio '(.*)-(.*)' avec '(.*)'[\\.|\\?]") @ And ( "I update radio list '(.*)-(.*)' with '(.*)'[\\.|\\?]" ) public void updateRadioList ( String page , String elementName , String valueOrKey , List < GherkinStepCondition > conditions ) throws TechnicalException , FailureException { updateRadioList ( Page . getInstance ( page ) . getPageElementByKey ( '-' + elementName ) , valueOrKey ) ; }
Updates the value of a html radio element with conditions .
3,594
public WebDriver getDriver ( ) { String driverName = Context . getBrowser ( ) ; driverName = driverName != null ? driverName : DEFAULT_DRIVER ; WebDriver driver = null ; if ( ! drivers . containsKey ( driverName ) ) { try { driver = generateWebDriver ( driverName ) ; } catch ( final TechnicalException e ) { logger . error ( "error DriverFactory.getDriver()" , e ) ; } } else { driver = drivers . get ( driverName ) ; } return driver ; }
Get selenium driver . Drivers are lazy loaded .
3,595
private WebDriver generateIEDriver ( ) throws TechnicalException { final String pathWebdriver = DriverFactory . getPath ( Driver . IE ) ; if ( ! new File ( pathWebdriver ) . setExecutable ( true ) ) { throw new TechnicalException ( Messages . getMessage ( TechnicalException . TECHNICAL_ERROR_MESSAGE_WEBDRIVER_SET_EXECUTABLE ) ) ; } logger . info ( "Generating IE driver ({}) ..." , pathWebdriver ) ; System . setProperty ( Driver . IE . getDriverName ( ) , pathWebdriver ) ; final DesiredCapabilities capabilities = DesiredCapabilities . internetExplorer ( ) ; capabilities . setCapability ( InternetExplorerDriver . IE_ENSURE_CLEAN_SESSION , true ) ; capabilities . setCapability ( InternetExplorerDriver . IGNORE_ZOOM_SETTING , true ) ; capabilities . setCapability ( InternetExplorerDriver . REQUIRE_WINDOW_FOCUS , true ) ; capabilities . setCapability ( InternetExplorerDriver . NATIVE_EVENTS , false ) ; capabilities . setCapability ( CapabilityType . UNEXPECTED_ALERT_BEHAVIOUR , UnexpectedAlertBehaviour . ACCEPT ) ; capabilities . setCapability ( InternetExplorerDriver . INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS , true ) ; capabilities . setCapability ( "disable-popup-blocking" , true ) ; capabilities . setJavascriptEnabled ( true ) ; setLoggingLevel ( capabilities ) ; if ( Context . getProxy ( ) . getProxyType ( ) != ProxyType . UNSPECIFIED && Context . getProxy ( ) . getProxyType ( ) != ProxyType . AUTODETECT ) { capabilities . setCapability ( CapabilityType . PROXY , Context . getProxy ( ) ) ; } return new InternetExplorerDriver ( capabilities ) ; }
Generates an ie webdriver . Unable to use it with a proxy . Causes a crash .
3,596
private WebDriver generateGoogleChromeDriver ( ) throws TechnicalException { final String pathWebdriver = DriverFactory . getPath ( Driver . CHROME ) ; if ( ! new File ( pathWebdriver ) . setExecutable ( true ) ) { throw new TechnicalException ( Messages . getMessage ( TechnicalException . TECHNICAL_ERROR_MESSAGE_WEBDRIVER_SET_EXECUTABLE ) ) ; } logger . info ( "Generating Chrome driver ({}) ..." , pathWebdriver ) ; System . setProperty ( Driver . CHROME . getDriverName ( ) , pathWebdriver ) ; final ChromeOptions chromeOptions = new ChromeOptions ( ) ; final DesiredCapabilities capabilities = DesiredCapabilities . chrome ( ) ; capabilities . setCapability ( CapabilityType . ForSeleniumServer . ENSURING_CLEAN_SESSION , true ) ; capabilities . setCapability ( CapabilityType . UNEXPECTED_ALERT_BEHAVIOUR , UnexpectedAlertBehaviour . ACCEPT ) ; setLoggingLevel ( capabilities ) ; if ( Context . isHeadless ( ) ) { chromeOptions . addArguments ( "--headless" ) ; } if ( Context . getProxy ( ) . getProxyType ( ) != ProxyType . UNSPECIFIED && Context . getProxy ( ) . getProxyType ( ) != ProxyType . AUTODETECT ) { capabilities . setCapability ( CapabilityType . PROXY , Context . getProxy ( ) ) ; } setChromeOptions ( capabilities , chromeOptions ) ; final String withWhitelistedIps = Context . getWebdriversProperties ( "withWhitelistedIps" ) ; if ( withWhitelistedIps != null && ! "" . equals ( withWhitelistedIps ) ) { final ChromeDriverService service = new ChromeDriverService . Builder ( ) . withWhitelistedIps ( withWhitelistedIps ) . withVerbose ( false ) . build ( ) ; return new ChromeDriver ( service , capabilities ) ; } else { return new ChromeDriver ( capabilities ) ; } }
Generates a chrome webdriver .
3,597
private void setChromeOptions ( final DesiredCapabilities capabilities , ChromeOptions chromeOptions ) { final HashMap < String , Object > chromePrefs = new HashMap < > ( ) ; chromePrefs . put ( "download.default_directory" , System . getProperty ( USER_DIR ) + File . separator + DOWNLOADED_FILES_FOLDER ) ; chromeOptions . setExperimentalOption ( "prefs" , chromePrefs ) ; final String targetBrowserBinaryPath = Context . getWebdriversProperties ( "targetBrowserBinaryPath" ) ; if ( targetBrowserBinaryPath != null && ! "" . equals ( targetBrowserBinaryPath ) ) { chromeOptions . setBinary ( targetBrowserBinaryPath ) ; } capabilities . setCapability ( ChromeOptions . CAPABILITY , chromeOptions ) ; }
Sets the target browser binary path in chromeOptions if it exists in configuration .
3,598
private WebDriver generateFirefoxDriver ( ) throws TechnicalException { final String pathWebdriver = DriverFactory . getPath ( Driver . FIREFOX ) ; if ( ! new File ( pathWebdriver ) . setExecutable ( true ) ) { throw new TechnicalException ( Messages . getMessage ( TechnicalException . TECHNICAL_ERROR_MESSAGE_WEBDRIVER_SET_EXECUTABLE ) ) ; } logger . info ( "Generating Firefox driver ({}) ..." , pathWebdriver ) ; System . setProperty ( Driver . FIREFOX . getDriverName ( ) , pathWebdriver ) ; final FirefoxOptions firefoxOptions = new FirefoxOptions ( ) ; final FirefoxBinary firefoxBinary = new FirefoxBinary ( ) ; final DesiredCapabilities capabilities = DesiredCapabilities . firefox ( ) ; capabilities . setCapability ( CapabilityType . ForSeleniumServer . ENSURING_CLEAN_SESSION , true ) ; capabilities . setCapability ( CapabilityType . UNEXPECTED_ALERT_BEHAVIOUR , UnexpectedAlertBehaviour . ACCEPT ) ; setLoggingLevel ( capabilities ) ; if ( Context . getProxy ( ) . getProxyType ( ) != ProxyType . UNSPECIFIED && Context . getProxy ( ) . getProxyType ( ) != ProxyType . AUTODETECT ) { capabilities . setCapability ( CapabilityType . PROXY , Context . getProxy ( ) ) ; } if ( Context . isHeadless ( ) ) { firefoxBinary . addCommandLineOptions ( "--headless" ) ; firefoxOptions . setBinary ( firefoxBinary ) ; } firefoxOptions . setLogLevel ( Level . OFF ) ; capabilities . setCapability ( FirefoxOptions . FIREFOX_OPTIONS , firefoxOptions ) ; return new FirefoxDriver ( capabilities ) ; }
Generates a firefox webdriver .
3,599
private WebDriver generateWebDriver ( String driverName ) throws TechnicalException { WebDriver driver ; if ( IE . equals ( driverName ) ) { driver = generateIEDriver ( ) ; } else if ( CHROME . equals ( driverName ) ) { driver = generateGoogleChromeDriver ( ) ; } else if ( FIREFOX . equals ( driverName ) ) { driver = generateFirefoxDriver ( ) ; } else { driver = generateGoogleChromeDriver ( ) ; } driver . manage ( ) . window ( ) . setSize ( new Dimension ( 1920 , 1080 ) ) ; driver . manage ( ) . timeouts ( ) . implicitlyWait ( IMPLICIT_WAIT , TimeUnit . MILLISECONDS ) ; drivers . put ( driverName , driver ) ; return driver ; }
Generates a selenium webdriver following a name given in parameter . By default a chrome driver is generated .