idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
24,100 | final void addData ( final AbstractMeter meter , final double data ) { checkIfMeterExists ( meter ) ; meterResults . get ( meter ) . add ( data ) ; } | Adding a data to a meter . |
24,101 | private void checkIfMeterExists ( final AbstractMeter meter ) { if ( ! meterResults . containsKey ( meter ) ) { meterResults . put ( meter , new LinkedList < Double > ( ) ) ; } } | Checking method if meter is registered otherwise inserting a suitable data structure . |
24,102 | public void onTokenRefresh ( ) { Intent intent = new Intent ( ACTION_REFRESH_PUSH ) ; LocalBroadcastManager . getInstance ( getApplicationContext ( ) ) . sendBroadcast ( intent ) ; } | Called if InstanceID token is updated . This may occur if the security of the previous token had been compromised . Note that this is also called when the InstanceID token is initially generated so this is where you retrieve the token . |
24,103 | public static BenchmarkExecutor getExecutor ( final BenchmarkElement meth ) { if ( BENCHRES == null ) { throw new IllegalStateException ( "Call initialize method first!" ) ; } if ( ! EXECUTOR . containsKey ( meth . getMeth ( ) ) ) { EXECUTOR . put ( meth . getMeth ( ) , new BenchmarkExecutor ( meth . getMeth ( ) ) ) ; int runsOnAnno = BenchmarkMethod . getNumberOfAnnotatedRuns ( meth . getMeth ( ) . getMethodToBench ( ) ) ; if ( runsOnAnno < 0 ) { runsOnAnno = CONFIG . getRuns ( ) ; } RUNS . put ( meth . getMeth ( ) , runsOnAnno ) ; } return EXECUTOR . get ( meth . getMeth ( ) ) ; } | Getting the executor corresponding to a BenchmarkElement . |
24,104 | public static void initialize ( final AbstractConfig config , final BenchmarkResult result ) { METERS_TO_BENCH . clear ( ) ; METERS_TO_BENCH . addAll ( Arrays . asList ( config . getMeters ( ) ) ) ; EXECUTOR . clear ( ) ; BENCHRES = result ; CONFIG = config ; } | Initializing the executor . |
24,105 | public static PerfidixMethodInvocationException invokeMethod ( final Object obj , final Class < ? extends Annotation > relatedAnno , final Method meth , final Object ... args ) { try { meth . invoke ( obj , args ) ; return null ; } catch ( final IllegalArgumentException e ) { return new PerfidixMethodInvocationException ( e , meth , relatedAnno ) ; } catch ( final IllegalAccessException e ) { return new PerfidixMethodInvocationException ( e , meth , relatedAnno ) ; } catch ( final InvocationTargetException e ) { return new PerfidixMethodInvocationException ( e . getCause ( ) , meth , relatedAnno ) ; } } | Method to invoke a reflective invokable method . |
24,106 | public static PerfidixMethodCheckException checkMethod ( final Object obj , final Class < ? extends Annotation > anno , final Method ... meths ) { for ( Method meth : meths ) { boolean classMethodCorr = false ; for ( final Method methodOfClass : obj . getClass ( ) . getDeclaredMethods ( ) ) { if ( methodOfClass . equals ( meth ) ) { classMethodCorr = true ; } } if ( ! classMethodCorr ) { return new PerfidixMethodCheckException ( new IllegalStateException ( "Object to execute " + obj + " is not having a Method named " + meth + "." ) , meth , anno ) ; } if ( ! BenchmarkMethod . isReflectedExecutable ( meth , anno ) ) { return new PerfidixMethodCheckException ( new IllegalAccessException ( "Method to execute " + meth + " is not reflected executable." ) , meth , anno ) ; } } return null ; } | Checking a method if it is reflective executable and if the mapping to the object fits . |
24,107 | public void executeBench ( final Object objToExecute , final Object ... args ) { final double [ ] meterResults = new double [ METERS_TO_BENCH . size ( ) ] ; final Method meth = element . getMethodToBench ( ) ; int meterIndex1 = 0 ; int meterIndex2 = 0 ; for ( final AbstractMeter meter : METERS_TO_BENCH ) { meterResults [ meterIndex1 ] = meter . getValue ( ) ; meterIndex1 ++ ; } final PerfidixMethodInvocationException res = invokeMethod ( objToExecute , Bench . class , meth , args ) ; for ( final AbstractMeter meter : METERS_TO_BENCH ) { meterResults [ meterIndex2 ] = meter . getValue ( ) - meterResults [ meterIndex2 ] ; meterIndex2 ++ ; } if ( res == null ) { meterIndex1 = 0 ; for ( final AbstractMeter meter : METERS_TO_BENCH ) { BENCHRES . addData ( element , meter , meterResults [ meterIndex1 ] ) ; meterIndex1 ++ ; } } else { BENCHRES . addException ( res ) ; } } | Execution of bench method . All data is stored corresponding to the meters . |
24,108 | private Device loadDevice ( ) { SharedPreferences sharedPreferences = getSharedPreferences ( ) ; return new Device ( ) . setApiSpaceId ( sharedPreferences . getString ( KEY_API_SPACE_ID , null ) ) . setAppVer ( sharedPreferences . getInt ( KEY_APP_VER , - 1 ) ) . setInstanceId ( sharedPreferences . getString ( KEY_INSTANCE_ID , null ) ) . setPushToken ( sharedPreferences . getString ( KEY_PUSH_TOKEN , null ) ) . setDeviceId ( sharedPreferences . getString ( KEY_DEVICE_ID , null ) ) ; } | Loads device details from internal storage . |
24,109 | public void insertRow ( int index , Object element ) { elements . add ( index , element ) ; fireTableRowsInserted ( index , index ) ; } | Add the given element as one row of the table |
24,110 | private void parseEvent ( JsonObject event , Parser parser , int i ) { JsonElement nameJE = event . get ( Event . KEY_NAME ) ; if ( nameJE != null ) { String name = nameJE . getAsString ( ) ; if ( MessageSentEvent . TYPE . equals ( name ) ) { MessageSentEvent parsed = parser . parse ( event , MessageSentEvent . class ) ; messageSent . add ( parsed ) ; map . put ( i , parsed ) ; } else if ( MessageDeliveredEvent . TYPE . equals ( name ) ) { MessageDeliveredEvent parsed = parser . parse ( event , MessageDeliveredEvent . class ) ; messageDelivered . add ( parsed ) ; map . put ( i , parsed ) ; } else if ( MessageReadEvent . TYPE . equals ( name ) ) { MessageReadEvent parsed = parser . parse ( event , MessageReadEvent . class ) ; messageRead . add ( parsed ) ; map . put ( i , parsed ) ; } } } | Parse event and add to appropriate list . |
24,111 | String formatMessage ( int msgLogLevel , String module , String msg ) { return getLevelTag ( msgLogLevel ) + module + ": " + msg ; } | Formats log message for console output . Short version . |
24,112 | public static JSpinner createSpinner ( SpinnerModel model , final int fractionDigits ) { return new JSpinner ( model ) { private static final long serialVersionUID = - 9185142711286020504L ; protected JComponent createEditor ( SpinnerModel model ) { if ( model instanceof SpinnerNumberModel ) { NumberEditor editor = new NumberEditor ( this ) ; DecimalFormat format = editor . getFormat ( ) ; format . setMaximumFractionDigits ( fractionDigits ) ; return editor ; } return super . createEditor ( model ) ; } } ; } | Create a spinner with the given model showing the given number of fraction digits for number models |
24,113 | public static void setSpinnerDraggingEnabled ( final JSpinner spinner , boolean enabled ) { SpinnerModel spinnerModel = spinner . getModel ( ) ; if ( ! ( spinnerModel instanceof SpinnerNumberModel ) ) { throw new IllegalArgumentException ( "Dragging is only possible for spinners with a " + "SpinnerNumberModel, found " + spinnerModel . getClass ( ) ) ; } if ( enabled ) { disableSpinnerDragging ( spinner ) ; enableSpinnerDragging ( spinner ) ; } else { disableSpinnerDragging ( spinner ) ; } } | Set whether the value of the given spinner may be changed with mouse drags |
24,114 | public void cacheFile ( ) { if ( orientation == Orientation . INV ) cache = new String [ fields ] [ elements ] ; else cache = new String [ elements ] [ fields ] ; int x = 0 , y = 0 ; Scanner file = null ; try { file = new Scanner ( csvFile ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } String line ; StringTokenizer tokenizer ; while ( file . hasNextLine ( ) ) { line = file . nextLine ( ) ; tokenizer = new StringTokenizer ( line , "," ) ; while ( tokenizer . hasMoreTokens ( ) ) { cache [ y ] [ x ] = tokenizer . nextToken ( ) ; x ++ ; } x = 0 ; y ++ ; } file . close ( ) ; cached = true ; } | load the entire CSV file into memory for much faster access subsequent use of getField will not use file access and will occur in constant time |
24,115 | public void clearAll ( ) { for ( int i = 0 ; i < textFields . size ( ) ; i ++ ) { JTextField textField = textFields . get ( i ) ; if ( textField == null ) { continue ; } textField . setText ( "" ) ; } } | Clear all text fields in this instance |
24,116 | public JTextField createFilterTextField ( int columnIndex ) { while ( textFields . size ( ) - 1 < columnIndex ) { textFields . add ( null ) ; } JTextField textField = new JTextField ( ) ; textFields . set ( columnIndex , textField ) ; Document document = textField . getDocument ( ) ; document . addDocumentListener ( new DocumentListener ( ) { public void removeUpdate ( DocumentEvent e ) { updateFilter ( ) ; } public void insertUpdate ( DocumentEvent e ) { updateFilter ( ) ; } public void changedUpdate ( DocumentEvent e ) { updateFilter ( ) ; } } ) ; return textField ; } | Create the text field for the specified column |
24,117 | private void updateFilter ( ) { List < RowFilter < TableModel , Integer > > regexFilters = new ArrayList < RowFilter < TableModel , Integer > > ( ) ; for ( int i = 0 ; i < textFields . size ( ) ; i ++ ) { JTextField textField = textFields . get ( i ) ; if ( textField == null ) { continue ; } String regex = textField . getText ( ) ; RowFilter < TableModel , Integer > regexFilter = createRegexFilter ( regex , i ) ; if ( regexFilter == null ) { continue ; } regexFilters . add ( regexFilter ) ; } if ( regexFilters . isEmpty ( ) ) { filterConsumer . accept ( null ) ; } else { RowFilter < TableModel , Integer > rowFilter = RowFilter . andFilter ( regexFilters ) ; filterConsumer . accept ( rowFilter ) ; } } | Update the row filter based on the contents of the text fields |
24,118 | public void detach ( ) { textComponent . removePropertyChangeListener ( documentPropertyChangeListener ) ; Document document = textComponent . getDocument ( ) ; document . removeUndoableEditListener ( undoableEditListener ) ; textComponent . getInputMap ( ) . remove ( undoKeyStroke ) ; textComponent . getActionMap ( ) . remove ( DO_UNDO_NAME ) ; textComponent . getInputMap ( ) . remove ( redoKeyStroke ) ; textComponent . getActionMap ( ) . remove ( DO_REDO_NAME ) ; } | Detach this handler from the text component . This will remove all listeners that have been attached to the text component its document and the elements of its input - and action maps . |
24,119 | static Map < Point , Object > addHighlights ( JTextComponent textComponent , Iterable < ? extends Point > appearances , Color color ) { Highlighter . HighlightPainter painter = new DefaultHighlighter . DefaultHighlightPainter ( color ) ; Highlighter highlighter = textComponent . getHighlighter ( ) ; Map < Point , Object > highlights = new LinkedHashMap < Point , Object > ( ) ; for ( Point appearance : appearances ) { try { Object highlight = highlighter . addHighlight ( appearance . x , appearance . y , painter ) ; highlights . put ( appearance , highlight ) ; } catch ( BadLocationException e ) { logger . severe ( e . toString ( ) ) ; } } return highlights ; } | Add the given highlights to the given text component . |
24,120 | static void removeHighlights ( JTextComponent textComponent , Iterable < ? > highlights ) { Highlighter highlighter = textComponent . getHighlighter ( ) ; for ( Object highlight : highlights ) { highlighter . removeHighlight ( highlight ) ; } } | Remove the given highlights from the given text component |
24,121 | synchronized void connect ( ) { if ( socket != null ) { socket . disconnect ( ) ; } final String token = getToken ( ) ; if ( ! TextUtils . isEmpty ( token ) ) { socket = factory . createSocket ( token , new WeakReference < > ( this ) ) ; if ( socket != null ) { socket . connect ( ) ; } } } | Start socket connection . |
24,122 | private String getToken ( ) { SessionData session = dataMgr . getSessionDAO ( ) . session ( ) ; if ( session != null && session . getExpiresOn ( ) > System . currentTimeMillis ( ) ) { return session . getAccessToken ( ) ; } return null ; } | Gets Comapi access token . |
24,123 | private void scheduleReconnection ( ) { if ( runnable != null ) { handler . removeCallbacks ( runnable ) ; } runnable = ( ) -> { if ( shouldReconnect ( ) && ( socket == null || ! socket . isOpen ( ) ) && retryStrategy . retry ( ) && ! isNetworkUnavailable ) { log . d ( "Reconnecting socket" ) ; connect ( ) ; } } ; long delay = retryStrategy . getDelay ( ) ; handler . postDelayed ( runnable , delay ) ; log . d ( "Socket reconnection in " + delay / 1000 + " seconds." ) ; } | Schedule socket connection retry . |
24,124 | public Map < String , Object > asMap ( ) { Map < String , Object > map = new HashMap < > ( ) ; map . putAll ( defaultProperties ) ; map . putAll ( customProperties ) ; return map ; } | Merge all profile properties to a single map . |
24,125 | private void minimize ( ) { if ( timer != null ) { timer . stop ( ) ; timer = null ; } currentHeight = getHeight ( ) ; double steps = ( double ) durationMS / delayMS ; double delta = currentHeight - minimizedHeight ; final int stepSize = ( int ) Math . ceil ( delta / steps ) ; timer = new Timer ( delayMS , new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { currentHeight -= stepSize ; currentHeight = Math . max ( currentHeight , minimizedHeight ) ; if ( currentHeight <= minimizedHeight ) { minimized = true ; timer . stop ( ) ; timer = null ; } revalidate ( ) ; } } ) ; timer . setInitialDelay ( 0 ) ; timer . start ( ) ; } | Performs the minimization process |
24,126 | private void maximize ( ) { if ( timer != null ) { timer . stop ( ) ; timer = null ; } final int targetHeight = getSuperPreferredHeight ( ) ; double steps = ( double ) durationMS / delayMS ; double delta = targetHeight - currentHeight ; final int stepSize = ( int ) Math . ceil ( delta / steps ) ; currentHeight = getHeight ( ) ; timer = new Timer ( delayMS , new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { minimized = false ; currentHeight += stepSize ; currentHeight = Math . min ( currentHeight , targetHeight ) ; if ( currentHeight >= targetHeight ) { currentHeight = Integer . MAX_VALUE ; timer . stop ( ) ; timer = null ; } revalidate ( ) ; } } ) ; timer . setInitialDelay ( 0 ) ; timer . start ( ) ; } | Performs the maximization process |
24,127 | public static BenchmarkResult runBenchs ( final String [ ] benchs ) throws ClassNotFoundException , InstantiationException , IllegalAccessException { final AbstractConfig conf = getConfiguration ( benchs ) ; final Benchmark bench = new Benchmark ( conf ) ; return setUpBenchmark ( benchs , bench ) . run ( ) ; } | Running one Benchmark . |
24,128 | public static Benchmark setUpBenchmark ( final String [ ] classes , final Benchmark benchmark ) throws ClassNotFoundException { for ( final String each : classes ) { benchmark . add ( Class . forName ( each ) ) ; } return benchmark ; } | Setting up an existing benchmark with the given number of class - files |
24,129 | void setId ( String sessionAuthId ) { synchronized ( lock ) { if ( isCreatingSession . get ( ) ) { this . sessionAuthId = sessionAuthId ; } lock . notifyAll ( ) ; } } | Sets id of current authentication process . |
24,130 | public void add ( final int [ ] e ) { if ( size == list . length ) list = Array . copyOf ( list , newSize ( ) ) ; list [ size ++ ] = e ; } | Adds an element . |
24,131 | public void set ( final int i , final int [ ] e ) { if ( i >= list . length ) list = Array . copyOf ( list , newSize ( i + 1 ) ) ; list [ i ] = e ; size = Math . max ( size , i + 1 ) ; } | Sets an element at the specified index . |
24,132 | private String buildFileName ( final String ... names ) { final StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < names . length ; i ++ ) { builder . append ( names [ i ] ) ; if ( i < names . length - 1 ) { builder . append ( SEPARATOR ) ; } } builder . append ( "." ) . append ( "csv" ) ; return builder . toString ( ) ; } | Helper method to build suitable fileNames . |
24,133 | private boolean handleWrapping ( MouseEvent e ) { if ( robot == null ) { return false ; } PointerInfo pointerInfo = null ; try { pointerInfo = MouseInfo . getPointerInfo ( ) ; } catch ( SecurityException ex ) { return false ; } Rectangle r = pointerInfo . getDevice ( ) . getDefaultConfiguration ( ) . getBounds ( ) ; Point onScreen = pointerInfo . getLocation ( ) ; if ( onScreen . y == 0 ) { robot . mouseMove ( onScreen . x , r . height - 2 ) ; previousPoint = new Point ( onScreen . x , r . height - 2 ) ; SwingUtilities . convertPointFromScreen ( previousPoint , spinner ) ; return true ; } else if ( onScreen . y == r . height - 1 ) { robot . mouseMove ( onScreen . x , 1 ) ; previousPoint = new Point ( onScreen . x , 1 ) ; SwingUtilities . convertPointFromScreen ( previousPoint , spinner ) ; return true ; } return false ; } | Let the mouse wrap from the top of the screen to the bottom or vice versa |
24,134 | private void tryCommit ( ) { try { JComponent editor = spinner . getEditor ( ) ; if ( editor instanceof JSpinner . DefaultEditor ) { JSpinner . DefaultEditor defaultEditor = ( JSpinner . DefaultEditor ) editor ; defaultEditor . commitEdit ( ) ; } } catch ( ParseException e1 ) { } } | Try to commit the current value to the spinner editor . This is necessary in order to validate the number in the model against the displayed value . |
24,135 | protected List < BenchmarkElement > arrangeList ( final List < BenchmarkElement > elements ) { final List < BenchmarkElement > elementList = new LinkedList < BenchmarkElement > ( ) ; elementList . addAll ( elements ) ; return elementList ; } | Not arranging the list in this case . That means normally that all elements are occuring in the same order than defined in the class - file . |
24,136 | public List < ComapiValidationFailure > getValidationFailures ( ) { if ( errorBody != null && ! errorBody . isEmpty ( ) ) { ComapiValidationFailures failures = null ; try { failures = new Parser ( ) . parse ( errorBody , ComapiValidationFailures . class ) ; } catch ( Exception e ) { return null ; } return failures . validationFailures ; } return null ; } | Get API call validation failures details . |
24,137 | public static byte [ ] [ ] copyOf ( final byte [ ] [ ] a , final int s ) { final byte [ ] [ ] tmp = new byte [ s ] [ ] ; System . arraycopy ( a , 0 , tmp , 0 , Math . min ( s , a . length ) ) ; return tmp ; } | Copies the specified array . |
24,138 | public static < T > T [ ] add ( final T [ ] ar , final T e ) { final int s = ar . length ; final T [ ] t = Arrays . copyOf ( ar , s + 1 ) ; t [ s ] = e ; return t ; } | Adds an entry to the end of an array and returns the new array . |
24,139 | public static void move ( final Object ar , final int pos , final int off , final int l ) { System . arraycopy ( ar , pos , ar , pos + off , l ) ; } | Moves entries inside an array . |
24,140 | public static < T > T [ ] delete ( final T [ ] ar , final int p ) { final int s = ar . length - 1 ; move ( ar , p + 1 , - 1 , s - p ) ; return Arrays . copyOf ( ar , s ) ; } | Removes an array entry at the specified position . |
24,141 | private static void swap ( final int [ ] arr , final int a , final int b ) { final int c = arr [ a ] ; arr [ a ] = arr [ b ] ; arr [ b ] = c ; } | Swaps two entries of the given int array . |
24,142 | private static Shape createArrowShape ( int w , int y0 , int y1 ) { Path2D path = new Path2D . Double ( ) ; path . moveTo ( 0 , y0 ) ; if ( ( w & 1 ) == 0 ) { path . lineTo ( w >> 1 , y1 ) ; } else { int c = w >> 1 ; path . lineTo ( c , y1 ) ; path . lineTo ( c + 1 , y1 ) ; } path . lineTo ( w , y0 ) ; path . closePath ( ) ; return path ; } | Creates a triangle shape with the given coordinates |
24,143 | private static SortOrder getSortOrder ( JTable table , int column ) { List < ? extends SortKey > sortKeys = table . getRowSorter ( ) . getSortKeys ( ) ; for ( int i = 0 ; i < sortKeys . size ( ) ; i ++ ) { SortKey sortKey = sortKeys . get ( i ) ; if ( sortKey . getColumn ( ) == table . convertColumnIndexToModel ( column ) ) { return sortKey . getSortOrder ( ) ; } } return null ; } | Returns the sort order of the specified column in the given table or null if the column is not sorted |
24,144 | private static int getSortPriority ( JTable table , int column ) { List < ? extends SortKey > sortKeys = table . getRowSorter ( ) . getSortKeys ( ) ; for ( int i = 0 ; i < sortKeys . size ( ) ; i ++ ) { SortKey sortKey = sortKeys . get ( i ) ; if ( sortKey . getColumn ( ) == table . convertColumnIndexToModel ( column ) ) { return i ; } } return - 1 ; } | Returns the sort priority of the specified column in the given table where 0 means the highest priority and - 1 means that the column is not sorted . |
24,145 | public void init ( final Context context , final Handler mainThreadHandler , final Logger logger , final PushTokenProvider provider , final PushTokenListener tokenListener , final PushMessageListener messageListener ) { log = logger ; this . provider = provider != null ? provider : ( ) -> FirebaseInstanceId . getInstance ( ) . getToken ( ) ; registerPushReceiver ( mainThreadHandler , context , this . provider , tokenListener , messageListener ) ; } | Initialise PushManager . |
24,146 | private void registerPushReceiver ( final Handler mainThreadHandler , final Context context , PushTokenProvider provider , final PushTokenListener tokenListener , final PushMessageListener messageListener ) { IntentFilter filter = new IntentFilter ( ) ; filter . addAction ( IDService . ACTION_REFRESH_PUSH ) ; filter . addAction ( PushService . ACTION_PUSH_MESSAGE ) ; receiver = new PushBroadcastReceiver ( mainThreadHandler , provider , tokenListener , messageListener ) ; LocalBroadcastManager . getInstance ( context . getApplicationContext ( ) ) . registerReceiver ( receiver , filter ) ; } | Register local broadcast listener for refreshed push tokens and push messages . |
24,147 | boolean checkAvailablePush ( Context context ) { int connectionStatus = GoogleApiAvailability . getInstance ( ) . isGooglePlayServicesAvailable ( context ) ; if ( connectionStatus == ConnectionResult . SUCCESS ) { log . i ( "Google Play Services are available on this device." ) ; return true ; } else { if ( GoogleApiAvailability . getInstance ( ) . isUserResolvableError ( connectionStatus ) ) { log . e ( "Google Play Services is probably not up to date. User recoverable Error Code is " + connectionStatus ) ; } else { log . e ( "This device is not supported by Google Play Services." ) ; } return false ; } } | Checks if Google Play Services is available on the device . |
24,148 | private static Object [ ] [ ] getDataProviderContent ( final Method meth , final Object toInvoke ) { Object [ ] [ ] res ; try { res = ( Object [ ] [ ] ) meth . invoke ( toInvoke ) ; } catch ( IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new IllegalArgumentException ( "Method " + meth + " as data provider throws an exception on invocation" ) ; } return res ; } | Getting the content of a dataprovider . |
24,149 | public void add ( final Class < ? > clazz ) { if ( this . clazzes . contains ( clazz ) ) { throw new IllegalArgumentException ( "Only one class-instance per benchmark allowed" ) ; } else { this . clazzes . add ( clazz ) ; } } | Adding a class to bench to this benchmark . This class should contain benchmarkable methods otherwise it will be ignored . |
24,150 | public void add ( final Object obj ) { final Class < ? > clazz = obj . getClass ( ) ; if ( this . clazzes . contains ( clazz ) ) { throw new IllegalArgumentException ( "Only one class-instance per benchmark allowed" ) ; } else { this . clazzes . add ( clazz ) ; this . objects . add ( obj ) ; } } | Adding a already instantiated objects to benchmark . Per benchmark only one objects of each class is allowed . |
24,151 | public Map < BenchmarkMethod , Integer > getNumberOfMethodsAndRuns ( ) throws PerfidixMethodCheckException { final Map < BenchmarkMethod , Integer > returnVal = new HashMap < BenchmarkMethod , Integer > ( ) ; final List < BenchmarkMethod > meths = getBenchmarkMethods ( ) ; for ( final BenchmarkMethod meth : meths ) { int numberOfRuns = BenchmarkMethod . getNumberOfAnnotatedRuns ( meth . getMethodToBench ( ) ) ; if ( numberOfRuns == Bench . NONE_RUN ) { numberOfRuns = conf . getRuns ( ) ; } returnVal . put ( meth , numberOfRuns ) ; } return returnVal ; } | Getting the number of all methods and all runs |
24,152 | public BenchmarkResult run ( ) { final BenchmarkResult res = new BenchmarkResult ( conf . getListener ( ) ) ; BenchmarkExecutor . initialize ( conf , res ) ; final Map < Class < ? > , Object > instantiatedObjs = instantiateObjects ( res ) ; try { final List < BenchmarkElement > elements = getBenchmarkElements ( instantiatedObjs ) ; final AbstractMethodArrangement arrangement = AbstractMethodArrangement . getMethodArrangement ( elements , conf . getArrangement ( ) ) ; final Map < Class < ? > , Object > objectsToExecute = executeBeforeBenchClass ( instantiatedObjs , res ) ; for ( final BenchmarkElement elem : arrangement ) { if ( RAN . nextDouble ( ) < conf . getGcProb ( ) ) { System . gc ( ) ; } final BenchmarkExecutor exec = BenchmarkExecutor . getExecutor ( elem ) ; final Object obj = objectsToExecute . get ( elem . getMeth ( ) . getMethodToBench ( ) . getDeclaringClass ( ) ) ; if ( obj != null ) { exec . executeBeforeMethods ( obj ) ; exec . executeBench ( obj , elem . getParameter ( ) ) ; exec . executeAfterMethods ( obj ) ; } } tearDownObjectsToExecute ( objectsToExecute , res ) ; } catch ( PerfidixMethodCheckException exc ) { res . addException ( exc ) ; } return res ; } | Running this benchmark |
24,153 | private Map < Class < ? > , Object > executeBeforeBenchClass ( final Map < Class < ? > , Object > instantiatedObj , final BenchmarkResult res ) { final Map < Class < ? > , Object > returnVal = new Hashtable < Class < ? > , Object > ( ) ; for ( final Class < ? > clazz : instantiatedObj . keySet ( ) ) { final Object objectToUse = instantiatedObj . get ( clazz ) ; Method beforeClassMeth = null ; boolean continueVal = true ; try { beforeClassMeth = BenchmarkMethod . findAndCheckAnyMethodByAnnotation ( clazz , BeforeBenchClass . class ) ; } catch ( final PerfidixMethodCheckException e ) { res . addException ( e ) ; continueVal = false ; } if ( continueVal ) { if ( beforeClassMeth == null ) { returnVal . put ( clazz , objectToUse ) ; } else { final PerfidixMethodCheckException beforeByCheck = BenchmarkExecutor . checkMethod ( objectToUse , BeforeBenchClass . class , beforeClassMeth ) ; if ( beforeByCheck == null ) { final PerfidixMethodInvocationException beforeByInvok = BenchmarkExecutor . invokeMethod ( objectToUse , BeforeBenchClass . class , beforeClassMeth ) ; if ( beforeByInvok == null ) { returnVal . put ( clazz , objectToUse ) ; } else { res . addException ( beforeByInvok ) ; } } else { res . addException ( beforeByCheck ) ; } } } } return returnVal ; } | Executing beforeBenchClass if present . |
24,154 | List < BenchmarkMethod > getBenchmarkMethods ( ) throws PerfidixMethodCheckException { final List < BenchmarkMethod > elems = new ArrayList < BenchmarkMethod > ( ) ; for ( final Class < ? > clazz : clazzes ) { for ( final Method meth : clazz . getDeclaredMethods ( ) ) { if ( BenchmarkMethod . isBenchmarkable ( meth ) ) { final BenchmarkMethod benchmarkMeth = new BenchmarkMethod ( meth ) ; elems . add ( benchmarkMeth ) ; } } } return elems ; } | Getting all Benchmarkable methods out of the registered class . |
24,155 | private List < BenchmarkElement > getBenchmarkElements ( final Map < Class < ? > , Object > paramObjs ) throws PerfidixMethodCheckException { final List < BenchmarkElement > elems = new ArrayList < BenchmarkElement > ( ) ; final List < BenchmarkMethod > meths = getBenchmarkMethods ( ) ; for ( final BenchmarkMethod meth : meths ) { final Method dataProv = meth . getDataProvider ( ) ; if ( dataProv == null ) { int numberOfRuns = BenchmarkMethod . getNumberOfAnnotatedRuns ( meth . getMethodToBench ( ) ) ; if ( numberOfRuns == Bench . NONE_RUN ) { numberOfRuns = conf . getRuns ( ) ; } for ( int i = 0 ; i < numberOfRuns ; i ++ ) { elems . add ( new BenchmarkElement ( meth ) ) ; } } else { final Object [ ] [ ] dataProvider = getDataProviderContent ( dataProv , paramObjs . get ( meth . getMethodToBench ( ) . getDeclaringClass ( ) ) ) ; for ( final Object [ ] parameterSet : dataProvider ) { elems . add ( new BenchmarkElement ( meth , parameterSet ) ) ; } } } return elems ; } | Getting all benchmarkable objects out of the registered classes with the annotated number of runs . |
24,156 | private NiceTable generateMeterResult ( final String columnDesc , final AbstractMeter meter , final AbstractResult result , final NiceTable input ) { input . addRow ( new String [ ] { columnDesc , meter . getUnit ( ) , AbstractOutput . format ( result . sum ( meter ) ) , AbstractOutput . format ( result . min ( meter ) ) , AbstractOutput . format ( result . max ( meter ) ) , AbstractOutput . format ( result . mean ( meter ) ) , AbstractOutput . format ( result . getStandardDeviation ( meter ) ) , new StringBuilder ( "[" ) . append ( AbstractOutput . format ( result . getConf05 ( meter ) ) ) . append ( "-" ) . append ( AbstractOutput . format ( result . getConf95 ( meter ) ) ) . append ( "]" ) . toString ( ) , AbstractOutput . format ( result . getResultSet ( meter ) . size ( ) ) } ) ; return input ; } | Generating the results for a given table . |
24,157 | private NiceTable generateHeader ( final NiceTable table ) { table . addHeader ( "Benchmark" ) ; table . addRow ( new String [ ] { "-" , "unit" , "sum" , "min" , "max" , "avg" , "stddev" , "conf95" , "runs" } ) ; return table ; } | Generating header for a given table . |
24,158 | public RestApi initialiseRestClient ( int logLevelNet , APIConfig . BaseURIs baseURIs ) { AuthManager authManager = new AuthManager ( ) { protected Observable < SessionData > restartSession ( ) { return reAuthenticate ( ) ; } } ; restClient = new RestClient ( new OkHttpAuthenticator ( authManager ) , logLevelNet , baseURIs . getService ( ) . toString ( ) ) ; service = restClient . getService ( ) ; setService ( service ) ; return service ; } | Initialise REST API client . |
24,159 | public Observable < ComapiResult < Void > > endSession ( ) { if ( isSessionValid ( ) ) { return wrapObservable ( sessionController . endSession ( ) . map ( mapToComapiResult ( ) ) ) ; } else { return Observable . just ( null ) ; } } | Ends currently active session . |
24,160 | public Observable < Pair < SessionData , ComapiResult < Void > > > updatePushToken ( ) { final SessionData session = dataMgr . getSessionDAO ( ) . session ( ) ; if ( isSessionValid ( session ) ) { return wrapObservable ( Observable . create ( ( Observable . OnSubscribe < String > ) sub -> { String token = dataMgr . getDeviceDAO ( ) . device ( ) . getPushToken ( ) ; if ( TextUtils . isEmpty ( token ) ) { token = pushMgr . getPushToken ( ) ; if ( ! TextUtils . isEmpty ( token ) ) { dataMgr . getDeviceDAO ( ) . setPushToken ( token ) ; } } sub . onNext ( token ) ; sub . onCompleted ( ) ; } ) . concatMap ( token -> sessionController . doUpdatePush ( session , token ) . map ( mapToComapiResult ( ) ) ) . map ( result -> new Pair < > ( session , result ) ) ) ; } else { return Observable . error ( getSessionStateErrorDescription ( ) ) ; } } | Gets an observable task for push token registration . Will emit FCM push token for provided senderId . |
24,161 | public Observable < ComapiResult < ConversationEventsResponse > > queryConversationEvents ( final String conversationId , final Long from , final Integer limit ) { final String token = getToken ( ) ; if ( sessionController . isCreatingSession ( ) ) { return getTaskQueue ( ) . queueQueryConversationEvents ( conversationId , from , limit ) ; } else if ( TextUtils . isEmpty ( token ) ) { return Observable . error ( getSessionStateErrorDescription ( ) ) ; } else { return doQueryConversationEvents ( token , conversationId , from , limit ) ; } } | Query conversation events . |
24,162 | public Observable < ComapiResult < Void > > isTyping ( final String conversationId ) { final String token = getToken ( ) ; if ( sessionController . isCreatingSession ( ) || TextUtils . isEmpty ( token ) ) { return Observable . error ( getSessionStateErrorDescription ( ) ) ; } else { return doIsTyping ( token , conversationId , true ) ; } } | Send user is typing . |
24,163 | private boolean isSessionValid ( final SessionData session ) { return ! sessionController . isCreatingSession ( ) && session != null && session . getSessionId ( ) != null && session . getAccessToken ( ) != null ; } | Is session successfully created . |
24,164 | < E > Observable < E > wrapObservable ( Observable < E > obs ) { return obs . subscribeOn ( Schedulers . io ( ) ) . observeOn ( Schedulers . io ( ) ) ; } | Sets schedulers for API calls observables . |
24,165 | private SortKey toggle ( SortKey key ) { if ( key . getSortOrder ( ) == SortOrder . ASCENDING ) { return new SortKey ( key . getColumn ( ) , SortOrder . DESCENDING ) ; } return new SortKey ( key . getColumn ( ) , SortOrder . ASCENDING ) ; } | Toggle the given key between ASCENDING and DESCENDING |
24,166 | private void init ( ) { TreeNode delegateRoot = null ; if ( delegate != null ) { delegateRoot = ( TreeNode ) delegate . getRoot ( ) ; } thisToDelegate . clear ( ) ; delegateToThis . clear ( ) ; if ( delegateRoot == null ) { root = null ; return ; } root = createNode ( delegateRoot ) ; } | Initialize this tree model |
24,167 | private FilteredTreeNode createNode ( final TreeNode delegateNode ) { FilteredTreeNode node = new FilteredTreeNode ( this , delegateNode ) ; delegateToThis . put ( delegateNode , node ) ; thisToDelegate . put ( node , delegateNode ) ; @ SuppressWarnings ( "unchecked" ) Enumeration < ? extends TreeNode > delegateChildren = delegateNode . children ( ) ; while ( delegateChildren . hasMoreElements ( ) ) { TreeNode delegateChild = delegateChildren . nextElement ( ) ; createNode ( delegateChild ) ; } return node ; } | Recursively create the node for the given delegate node and its children . |
24,168 | protected void fireTreeStructureChanged ( Object source , Object [ ] path , int [ ] childIndices , Object [ ] children ) { for ( TreeModelListener listener : treeModelListeners ) { listener . treeStructureChanged ( new TreeModelEvent ( source , path , childIndices , children ) ) ; } } | Fires a treeStructureChanged event |
24,169 | @ Bench ( runs = RUNS , beforeEachRun = "intArrayListAdd" ) public void intArrayListGet ( ) { for ( int i = 0 ; i < list . size ( ) ; i ++ ) { list . get ( i ) ; } } | bench for retrieving an element at a specified index |
24,170 | @ Bench ( runs = RUNS ) public void arrayListAdd ( ) { arrayList = new ArrayList < Integer > ( ) ; for ( final int i : intData ) { arrayList . add ( i ) ; } } | bench for adding data to the [ |
24,171 | @ Bench ( runs = RUNS ) public void vectorAdd ( ) { vector = new Vector < Integer > ( ) ; for ( final int i : intData ) { vector . add ( i ) ; } } | benchmark for adding data to [ |
24,172 | public boolean registerClasses ( final String ... classNames ) throws SocketViewException { try { benchmark = Perfidix . setUpBenchmark ( classNames , benchmark ) ; final Map < BenchmarkMethod , Integer > vals = benchmark . getNumberOfMethodsAndRuns ( ) ; return view . initProgressView ( vals ) ; } catch ( final ClassNotFoundException | PerfidixMethodCheckException e2 ) { return view . updateErrorInElement ( e2 . toString ( ) , e2 ) ; } } | Registering all classes and getting a mapping with the Methods and the corresponding overall runs |
24,173 | public boolean runBenchmark ( ) throws SocketViewException { final BenchmarkResult res = benchmark . run ( ) ; new TabularSummaryOutput ( ) . visitBenchmark ( res ) ; view . finished ( ) ; return true ; } | This method starts the bench progress with the registered classes . |
24,174 | public static void adjustColumnWidths ( JTable table , int maxWidth ) { final int safety = 20 ; for ( int c = 0 ; c < table . getColumnCount ( ) ; c ++ ) { TableColumn column = table . getColumnModel ( ) . getColumn ( c ) ; TableCellRenderer headerRenderer = column . getHeaderRenderer ( ) ; if ( headerRenderer == null ) { headerRenderer = table . getTableHeader ( ) . getDefaultRenderer ( ) ; } Component headerComponent = headerRenderer . getTableCellRendererComponent ( table , column . getHeaderValue ( ) , false , false , 0 , 0 ) ; int width = headerComponent . getPreferredSize ( ) . width ; for ( int r = 0 ; r < table . getRowCount ( ) ; r ++ ) { TableCellRenderer cellRenderer = table . getCellRenderer ( r , c ) ; Component cellComponent = cellRenderer . getTableCellRendererComponent ( table , table . getValueAt ( r , c ) , false , false , r , c ) ; Dimension d = cellComponent . getPreferredSize ( ) ; width = Math . max ( width , d . width ) ; } column . setPreferredWidth ( Math . min ( maxWidth , width + safety ) ) ; } } | Adjust the preferred widths of the columns of the given table depending on the contents of the cells and headers . |
24,175 | public static void scrollToRow ( JTable table , int row ) { Rectangle visibleRect = table . getVisibleRect ( ) ; Rectangle cellRect = table . getCellRect ( row , 0 , true ) ; Rectangle r = new Rectangle ( visibleRect . x , cellRect . y , visibleRect . width , cellRect . height ) ; table . scrollRectToVisible ( r ) ; } | Scroll the given table so that the specified row is visible . |
24,176 | public static Set < Integer > convertRowIndicesToView ( JTable table , Iterable < ? extends Integer > modelRows ) { Set < Integer > viewRows = new LinkedHashSet < Integer > ( ) ; for ( Integer modelRow : modelRows ) { int viewRow = table . convertRowIndexToView ( modelRow ) ; viewRows . add ( viewRow ) ; } return viewRows ; } | Convert all of the given model row indices to view row indices for the given table |
24,177 | public static Set < Integer > convertRowIndicesToModel ( JTable table , Iterable < ? extends Integer > viewRows ) { Set < Integer > modelRows = new LinkedHashSet < Integer > ( ) ; for ( Integer viewRow : viewRows ) { int modelRow = table . convertRowIndexToModel ( viewRow ) ; modelRows . add ( modelRow ) ; } return modelRows ; } | Convert all of the given view row indices to model row indices for the given table |
24,178 | private static void setDerivedFont ( JTable t , float size ) { t . setFont ( t . getFont ( ) . deriveFont ( size ) ) ; t . getTableHeader ( ) . setFont ( t . getTableHeader ( ) . getFont ( ) . deriveFont ( size ) ) ; } | Set a derived font with the given size for the given table and its header |
24,179 | private static double computeLuminance ( int argb ) { int r = ( argb >> 16 ) & 0xFF ; int g = ( argb >> 8 ) & 0xFF ; int b = ( argb ) & 0xFF ; double nr = Math . pow ( ( r / 255.0 ) , 2.2 ) ; double ng = Math . pow ( ( g / 255.0 ) , 2.2 ) ; double nb = Math . pow ( ( b / 255.0 ) , 2.2 ) ; double y = 0.2126 * nr + 0.7151 * ng + 0.0721 * nb ; return y ; } | Returns the luminance of the given ARGB color |
24,180 | public void log ( final String tag , final int logLevel , final String msg , final Throwable exception ) { if ( aConsole != null ) { aConsole . appendLog ( tag , logLevel , msg , exception ) ; } if ( aFile != null ) { aFile . appendLog ( tag , logLevel , msg , exception ) ; } } | Logs message using defined appender . |
24,181 | private void dispatchMessage ( PushMessageListener listener , RemoteMessage message ) { if ( listener != null ) { mainThreadHandler . post ( ( ) -> listener . onMessageReceived ( message ) ) ; } } | Dispatch received push message to external listener . |
24,182 | private OkHttpClient createOkHttpClient ( OkHttpAuthenticator authenticator , int logLevel ) { OkHttpClient . Builder builder = new OkHttpClient . Builder ( ) . addInterceptor ( loggingInterceptor ( logLevel ) ) . connectTimeout ( CONNECT_TIMEOUT , TimeUnit . SECONDS ) . writeTimeout ( WRITE_TIMEOUT , TimeUnit . SECONDS ) . readTimeout ( READ_TIMEOUT , TimeUnit . SECONDS ) . authenticator ( authenticator ) ; return builder . build ( ) ; } | Create and configure OkHTTP client . |
24,183 | private HttpLoggingInterceptor loggingInterceptor ( int logLevel ) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor ( ) ; switch ( logLevel ) { case LogLevelConst . DEBUG : interceptor . setLevel ( HttpLoggingInterceptor . Level . BODY ) ; break ; default : interceptor . setLevel ( HttpLoggingInterceptor . Level . NONE ) ; break ; } return interceptor ; } | Create and configure HTTP interceptor that will log the bodies of requests and responses . |
24,184 | private Gson createGson ( ) { GsonBuilder gsonBuilder = new GsonBuilder ( ) . disableHtmlEscaping ( ) . setLenient ( ) . addSerializationExclusionStrategy ( new ExclusionStrategy ( ) { public boolean shouldSkipField ( FieldAttributes f ) { return f . getAnnotation ( SerializedName . class ) == null ; } public boolean shouldSkipClass ( Class < ? > clazz ) { return false ; } } ) ; return gsonBuilder . create ( ) ; } | Create Gson converter for the service . |
24,185 | void initialise ( final Application application , CallbackAdapter adapter , Callback < ComapiClient > callback ) { this . adapter = adapter ; adapter . adapt ( super . initialise ( application , this , adapter ) , callback ) ; } | Initialise Comapi client instance . |
24,186 | boolean clearAll ( ) { SharedPreferences . Editor editor = sharedPreferences . edit ( ) ; Map < String , ? > all = sharedPreferences . getAll ( ) ; for ( String key : all . keySet ( ) ) { editor . remove ( key ) ; } return editor . commit ( ) ; } | Clear all entries in internal shared preferences file . |
24,187 | boolean clear ( String key ) { SharedPreferences . Editor editor = sharedPreferences . edit ( ) ; editor . remove ( key ) ; return editor . commit ( ) ; } | Clear entry . |
24,188 | public void addHeader ( final String title , final char mark , final Alignment orientation ) { final Header header = new Header ( title , mark , orientation , this ) ; rows . add ( header ) ; } | Adds a header row to the table . can be used to give a table some title . |
24,189 | public void addRow ( final String [ ] data ) { if ( anyStringContainsNewLine ( data ) ) { final String [ ] [ ] theMatrix = Util . createMatrix ( data ) ; for ( int i = 0 ; i < theMatrix . length ; i ++ ) { addRow ( theMatrix [ i ] ) ; } } else { final Row myRow = new Row ( this , data ) ; rows . add ( myRow ) ; } } | Adds a string row . checks that the strings added do not contain newlines because if so it has to split them in order to make them fit the row . |
24,190 | void updateColumnWidth ( final int index , final int newSize ) { columnLengths [ index ] = Math . max ( columnLengths [ index ] , newSize ) ; } | Performs an update on the column lengths . |
24,191 | private int getRowWidth ( ) { int returnVal = 1 ; if ( rows . size ( ) < 1 ) { returnVal = 0 ; } for ( int i = 0 ; i < rows . size ( ) ; i ++ ) { if ( rows . get ( i ) instanceof Row ) { returnVal = ( ( Row ) rows . get ( i ) ) . getRowWidth ( ) ; } } return returnVal ; } | Returns the row width . |
24,192 | private boolean anyStringContainsNewLine ( final String [ ] data ) { boolean returnVal = false ; for ( int i = 0 ; i < data . length ; i ++ ) { if ( Util . containsNewlines ( data [ i ] ) ) { returnVal = true ; } } return returnVal ; } | Tests whether any string contains a newline symbol . |
24,193 | public < T > T parse ( String text , Class < T > clazz ) { return gson . fromJson ( text , clazz ) ; } | Parse json to POJO . |
24,194 | public < T > T parse ( JsonObject obj , Class < T > clazz ) { return gson . fromJson ( obj , clazz ) ; } | Parse JsonObject to POJO . |
24,195 | public static int showValidatedTextInputDialog ( Window parent , String title , JComponent mainComponent , JTextComponent textComponent , Predicate < String > validInputPredicate ) { JButton okButton = new JButton ( "Ok" ) ; String text = textComponent . getText ( ) ; boolean valid = validInputPredicate . test ( text ) ; okButton . setEnabled ( valid ) ; JButton cancelButton = new JButton ( "Cancel" ) ; Object [ ] options = new Object [ ] { okButton , cancelButton } ; JOptionPane optionPane = new JOptionPane ( mainComponent , JOptionPane . PLAIN_MESSAGE , JOptionPane . OK_CANCEL_OPTION , null , options , okButton ) ; okButton . addActionListener ( e -> optionPane . setValue ( okButton ) ) ; cancelButton . addActionListener ( e -> optionPane . setValue ( cancelButton ) ) ; AncestorListener focussingAncestorListener = new AncestorListener ( ) { public void ancestorAdded ( AncestorEvent event ) { textComponent . requestFocus ( ) ; } public void ancestorRemoved ( AncestorEvent event ) { } public void ancestorMoved ( AncestorEvent event ) { } } ; textComponent . addAncestorListener ( focussingAncestorListener ) ; DocumentListener documentListener = new DocumentListener ( ) { public void insertUpdate ( DocumentEvent e ) { updateButtonState ( ) ; } public void removeUpdate ( DocumentEvent e ) { updateButtonState ( ) ; } public void changedUpdate ( DocumentEvent e ) { updateButtonState ( ) ; } protected void updateButtonState ( ) { String text = textComponent . getText ( ) ; boolean valid = validInputPredicate . test ( text ) ; okButton . setEnabled ( valid ) ; } } ; Document document = textComponent . getDocument ( ) ; document . addDocumentListener ( documentListener ) ; JDialog dialog = optionPane . createDialog ( parent , title ) ; dialog . pack ( ) ; dialog . setResizable ( true ) ; dialog . setVisible ( true ) ; document . removeDocumentListener ( documentListener ) ; textComponent . removeAncestorListener ( focussingAncestorListener ) ; Object selectedValue = optionPane . getValue ( ) ; if ( selectedValue == null ) { return JOptionPane . CLOSED_OPTION ; } return Arrays . asList ( options ) . indexOf ( selectedValue ) ; } | Create a new input dialog that performs validation . |
24,196 | private void handleOnResume ( Context context ) { if ( wasInBackground . get ( ) ) { startTime . set ( System . currentTimeMillis ( ) ) ; isApplicationForegrounded . set ( true ) ; listener . onForegrounded ( context ) ; } stopActivityTransitionTimer ( ) ; } | React to activity onResume event . |
24,197 | @ SuppressWarnings ( "resource" ) protected static final String format ( final double toFormat ) { return new Formatter ( Locale . US ) . format ( FLOATFORMAT , toFormat ) . toString ( ) ; } | Formats a double . |
24,198 | private void rollOverFiles ( ) { Context context = appContextRef . get ( ) ; if ( context != null ) { File dir = context . getFilesDir ( ) ; File mainFile = new File ( dir , name ( 1 ) ) ; if ( mainFile . exists ( ) ) { float fileSize = mainFile . length ( ) ; fileSize = fileSize / 1024.0f ; if ( fileSize > fileSizeLimitKb ) { File file ; File target ; file = new File ( dir , name ( maxFiles ) ) ; if ( file . exists ( ) ) { file . delete ( ) ; } for ( int i = maxFiles - 1 ; i > 0 ; i -- ) { file = new File ( dir , name ( i ) ) ; if ( file . exists ( ) ) { target = new File ( dir , name ( i + 1 ) ) ; file . renameTo ( target ) ; } } } } } } | Keep the maximum size of log files close to maximum value . Logs are cached if the size of the currently used log file exceeds max value . |
24,199 | private Observable < String > loadLogsObservable ( ) { return Observable . fromCallable ( ( ) -> { StringBuilder sb = new StringBuilder ( ) ; Context context = appContextRef . get ( ) ; if ( context != null ) { synchronized ( sharedLock ) { try { File dir = context . getFilesDir ( ) ; String line ; for ( int i = 1 ; i <= maxFiles ; i ++ ) { File file = new File ( dir , name ( i ) ) ; if ( file . exists ( ) ) { inputStream = new FileInputStream ( file ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; while ( ( line = reader . readLine ( ) ) != null ) { sb . append ( line ) . append ( '\n' ) ; } reader . close ( ) ; } } } catch ( Exception e ) { throw Exceptions . propagate ( e ) ; } finally { sharedLock . notifyAll ( ) ; } } } return sb . toString ( ) ; } ) ; } | Gets rx observable that reads the log files and appends to string . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.