idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
16,400
public void start ( ) { threadFactory = Executors . defaultThreadFactory ( ) ; disruptor = new Disruptor < > ( Registration . FACTORY , ringSize , threadFactory , ProducerType . MULTI , new BlockingWaitStrategy ( ) ) ; disruptor . handleEventsWith ( new ContainerEventHandler ( ) ) ; ringBuffer = disruptor . start ( ) ; }
Set up the disruptor service to have a single consumer which aggregates the data .
16,401
public String getMealDesc ( Date date ) { if ( ! date . before ( m_startTime ) ) if ( ! date . after ( m_endTime ) ) return m_strMeals ; return null ; }
Get the meal description on this date .
16,402
public static Date creditCardExpiryDate ( ) { DateTime dateTime = new DateTime ( ) ; DateTime addedMonths = dateTime . plusMonths ( JDefaultNumber . randomIntBetweenTwoNumbers ( 24 , 48 ) ) ; return addedMonths . dayOfMonth ( ) . withMaximumValue ( ) . toDate ( ) ; }
Typically Cards are good for 3 years . Will create a random date between 24 and 48 months
16,403
public static String creditCardNumber ( JDefaultCreditCardType type ) { String ccNumber = null ; switch ( type ) { case VISA : { StringBuffer tempCC = new StringBuffer ( "4" ) ; tempCC . append ( JDefaultNumber . randomNumberString ( 14 ) ) ; ccNumber = tempCC . append ( + generateCheckDigit ( tempCC . toString ( ) ) ) . toString ( ) ; break ; } case MASTERCARD : { StringBuffer tempCC = new StringBuffer ( "5" ) ; tempCC . append ( JDefaultNumber . randomIntBetweenTwoNumbers ( 1 , 5 ) ) ; tempCC . append ( JDefaultNumber . randomNumberString ( 13 ) ) ; ccNumber = tempCC . append ( + generateCheckDigit ( tempCC . toString ( ) ) ) . toString ( ) ; break ; } case AMEX : { StringBuffer tempCC = new StringBuffer ( "3" ) ; tempCC . append ( JDefaultNumber . randomIntBetweenTwoNumbers ( 4 , 7 ) ) ; tempCC . append ( JDefaultNumber . randomNumberString ( 12 ) ) ; ccNumber = tempCC . append ( + generateCheckDigit ( tempCC . toString ( ) ) ) . toString ( ) ; break ; } case DISCOVER : { StringBuffer tempCC = new StringBuffer ( "6011" ) ; tempCC . append ( JDefaultNumber . randomNumberString ( 11 ) ) ; ccNumber = tempCC . append ( + generateCheckDigit ( tempCC . toString ( ) ) ) . toString ( ) ; break ; } } return ccNumber ; }
Create a Credit Card number for different types of cards . The number that is generated can pass through a Luhn verification process since the proper check digit is calculated .
16,404
public static Double money ( int maxDollars ) { int dollars = RandomUtils . nextInt ( maxDollars + 1 ) ; int cents = RandomUtils . nextInt ( 100 ) ; Double d = new Double ( dollars + "." + cents ) ; return d ; }
Random dollar amount starting at zero
16,405
public T getAndSetReference ( final T newValue ) { _lock . writeLock ( ) . lock ( ) ; final T oldReference = _reference . getAndSet ( newValue ) ; _lock . writeLock ( ) . unlock ( ) ; return oldReference ; }
Replaces the held reference safely .
16,406
public Statement apply ( final Statement base , final Description description ) { if ( description . isSuite ( ) ) { return super . apply ( classStatement ( base ) , description ) ; } return super . apply ( statement ( base ) , description ) ; }
Verifies if the caller is a Suite and triggers the beforeClass and afterClass behavior .
16,407
public static ValidatorConfiguration createExperimental ( ) { Map < Check , Level > checks = getStandardChecks ( ) ; checks . put ( GdlArityCheck . INSTANCE , Level . ERROR ) ; checks . put ( GdlNotInRuleHeadCheck . INSTANCE , Level . ERROR ) ; checks . put ( UnrecognizedGdlArgumentCheck . INSTANCE , Level . WARNING ) ; checks . put ( GdlRandomGoalCheck . INSTANCE , Level . ERROR ) ; return new ValidatorConfiguration ( checks ) ; }
This validator includes support for the experimental GDL keyword and associated GDL variants .
16,408
private int getLogFileIndex ( String fileName ) { int fileIndex = 0 ; try { fileIndex = Integer . parseInt ( fileName . substring ( fileName . lastIndexOf ( COUNT_SEPARATOR ) + 1 ) ) ; } catch ( NumberFormatException e ) { e . printStackTrace ( ) ; } return fileIndex ; }
Get the log file index from the composed log file name .
16,409
private static < E extends Comparable < E > > void sort ( List < E > list , int start , int end , boolean descending ) { if ( start == end ) { return ; } int middle = ( start + end ) >> 1 ; Merge . sort ( list , start , middle , descending ) ; Merge . sort ( list , middle + 1 , end , descending ) ; if ( descending ) { Merge . mergeDescending ( list , start , middle , end ) ; } else { Merge . merge ( list , start , middle , end ) ; } }
Sort routine that recursively calls itself after splitting the original list in half . This routine is used for both ascending and descending sort since the work done is similar . The only difference is when calling the merge routine .
16,410
public static < E > ImmutableIterator < E > makeImmutable ( final Iterator < E > iterator ) { return new ImmutableIterator < E > ( ) { public boolean hasNext ( ) { return iterator . hasNext ( ) ; } public E next ( ) { return iterator . next ( ) ; } } ; }
Make an iterator immutable .
16,411
public void addFile ( File file ) throws IOException { if ( ! file . exists ( ) ) { throw new IllegalArgumentException ( String . format ( "File |%s| does not exist." , file ) ) ; } if ( file . isDirectory ( ) ) { throw new IllegalArgumentException ( String . format ( "File |%s| is a directory." , file ) ) ; } addFileEntry ( file . getPath ( ) , new FileInputStream ( file ) ) ; }
Inject file content into archive using file relative path as archive entry name . File to add is relative to a common base directory . All files from this archive should be part of that base directory hierarchy ; it is user code responsibility to enforce this constrain .
16,412
private void addFileEntry ( String entryName , InputStream inputStream ) throws IOException { if ( manifest != null ) { addManifestEntry ( ) ; } ZipEntry entry = new ZipEntry ( entryName ) ; filesArchive . putNextEntry ( entry ) ; inputStream = new BufferedInputStream ( inputStream ) ; try { byte [ ] buffer = new byte [ BUFFER_SIZE ] ; for ( ; ; ) { int bytesRead = inputStream . read ( buffer ) ; if ( bytesRead <= 0 ) { break ; } write ( buffer , 0 , bytesRead ) ; } } finally { Files . close ( inputStream ) ; filesArchive . closeEntry ( ) ; } }
Add file entry to this files archive . This method takes care to lazily write manifest just before first file entry .
16,413
public void free ( ) { if ( this . getContentPane ( ) . getComponentCount ( ) > 0 ) if ( this . getContentPane ( ) . getComponent ( 0 ) instanceof BaseApplet ) ( ( BaseApplet ) this . getContentPane ( ) . getComponent ( 0 ) ) . free ( ) ; this . dispose ( ) ; }
Close this frame and free the baseApplet .
16,414
protected void dispose ( ) { try { if ( generator != null ) { generator . writeEndArray ( ) ; generator . close ( ) ; } this . getOutputStream ( ) . close ( ) ; } catch ( IOException ioe ) { logger . error ( "Unable to close stream" , ioe ) ; logger . trace ( ioe . getMessage ( ) , ioe ) ; } finally { generator = null ; this . setOutputStream ( null ) ; } }
Closes the output stream .
16,415
public boolean parseNextLine ( ) { if ( firstTime ) { firstTime = false ; try { XMLReader parser = org . xml . sax . helpers . XMLReaderFactory . createXMLReader ( ) ; parser . setContentHandler ( m_handler ) ; parser . parse ( new InputSource ( m_reader ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( SAXException e ) { e . printStackTrace ( ) ; } m_record . close ( ) ; } try { return m_record . hasNext ( ) ; } catch ( DBException e ) { e . printStackTrace ( ) ; } return false ; }
Parse the next line and return false at EOF .
16,416
public void free ( ) { if ( this . getTargetScreen ( JBaseFrame . class ) != null ) ( ( JBaseFrame ) this . getTargetScreen ( JBaseFrame . class ) ) . setTitle ( null ) ; this . freeSubComponents ( this ) ; }
Free the resources held by this object . This method calls freeSubComponents for this .
16,417
public static Component getSubScreen ( Container container , Class < ? > targetClass ) { for ( int i = container . getComponentCount ( ) - 1 ; i >= 0 ; i -- ) { Component component = container . getComponent ( i ) ; if ( targetClass . isAssignableFrom ( component . getClass ( ) ) ) return component ; if ( component instanceof Container ) { component = JBasePanel . getSubScreen ( ( Container ) component , targetClass ) ; if ( component != null ) return component ; } } return null ; }
Climb down through the panel hierarchy until you find a component of this class .
16,418
public Component getComponentByName ( String strName , Container parent ) { for ( int i = 0 ; i < parent . getComponentCount ( ) ; i ++ ) { Component component = parent . getComponent ( i ) ; if ( strName . equals ( component . getName ( ) ) ) return component ; if ( component instanceof Container ) { component = this . getComponentByName ( strName , ( Container ) component ) ; if ( component != null ) return component ; } } return null ; }
Get the sub - component with this name .
16,419
public JPanel addScrollbars ( JComponent screen ) { Dimension dimension = screen . getPreferredSize ( ) ; if ( ( dimension . height == 0 ) && ( dimension . width == 0 ) ) dimension = JScreenConstants . PREFERRED_SCREEN_SIZE ; else if ( ( screen . getBounds ( ) . width != 0 ) && ( screen . getBounds ( ) . height != 0 ) ) { dimension . width = screen . getBounds ( ) . width ; dimension . height = screen . getBounds ( ) . height ; } dimension . width = Math . max ( JScreenConstants . MIN_SCREEN_SIZE . width , Math . min ( dimension . width + 20 , JScreenConstants . PREFERRED_SCREEN_SIZE . width ) ) ; dimension . height = Math . max ( JScreenConstants . MIN_SCREEN_SIZE . height , Math . min ( dimension . height + 20 , JScreenConstants . PREFERRED_SCREEN_SIZE . height ) ) ; JScrollPane scrollpane = new JScrollPane ( ScrollPaneConstants . VERTICAL_SCROLLBAR_AS_NEEDED , ScrollPaneConstants . HORIZONTAL_SCROLLBAR_AS_NEEDED ) ; if ( dimension != null ) scrollpane . setPreferredSize ( dimension ) ; scrollpane . setAlignmentX ( Component . LEFT_ALIGNMENT ) ; scrollpane . getViewport ( ) . add ( screen ) ; JPanel panel = new JPanel ( ) ; panel . setAlignmentX ( Component . LEFT_ALIGNMENT ) ; panel . add ( scrollpane ) ; panel . setLayout ( new BoxLayout ( panel , BoxLayout . Y_AXIS ) ) ; panel . setOpaque ( false ) ; screen . setOpaque ( false ) ; scrollpane . setOpaque ( false ) ; scrollpane . getViewport ( ) . setOpaque ( false ) ; return panel ; }
Add a scrollpane to this component and return the component with the scroller and this screen in it .
16,420
public JBasePanel getToolbarParent ( ) { JBasePanel parent = ( JBasePanel ) this . getTargetScreen ( JBasePanel . class ) ; if ( parent == null ) if ( m_parent instanceof JBasePanel ) parent = ( JBasePanel ) m_parent ; if ( parent == null ) return this ; return parent . getToolbarParent ( ) ; }
Get the highest level parent that is a JBasePanel . This is where a toolbar or menubar should be added .
16,421
public JPanel addToolbar ( JComponent screen , JComponent toolbar ) { JPanel panelMain = new JPanel ( ) ; panelMain . setOpaque ( false ) ; panelMain . setLayout ( new BoxLayout ( panelMain , BoxLayout . Y_AXIS ) ) ; panelMain . add ( toolbar ) ; toolbar . setAlignmentX ( 0 ) ; panelMain . add ( screen ) ; screen . setAlignmentX ( 0 ) ; return panelMain ; }
Add this toolbar to this panel and return the new main panel .
16,422
public void set ( BridgeFactory factory ) { if ( factory . getNearType ( ) != nearType ) { throw new IllegalArgumentException ( "Type mismatch: " + nearType + ": " + factory . getNearType ( ) ) ; } factorySetting . set ( factory ) ; }
Sets the bridge factory to use with this accessor . The near type of the given bridge factory has to match the near type of this bridge accessor .
16,423
public BridgeFactory get ( ) { BridgeFactory result ; try { result = factorySetting . get ( ) ; } catch ( RuntimeException exception ) { RuntimeException wrapper = new IllegalStateException ( "Missing factory for: " + display ( nearType ) , exception ) ; logger . trace ( "Stack trace" , wrapper ) ; throw wrapper ; } return result ; }
Returns the bridge factory for this accessor .
16,424
public NT getNearObject ( Object farObject ) { return nearType . cast ( factorySetting . get ( ) . getNearObject ( farObject ) ) ; }
Returns the near object that corresponds to the given far object . The types must match the bridge factory associated with this accessor and the bridge factory must be set .
16,425
public static MethodInvocation start ( String objectName , String methodName , int lineNumber ) { bigMessage ( "Starting profiling... " + objectName + "#" + methodName + " (" + lineNumber + ")" ) ; if ( profiling ( ) ) { logger . error ( "Profiling was already started for '{}'" , callstack . getFirst ( ) . getCls ( ) + "#" + callstack . getFirst ( ) . getMethod ( ) ) ; throw new IllegalStateException ( ) ; } MethodDescriptor methodDescriptor = new MethodDescriptor ( objectName , methodName , lineNumber ) ; MethodInvocation rootInvocation = new MethodInvocation ( methodDescriptor ) ; invocations . add ( rootInvocation ) ; callstack . add ( rootInvocation ) ; Agent . setRootInvocation ( rootInvocation ) ; return rootInvocation ; }
the first invocation for this profiling session .
16,426
public Record getMainRecord ( ) { Record record = super . getMainRecord ( ) ; if ( record == null ) if ( m_sessionObjectParent != null ) record = ( ( BaseSession ) m_sessionObjectParent ) . getMainRecord ( ) ; return record ; }
Get the main record for this session .
16,427
public Record getScreenRecord ( ) { Record record = super . getScreenRecord ( ) ; if ( record == null ) if ( m_sessionObjectParent != null ) record = ( ( BaseSession ) m_sessionObjectParent ) . getScreenRecord ( ) ; return record ; }
Get the screen query .
16,428
public Record setRecordCurrent ( ) { Record recordMain = this . getMainRecord ( ) ; try { if ( recordMain != null ) { if ( m_objectID != null ) { if ( recordMain . setHandle ( m_objectID , DBConstants . BOOKMARK_HANDLE ) != null ) recordMain . edit ( ) ; else m_objectID = null ; } if ( m_objectID == null ) if ( ( recordMain . getEditMode ( ) != DBConstants . EDIT_CURRENT ) && ( recordMain . getEditMode ( ) != DBConstants . EDIT_IN_PROGRESS ) ) { recordMain . addNew ( ) ; } } } catch ( DBException ex ) { Debug . print ( ex ) ; ex . printStackTrace ( ) ; m_objectID = null ; } if ( m_objectID == null ) return null ; else return recordMain ; }
Set the record to the bookmark passed in .
16,429
public void addSessionObject ( BaseSession sessionObject ) { if ( sessionObject == null ) return ; if ( m_vSessionObjectList == null ) m_vSessionObjectList = new Vector < BaseSession > ( ) ; m_vSessionObjectList . addElement ( sessionObject ) ; }
Add this sub - session to this session .
16,430
public boolean removeSessionObject ( BaseSession sessionObject ) { if ( m_vSessionObjectList == null ) return false ; boolean bFlag = m_vSessionObjectList . removeElement ( sessionObject ) ; return bFlag ; }
Remove this sub - session from this session .
16,431
public BaseSession getSessionObjectAt ( int iIndex ) { if ( m_vSessionObjectList == null ) return null ; return ( BaseSession ) m_vSessionObjectList . elementAt ( iIndex ) ; }
Get the sub - session at this location .
16,432
public Map < String , Object > getFieldData ( Map < String , Object > properties ) { Map < String , Object > propReturn = null ; if ( properties != null ) { propReturn = new Hashtable < String , Object > ( ) ; for ( int i = 1 ; ; i ++ ) { String strFieldNumber = DBParams . FIELD + Integer . toString ( i ) ; String strFieldName = ( String ) properties . get ( strFieldNumber ) ; if ( strFieldName == null ) break ; Record record = this . getMainRecord ( ) ; if ( strFieldName . indexOf ( '.' ) != - 1 ) { record = this . getRecord ( strFieldName . substring ( 0 , strFieldName . indexOf ( '.' ) ) ) ; strFieldName = strFieldName . substring ( strFieldName . indexOf ( '.' ) + 1 ) ; } BaseField field = null ; if ( record != null ) field = record . getField ( strFieldName ) ; if ( field != null ) propReturn . put ( strFieldNumber , field . getData ( ) ) ; } } return propReturn ; }
GetFieldData Method .
16,433
public DatabaseSession getDatabaseSession ( BaseDatabase database ) { for ( int iFieldSeq = 0 ; iFieldSeq < this . getSessionObjectCount ( ) ; iFieldSeq ++ ) { if ( this . getSessionObjectAt ( iFieldSeq ) . getDatabaseSession ( database ) != null ) return this . getSessionObjectAt ( iFieldSeq ) . getDatabaseSession ( database ) ; } return null ; }
If this database is in my database list return this object .
16,434
public NodeData mySingleClick ( int selRow , TreePath selPath ) { Object [ ] x = selPath . getPath ( ) ; DynamicTreeNode nodeCurrent = ( DynamicTreeNode ) x [ x . length - 1 ] ; NodeData data = ( NodeData ) nodeCurrent . getUserObject ( ) ; String strDescription = data . toString ( ) ; String strID = data . getID ( ) ; String strRecord = data . getRecordName ( ) ; this . firePropertyChange ( m_strLocationRecordParam , null , strRecord ) ; this . firePropertyChange ( m_strLocationIDParam , null , strID ) ; this . firePropertyChange ( m_strLocationParam , null , strDescription ) ; return data ; }
User selected item .
16,435
public void run ( ) { Record record = this . getMainRecord ( ) ; String strFileName = this . getProperty ( "filename" ) ; String strImport = this . getProperty ( "import" ) ; if ( strFileName == null ) strFileName = strImport ; String strExport = this . getProperty ( "export" ) ; if ( strFileName == null ) strFileName = strExport ; m_bOverwriteDups = false ; if ( ( DBConstants . TRUE . equalsIgnoreCase ( this . getProperty ( "overwritedups" ) ) ) || ( DBConstants . YES . equalsIgnoreCase ( this . getProperty ( "overwritedups" ) ) ) ) m_bOverwriteDups = true ; boolean bSuccess = false ; if ( strImport != null ) bSuccess = this . importXML ( record . getTable ( ) , strFileName , null ) ; else bSuccess = this . exportXML ( record . getTable ( ) , strFileName ) ; if ( ! bSuccess ) System . exit ( 1 ) ; }
Run this process given the parameters passed in on initialization .
16,436
public boolean importXML ( BaseTable table , String filename , InputStream inStream ) { Record record = table . getRecord ( ) ; XmlInOut . enableAllBehaviors ( record , false , false ) ; DocumentBuilder db = Utility . getDocumentBuilder ( ) ; DocumentBuilder stringdb = Utility . getDocumentBuilder ( ) ; Document doc = null ; try { synchronized ( db ) { if ( inStream != null ) doc = db . parse ( inStream ) ; else doc = db . parse ( new File ( filename ) ) ; } } catch ( FileNotFoundException e ) { Utility . getLogger ( ) . info ( "Table input file not found: " + filename ) ; return false ; } catch ( SAXException e ) { Debug . print ( e ) ; return false ; } catch ( IOException e ) { Debug . print ( e ) ; return false ; } catch ( Exception e ) { Debug . print ( e ) ; return false ; } try { String databaseName = null ; int iEndDB = filename . lastIndexOf ( System . getProperty ( "file.separator" , "/" ) ) ; if ( iEndDB == - 1 ) iEndDB = filename . lastIndexOf ( '/' ) ; if ( iEndDB != - 1 ) { int iStartDB = filename . lastIndexOf ( System . getProperty ( "file.separator" , "/" ) , iEndDB - 1 ) ; if ( iStartDB == - 1 ) iStartDB = filename . lastIndexOf ( '/' , iEndDB - 1 ) ; iStartDB ++ ; databaseName = filename . substring ( iStartDB , iEndDB ) ; } if ( record == null ) this . parseXSL ( ) ; Element elParent = doc . getDocumentElement ( ) ; RecordParser parser = new RecordParser ( elParent ) ; while ( parser . next ( stringdb ) != null ) { Node elChild = parser . getChildNode ( ) ; String strName = parser . getName ( ) ; this . parseRecord ( stringdb , ( Element ) elChild , strName , databaseName , table , null , false ) ; } } catch ( Throwable t ) { t . printStackTrace ( ) ; return false ; } XmlInOut . enableAllBehaviors ( record , true , true ) ; return true ; }
Parses this XML text and place it in new records .
16,437
public static void enableAllBehaviors ( Record record , boolean bEnableRecordBehaviors , boolean bEnableFieldBehaviors ) { if ( record == null ) return ; record . setEnableListeners ( bEnableRecordBehaviors ) ; for ( int iFieldSeq = 0 ; iFieldSeq < record . getFieldCount ( ) ; iFieldSeq ++ ) { BaseField field = record . getField ( iFieldSeq ) ; field . setEnableListeners ( bEnableFieldBehaviors ) ; } }
Enable or disable all the behaviors .
16,438
public boolean directoryContainsFiles ( File fileDir ) { boolean containsFiles = false ; File [ ] files = fileDir . listFiles ( ) ; if ( files != null ) { for ( File file : files ) { if ( ! file . isDirectory ( ) ) containsFiles = true ; } } return containsFiles ; }
Get the projectID if this directory has any files in it . Otherwise return 0 meaning I don t have to specify this package .
16,439
public double getColorPercentage ( Color color ) { if ( color == null ) return 0 ; else { Integer num = colors . get ( colorKey ( color ) ) ; if ( num == null ) num = 0 ; if ( totalLength == 0 ) return 0 ; else return ( double ) num / totalLength ; } }
Obtains the percentage of the text that has the given color .
16,440
public double getColorPercentage ( Area node ) { int tlen = 0 ; double sum = 0 ; for ( Box box : node . getBoxes ( ) ) { int len = letterLength ( box . getText ( ) ) ; if ( len > 0 ) { sum += getColorPercentage ( box . getColor ( ) ) * len ; tlen += len ; } } for ( int i = 0 ; i < node . getChildCount ( ) ; i ++ ) { Area child = node . getChildAt ( i ) ; int nlen = letterLength ( child . getText ( ) ) ; tlen += nlen ; sum += getColorPercentage ( child ) * nlen ; } if ( tlen == 0 ) return 0 ; else return sum / tlen ; }
Obtains the average percentage of all the text that has the given color .
16,441
public void set ( final String originalKey , final Object object ) { final String key = applicationName + "." + originalKey ; if ( object == null || ( object instanceof String && ( ( String ) object ) . length ( ) == 0 ) ) { application . setConfig ( application . getConfig ( ) . withoutPath ( key ) ) ; } else { ConfigValue value = ConfigValueFactory . fromAnyRef ( object , "modified at runtime " ) ; application . setConfig ( application . getConfig ( ) . withValue ( key , value ) ) ; } config = application . getConfig ( ) . withFallback ( user . getConfig ( ) ) . withFallback ( system . getConfig ( ) ) ; }
will throw exception if key is not found
16,442
void loadConfigs ( ) throws IOException { application . loadConfig ( ) ; user . loadConfig ( ) ; system . loadConfig ( ) ; config = application . getConfig ( ) . withFallback ( user . getConfig ( ) ) . withFallback ( system . getConfig ( ) ) ; dump2debugLog ( "MERGED" , config ) ; }
THE BIG LOAD AND MERGE
16,443
static void dumpConfig ( final String name , final Config config , final PrintWriter printWriter ) { if ( printWriter == null ) { throw new IllegalArgumentException ( "writer argument cannot be null" ) ; } printWriter . println ( ) ; printWriter . println ( "^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^" ) ; printWriter . println ( name + " " + config . root ( ) . origin ( ) ) ; printWriter . println ( config . root ( ) . render ( configRenderOptions ) ) ; printWriter . flush ( ) ; }
end of class ConfigSource
16,444
private static String reader2String ( final Reader reader ) throws IOException { final StringBuilder stringBuilder = new StringBuilder ( ) ; try ( BufferedReader bufferedReader = new BufferedReader ( reader ) ) { String line = null ; while ( ( line = bufferedReader . readLine ( ) ) != null ) { stringBuilder . append ( line ) ; stringBuilder . append ( "\n" ) ; } } return stringBuilder . toString ( ) ; }
convert Reader to String
16,445
public void init ( DatabaseOwner databaseOwner , String strDbName , int iDatabaseType , Map < String , Object > properties ) { super . init ( databaseOwner , strDbName , iDatabaseType , properties ) ; this . setProperty ( SQLParams . EDIT_DB_PROPERTY , SQLParams . DB_EDIT_NOT_SUPPORTED ) ; m_bAutosequenceSupport = false ; this . setProperty ( DBParams . MESSAGES_TO_REMOTE , DBConstants . TRUE ) ; this . setProperty ( DBParams . CREATE_REMOTE_FILTER , DBConstants . TRUE ) ; this . setProperty ( DBParams . UPDATE_REMOTE_FILTER , DBConstants . TRUE ) ; }
Initialize this database and add it to the databaseOwner .
16,446
public String fixDatabaseProductName ( String strDatabaseProductName ) { if ( strDatabaseProductName == null ) return null ; if ( strDatabaseProductName . lastIndexOf ( ' ' ) != - 1 ) strDatabaseProductName = strDatabaseProductName . substring ( strDatabaseProductName . lastIndexOf ( ' ' ) + 1 ) ; return strDatabaseProductName . toLowerCase ( ) ; }
Fix the database product name .
16,447
public void close ( ) { super . close ( ) ; try { if ( m_JDBCConnection != null ) m_JDBCConnection . close ( ) ; } catch ( SQLException ex ) { } m_JDBCConnection = null ; }
Close the physical database .
16,448
public void initConnection ( ) { try { boolean bAutoCommit = true ; if ( DBConstants . FALSE . equalsIgnoreCase ( this . getProperty ( SQLParams . AUTO_COMMIT_PARAM ) ) ) bAutoCommit = false ; m_JDBCConnection . setAutoCommit ( bAutoCommit ) ; DatabaseMetaData dma = m_JDBCConnection . getMetaData ( ) ; String strDatabaseProductName = dma . getDatabaseProductName ( ) ; Utility . getLogger ( ) . info ( "DB Name: " + strDatabaseProductName ) ; this . setProperty ( SQLParams . INTERNAL_DB_NAME , strDatabaseProductName ) ; this . setupDatabaseProperties ( ) ; String strDateQuote = this . getProperty ( SQLParams . SQL_DATE_QUOTE ) ; if ( ( strDateQuote != null ) && ( strDateQuote . length ( ) > 0 ) ) DateTimeField . setSQLQuote ( strDateQuote . charAt ( 0 ) ) ; Converter . initGlobals ( ) ; String strFormat = this . getProperty ( SQLParams . SQL_DATE_FORMAT ) ; if ( strFormat != null ) Converter . gDateSqlFormat = new java . text . SimpleDateFormat ( strFormat ) ; strFormat = this . getProperty ( SQLParams . SQL_TIME_FORMAT ) ; if ( strFormat != null ) Converter . gTimeSqlFormat = new java . text . SimpleDateFormat ( strFormat ) ; strFormat = this . getProperty ( SQLParams . SQL_DATETIME_FORMAT ) ; if ( strFormat != null ) Converter . gDateTimeSqlFormat = new java . text . SimpleDateFormat ( strFormat ) ; if ( DBConstants . TRUE . equals ( this . getProperty ( SQLParams . SHARE_JDBC_CONNECTION ) ) ) m_sharedConnection = m_JDBCConnection ; Utility . getLogger ( ) . info ( "Connected to db: " + this . getDatabaseName ( true ) ) ; } catch ( SQLException ex ) { } }
Setup the new connection .
16,449
public boolean create ( String strDatabaseName ) throws DBException { try { String strDBName = this . getProperty ( SQLParams . INTERNAL_DB_NAME ) ; int iDatabaseType = DBConstants . SYSTEM_DATABASE ; DatabaseOwner env = this . getDatabaseOwner ( ) ; JdbcDatabase db = ( JdbcDatabase ) env . getDatabase ( strDBName , iDatabaseType , null ) ; Statement queryStatement = db . getJDBCConnection ( ) . createStatement ( ) ; String strSQL = "create database " + strDatabaseName + ";" ; queryStatement . execute ( strSQL ) ; queryStatement . close ( ) ; db . free ( ) ; String oldValue = this . getProperty ( DBConstants . CREATE_DB_IF_NOT_FOUND ) ; this . setProperty ( DBConstants . CREATE_DB_IF_NOT_FOUND , DBConstants . FALSE ) ; this . close ( ) ; this . setupDBConnection ( ) ; this . setProperty ( DBConstants . CREATE_DB_IF_NOT_FOUND , oldValue ) ; if ( this . getProperty ( DBConstants . LOAD_INITIAL_DATA ) != null ) if ( ( this . getDatabaseType ( ) & ( DBConstants . SHARED_DATA | DBConstants . USER_DATA ) ) == DBConstants . SHARED_DATA ) { DatabaseInfo recDatabaseInfo = new DatabaseInfo ( ) ; try { recDatabaseInfo . setDatabaseName ( this . getDatabaseName ( false ) ) ; recDatabaseInfo . setTable ( this . doMakeTable ( recDatabaseInfo ) ) ; recDatabaseInfo . init ( null ) ; } catch ( Exception ex ) { } finally { recDatabaseInfo . free ( ) ; } } return true ; } catch ( SQLException ex ) { ex . printStackTrace ( ) ; } return super . create ( strDatabaseName ) ; }
Create a new empty database using the definition in the record .
16,450
public void addDatabaseProperty ( String strKey , String strValue ) { this . setProperty ( strKey , strValue ) ; Environment env = ( Environment ) this . getDatabaseOwner ( ) . getEnvironment ( ) ; if ( env . getCachedDatabaseProperties ( this . getDatabaseName ( true ) ) != null ) if ( env . getCachedDatabaseProperties ( this . getDatabaseName ( true ) ) != Environment . DATABASE_DOESNT_EXIST ) env . getCachedDatabaseProperties ( this . getDatabaseName ( true ) ) . put ( strKey , strValue ) ; }
Add this database property .
16,451
public void clearBookmarkFilters ( String strKeyName , Object objKeyData ) { Map < String , Object > properties = new Hashtable < String , Object > ( ) ; properties . put ( GridRecordMessageFilter . ADD_BOOKMARK , GridRecordMessageFilter . CLEAR_BOOKMARKS ) ; if ( objKeyData != null ) { properties . put ( GridRecordMessageFilter . SECOND_KEY_HINT , strKeyName ) ; properties . put ( strKeyName , objKeyData ) ; } m_recordMessageFilter . updateFilterMap ( properties ) ; }
Update the listener to listen for changes to no records .
16,452
public synchronized void transmit ( Object o , ReceiverQueue t ) { if ( ! closed ) { ArrayList < Receiver > toBeRemoved = new ArrayList < Receiver > ( ) ; for ( Receiver r : receivers ) { if ( r instanceof ReceiverQueue && ( ( ReceiverQueue ) r ) . isClosed ( ) ) { toBeRemoved . add ( r ) ; } else { if ( echo || r != t ) { r . onReceive ( o ) ; } } } for ( Receiver r : toBeRemoved ) { receivers . remove ( r ) ; } } }
Dispatches an object to all connected receivers .
16,453
public ReceiverQueue createReceiver ( int limit ) { synchronized ( receivers ) { ReceiverQueue q = null ; if ( ! closed && ( maxNrofReceivers == 0 || receivers . size ( ) < maxNrofReceivers ) ) { q = new ReceiverQueue ( limit ) ; receivers . add ( q ) ; } return q ; } }
Creates a receiver for this channel .
16,454
public Receiver registerReceiver ( Receiver receiver ) { synchronized ( receivers ) { if ( ! closed && ( maxNrofReceivers == 0 || receivers . size ( ) < maxNrofReceivers ) ) { receivers . add ( receiver ) ; } else { return null ; } return receiver ; } }
Adds a receiver so that it will receive transmitted messages .
16,455
public void close ( ) { synchronized ( receivers ) { Iterator i = receivers . iterator ( ) ; while ( i . hasNext ( ) ) { ReceiverQueue r = ( ReceiverQueue ) i . next ( ) ; r . onTransmissionClose ( ) ; } closed = true ; receivers . clear ( ) ; } }
Closes the channel and all receivers .
16,456
public void free ( ) { if ( m_messageMap != null ) { for ( BaseMessageQueue messageQueue : m_messageMap . values ( ) ) { if ( messageQueue != null ) { messageQueue . setMessageManager ( null ) ; messageQueue . free ( ) ; } } } m_messageMap = null ; super . free ( ) ; }
Free this message manager .
16,457
public int addMessageFilter ( MessageFilter messageFilter ) { MessageReceiver receiver = this . getMessageQueue ( messageFilter . getQueueName ( ) , messageFilter . getQueueType ( ) ) . getMessageReceiver ( ) ; receiver . addMessageFilter ( messageFilter ) ; return Constant . NORMAL_RETURN ; }
Add this message filter to the appropriate queue . The message filter contains the queue name and type and a listener to send the message to .
16,458
public int sendMessage ( Message message ) { BaseMessageHeader messageHeader = ( ( BaseMessage ) message ) . getMessageHeader ( ) ; String strQueueType = messageHeader . getQueueType ( ) ; String strQueueName = messageHeader . getQueueName ( ) ; MessageSender sender = this . getMessageQueue ( strQueueName , strQueueType ) . getMessageSender ( ) ; if ( sender != null ) sender . sendMessage ( message ) ; else return Constant . ERROR_RETURN ; return Constant . NORMAL_RETURN ; }
Send this message to the appropriate queue . The message s message header has the queue name and type .
16,459
void updateExceptionStatement ( PreparedStatement exceptionStatement , String txt , short i , long eventId ) throws SQLException { exceptionStatement . setLong ( 1 , eventId ) ; exceptionStatement . setShort ( 2 , i ) ; exceptionStatement . setString ( 3 , txt ) ; if ( cnxSupportsBatchUpdates ) { exceptionStatement . addBatch ( ) ; } else { exceptionStatement . execute ( ) ; } }
Add an exception statement either as a batch or execute immediately if batch updates are not supported .
16,460
public String addScreenParams ( BasePanel screen , String strURL ) { int iNumCols = screen . getSFieldCount ( ) ; for ( int iIndex = 0 ; iIndex < iNumCols ; iIndex ++ ) { ScreenField sField = screen . getSField ( iIndex ) ; boolean bPrintControl = true ; if ( sField instanceof BasePanel ) { strURL = this . addScreenParams ( ( BasePanel ) sField , strURL ) ; bPrintControl = false ; } if ( sField . getConverter ( ) == null ) bPrintControl = false ; if ( screen == this ) bPrintControl = false ; if ( ! sField . isInputField ( ) ) bPrintControl = false ; if ( ! sField . isEnabled ( ) ) bPrintControl = false ; if ( bPrintControl ) if ( sField . getScreenFieldView ( ) != null ) { String strData = sField . getSFieldValue ( false , false ) ; strURL = Utility . addURLParam ( strURL , sField . getSFieldParam ( null , false ) , strData ) ; } } return strURL ; }
Display this screen in html input format . returns true if default params were found for this form .
16,461
public void execute ( String query , Object ... params ) throws SQLException { createPreparedStatement ( query , 0 , params ) . execute ( ) ; }
Executes SQL query which returns nothing .
16,462
public < T > List < T > getList ( String query , Class < T > entityClass , Object ... params ) throws SQLException , NoSuchFieldException , InstantiationException , IllegalAccessException { Cursor < T > cursor = getCursor ( query , entityClass , params ) ; return cursor . fetchList ( ) ; }
Executes SQL query which returns list of entities .
16,463
public < T > T getSingle ( String query , Class < T > entityClass , Object ... params ) throws SQLException , NoSuchFieldException , InstantiationException , IllegalAccessException { Cursor < T > cursor = getCursor ( query , entityClass , params ) ; return cursor . fetchSingle ( ) ; }
Executes SQL query which returns single entity .
16,464
public < T > T getSingleOrNull ( String query , Class < T > entityClass , Object ... params ) throws SQLException , NoSuchFieldException , InstantiationException , IllegalAccessException { Cursor < T > cursor = getCursor ( query , entityClass , params ) ; return cursor . fetchSingleOrNull ( ) ; }
Executes SQL query which returns single entity or null if result is not there .
16,465
public String getHeaderValue ( String name ) { if ( headers == null ) { return null ; } return headers . get ( name ) ; }
Gets value of specified HTTP response header .
16,466
public ValidationResult < ? > validate ( final BCryptUsernameAndPassword existingSingleUser , final UsernameAndPassword defaultLogin ) { if ( passwordRedacted ) { return new ValidationResult < > ( true ) ; } final boolean valid = defaultLogin . getPassword ( ) != null ? currentPassword . equals ( defaultLogin . getPassword ( ) ) : BCrypt . checkpw ( currentPassword , existingSingleUser . hashedPassword ) ; return valid ? new ValidationResult < > ( true ) : new ValidationResult < > ( false , "The current password is incorrect" ) ; }
Validates this component by comparing the current password against either a default login or an existing single user
16,467
public int getMessageLength ( ) { int messageLength = 1 + 4 ; messageLength += 4 ; if ( this . identifierRegex != null ) { try { messageLength += this . identifierRegex . getBytes ( "UTF-16BE" ) . length ; } catch ( UnsupportedEncodingException e ) { log . error ( "Unable to encode String into UTF-16." ) ; e . printStackTrace ( ) ; } } messageLength += 4 ; if ( this . attributeRegexes != null ) { for ( String attrib : this . attributeRegexes ) { messageLength += 4 ; try { messageLength += attrib . getBytes ( "UTF-16BE" ) . length ; } catch ( UnsupportedEncodingException e ) { log . error ( "Unable to encode String into uTF-16" ) ; e . printStackTrace ( ) ; } } } messageLength += 16 ; return messageLength ; }
Returns the length of the message in bytes excluding the message length prefix value .
16,468
public void addComponent ( Object screenField ) { this . setEnableTranslation ( false ) ; super . addComponent ( screenField ) ; this . setEnableTranslation ( true ) ; for ( int iIndex = 0 ; ; iIndex ++ ) { Converter converter = this . getConverterToPass ( iIndex ) ; if ( converter == null ) break ; converter . addComponent ( screenField ) ; } }
Add this component to the components displaying this field . Make sure all the converter have this screenfield on their list .
16,469
public Converter getNextConverter ( ) { if ( ( m_bEnableTranslation == true ) && ( this . getConverterToPass ( m_bSetData ) != null ) ) return this . getConverterToPass ( m_bSetData ) ; else return super . getNextConverter ( ) ; }
Get the next Converter in the chain .
16,470
public Converter getConverterToPass ( int iIndex ) { if ( iIndex == - 1 ) return super . getNextConverter ( ) ; if ( m_vconvDependent != null ) { if ( iIndex < m_vconvDependent . size ( ) ) return ( Converter ) m_vconvDependent . get ( iIndex ) ; } return null ; }
Get this converter to use at this index .
16,471
public void addConverterToPass ( Converter converter ) { if ( m_vconvDependent == null ) m_vconvDependent = new Vector < Converter > ( ) ; m_vconvDependent . add ( converter ) ; this . setEnableTranslation ( false ) ; if ( ( this . getNextConverter ( ) == null ) || ( this . getNextConverter ( ) . getField ( ) == null ) ) { this . setEnableTranslation ( true ) ; return ; } for ( int iSeq = 0 ; ; iSeq ++ ) { ScreenComponent sField = ( ScreenComponent ) this . getNextConverter ( ) . getField ( ) . getComponent ( iSeq ) ; if ( sField == null ) break ; if ( ! this . isConverterInPath ( sField ) ) continue ; if ( converter != null ) if ( converter . getField ( ) != null ) { boolean bFound = false ; for ( int iSeq2 = 0 ; ; iSeq2 ++ ) { if ( converter . getField ( ) . getComponent ( iSeq2 ) == null ) break ; if ( converter . getField ( ) . getComponent ( iSeq2 ) == sField ) bFound = true ; } if ( ! bFound ) converter . addComponent ( sField ) ; } } this . setEnableTranslation ( true ) ; }
Add this converter to pass .
16,472
public boolean setEnableTranslation ( boolean bEnableTranslation ) { boolean bOldTranslation = m_bEnableTranslation ; m_bEnableTranslation = false ; LinkedConverter converter = this ; while ( converter != null ) { if ( converter . getNextConverter ( ) instanceof LinkedConverter ) { converter = ( LinkedConverter ) ( ( LinkedConverter ) converter ) . getNextConverter ( ) ; if ( converter instanceof MultipleFieldConverter ) ( ( MultipleFieldConverter ) converter ) . setEnableTranslation ( bEnableTranslation ) ; } else converter = null ; } m_bEnableTranslation = bEnableTranslation ; return bOldTranslation ; }
Enable or disable the converter translation .
16,473
public boolean isConverterInPath ( ScreenComponent sField ) { Convert converter = sField . getConverter ( ) ; while ( converter != null ) { if ( converter == this ) return true ; if ( converter instanceof LinkedConverter ) { MultipleFieldConverter convMultiple = null ; boolean bOldEnable = false ; if ( converter instanceof MultipleFieldConverter ) convMultiple = ( MultipleFieldConverter ) converter ; if ( convMultiple != null ) bOldEnable = convMultiple . setEnableTranslation ( false ) ; converter = ( ( LinkedConverter ) converter ) . getNextConverter ( ) ; if ( convMultiple != null ) convMultiple . setEnableTranslation ( bOldEnable ) ; } else converter = null ; } return false ; }
Is this converter in the converter path of this screen field .
16,474
public Record makeDefaultAnalysisRecord ( Record recBasis ) { Record recSummary = new AnalysisRecord ( this ) ; KeyArea keyArea = recSummary . makeIndex ( DBConstants . UNIQUE , "SummaryKey" ) ; boolean bAddKeyField = true ; for ( int i = 0 ; i < this . getSourceFieldCount ( ) ; i ++ ) { BaseField field = this . getSourceField ( i ) ; if ( field == null ) continue ; try { BaseField fldSummary = BaseField . cloneField ( field ) ; if ( field . getRecord ( ) != recBasis ) { String strRecord = field . getRecord ( ) . getRecordName ( ) ; if ( field . getRecord ( ) == this . getScreenRecord ( ) ) strRecord = "ScreenRecord" ; fldSummary . setFieldName ( strRecord + '.' + field . getFieldName ( ) ) ; } if ( field == field . getRecord ( ) . getCounterField ( ) ) { fldSummary . setFieldName ( "Count" ) ; fldSummary . setFieldDesc ( "Count" ) ; } recSummary . addField ( fldSummary ) ; if ( ! this . isKeyField ( fldSummary , i ) ) if ( i != 0 ) bAddKeyField = false ; if ( bAddKeyField ) keyArea . addKeyField ( fldSummary , DBConstants . ASCENDING ) ; } catch ( CloneNotSupportedException ex ) { ex . printStackTrace ( ) ; } } recSummary . setKeyArea ( AnalysisRecord . kIDKey + 1 ) ; for ( int i = this . getSFieldCount ( ) - 1 ; i >= 0 ; i -- ) { ScreenField sField = this . getSField ( i ) ; if ( ! ( sField instanceof BasePanel ) ) sField . free ( ) ; } int iToolbars = this . getSFieldCount ( ) ; for ( int i = AnalysisRecord . kID + 1 ; i < recSummary . getFieldCount ( ) ; i ++ ) { recSummary . getField ( i ) . setupDefaultView ( this . getNextLocation ( ScreenConstants . NEXT_LOGICAL , ScreenConstants . ANCHOR_DEFAULT ) , this , ScreenConstants . DEFAULT_DISPLAY ) ; } while ( iToolbars > 0 ) { ScreenField sField = this . getSField ( 0 ) ; this . removeSField ( sField ) ; this . addSField ( sField ) ; iToolbars -- ; } this . addRecord ( recSummary , true ) ; return recSummary ; }
Create a record to do the data analysis with .
16,475
public BaseField [ ] [ ] getKeyMap ( Record recSummary , Record recBasis ) { BaseField [ ] [ ] mxKeyFields = new BaseField [ recSummary . getKeyArea ( ) . getKeyFields ( ) ] [ 2 ] ; for ( int i = 0 ; i < mxKeyFields . length ; i ++ ) { mxKeyFields [ i ] [ SUMMARY ] = recSummary . getKeyArea ( ) . getField ( i ) ; mxKeyFields [ i ] [ BASIS ] = this . getBasisField ( mxKeyFields [ i ] [ SUMMARY ] , recBasis , i ) ; } return mxKeyFields ; }
Create a map of the source and destination key fields .
16,476
public BaseField [ ] [ ] getDataMap ( Record recSummary , Record recBasis ) { int iFieldSeq = 0 ; if ( recSummary . getField ( iFieldSeq ) == recSummary . getCounterField ( ) ) iFieldSeq ++ ; int iLength = recSummary . getFieldCount ( ) ; iLength = iLength - recSummary . getKeyArea ( ) . getKeyFields ( ) - iFieldSeq ; BaseField [ ] [ ] mxDataFields = new BaseField [ iLength ] [ 2 ] ; for ( int i = 0 ; i < mxDataFields . length ; i ++ ) { mxDataFields [ i ] [ SUMMARY ] = recSummary . getField ( iFieldSeq ) ; mxDataFields [ i ] [ BASIS ] = this . getBasisField ( mxDataFields [ i ] [ SUMMARY ] , recBasis , i ) ; iFieldSeq ++ ; for ( int j = 0 ; j < recSummary . getKeyArea ( ) . getKeyFields ( ) ; j ++ ) { if ( mxDataFields [ i ] [ SUMMARY ] == recSummary . getKeyArea ( ) . getField ( j ) ) { i -- ; break ; } } } return mxDataFields ; }
Create a map of the source and destination data fields .
16,477
public BaseField getBasisField ( BaseField fldSummary , Record recBasis , int iSummarySeq ) { BaseField fldBasis = null ; String strFieldName = fldSummary . getFieldName ( ) ; if ( ( strFieldName != null ) && ( strFieldName . indexOf ( '.' ) != - 1 ) ) { Record record = this . getRecord ( strFieldName . substring ( 0 , strFieldName . indexOf ( '.' ) ) ) ; if ( ( strFieldName . indexOf ( '.' ) == 0 ) || ( "ScreenRecord" . equalsIgnoreCase ( strFieldName . substring ( 0 , strFieldName . indexOf ( '.' ) ) ) ) ) record = this . getScreenRecord ( ) ; fldBasis = record . getField ( strFieldName . substring ( strFieldName . indexOf ( '.' ) + 1 ) ) ; } else fldBasis = recBasis . getField ( strFieldName ) ; return fldBasis ; }
Get the matching basis field given the summary field . Override this if you don t want the defaults .
16,478
public void setupSummaryKey ( BaseField [ ] [ ] mxKeyFields ) { for ( int i = 0 ; i < mxKeyFields . length ; i ++ ) { mxKeyFields [ i ] [ SUMMARY ] . moveFieldToThis ( mxKeyFields [ i ] [ BASIS ] ) ; } }
Move the source key fields to the destinataion keys .
16,479
public void addSummaryData ( BaseField [ ] [ ] mxDataFields ) { for ( int i = 0 ; i < mxDataFields . length ; i ++ ) { double dAmount = 1 ; if ( mxDataFields [ i ] [ BASIS ] != null ) dAmount = mxDataFields [ i ] [ BASIS ] . getValue ( ) ; mxDataFields [ i ] [ SUMMARY ] . setValue ( mxDataFields [ i ] [ SUMMARY ] . getValue ( ) + dAmount ) ; } }
Move the source data fields to the destinataion data fields .
16,480
public void onReceive ( Context context , Intent notification ) { GoogleCloudMessaging gcm = GoogleCloudMessaging . getInstance ( context ) ; String messageType = gcm . getMessageType ( notification ) ; Bundle extras = notification . getExtras ( ) ; if ( ! extras . isEmpty ( ) && GoogleCloudMessaging . MESSAGE_TYPE_MESSAGE . equals ( messageType ) ) { showNotification ( context , extras ) ; } }
Called when a notification is received
16,481
public void showNotification ( Context context , Bundle extras ) { String title = getTitle ( context , extras ) ; String message = getMessage ( context , extras ) ; if ( message == null ) return ; NotificationManager mNotificationManager = ( NotificationManager ) context . getSystemService ( Context . NOTIFICATION_SERVICE ) ; long when = System . currentTimeMillis ( ) ; NotificationCompat . Builder mBuilder = new NotificationCompat . Builder ( context ) . setAutoCancel ( true ) . setSmallIcon ( getIcon ( context ) ) . setContentTitle ( title ) . setContentText ( message ) . setContentIntent ( getContentIntent ( context , extras , when ) ) . setStyle ( new NotificationCompat . BigTextStyle ( ) . bigText ( message ) ) ; mNotificationManager . notify ( ( int ) when , mBuilder . build ( ) ) ; }
Shows a notification for the given push message
16,482
public static ColorUIResource darken ( ColorUIResource color ) { return new ColorUIResource ( darkenRGB ( color . getRed ( ) ) , darkenRGB ( color . getGreen ( ) ) , darkenRGB ( color . getBlue ( ) ) ) ; }
Lighten this color .
16,483
public void run ( ) { try { MDC . put ( "name" , name ) ; log . info ( "Starting {}..." , name ) ; String brokerUrl = globalConfig . getString ( ActiveMQConnectionFactory . DEFAULT_BROKER_BIND_URL , "messaging" , "url" ) ; ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory ( brokerUrl ) ; connection = connectionFactory . createConnection ( ) ; session = connection . createSession ( false , Session . AUTO_ACKNOWLEDGE ) ; consumer = session . createConsumer ( session . createQueue ( QUEUE_ID ) ) ; consumer . setMessageListener ( this ) ; connection . start ( ) ; solr = initCore ( "solr" ) ; timer = new Timer ( "SolrWrapper:" + toString ( ) , true ) ; timer . scheduleAtFixedRate ( new TimerTask ( ) { public void run ( ) { checkTimeout ( ) ; } } , 0 , 10000 ) ; } catch ( JMSException ex ) { log . error ( "Error starting message thread!" , ex ) ; } }
Start thread running
16,484
public void stop ( ) throws Exception { log . info ( "Stopping {}..." , name ) ; submitBuffer ( true ) ; if ( coreContainer != null ) { coreContainer . shutdown ( ) ; } if ( consumer != null ) { try { consumer . close ( ) ; } catch ( JMSException jmse ) { log . warn ( "Failed to close consumer: {}" , jmse . getMessage ( ) ) ; throw jmse ; } } if ( session != null ) { try { session . close ( ) ; } catch ( JMSException jmse ) { log . warn ( "Failed to close consumer session: {}" , jmse ) ; } } if ( connection != null ) { try { connection . close ( ) ; } catch ( JMSException jmse ) { log . warn ( "Failed to close connection: {}" , jmse ) ; } } timer . cancel ( ) ; }
Stop the Render Queue Consumer . Including stopping the storage and indexer
16,485
public void onMessage ( Message message ) { MDC . put ( "name" , name ) ; try { if ( ! Thread . currentThread ( ) . getName ( ) . equals ( thread . getName ( ) ) ) { Thread . currentThread ( ) . setName ( thread . getName ( ) ) ; Thread . currentThread ( ) . setPriority ( thread . getPriority ( ) ) ; } String text = ( ( TextMessage ) message ) . getText ( ) ; JsonSimple config = new JsonSimple ( text ) ; String event = config . getString ( null , "event" ) ; if ( event == null ) { log . error ( "Invalid message received: '{}'" , text ) ; return ; } if ( event . equals ( "commit" ) ) { log . debug ( "Commit received" ) ; submitBuffer ( true ) ; } if ( event . equals ( "index" ) ) { String index = config . getString ( null , "index" ) ; String document = config . getString ( null , "document" ) ; if ( index == null || document == null ) { log . error ( "Invalid message received: '{}'" , text ) ; return ; } addToBuffer ( index , document ) ; } } catch ( JMSException jmse ) { log . error ( "Failed to send/receive message: {}" , jmse . getMessage ( ) ) ; } catch ( IOException ioe ) { log . error ( "Failed to parse message: {}" , ioe . getMessage ( ) ) ; } }
Callback function for incoming messages .
16,486
private void submitBuffer ( boolean forceCommit ) { int size = docBuffer . size ( ) ; if ( size > 0 ) { log . debug ( "=== Submitting buffer: " + size + " documents" ) ; StringBuffer submissionBuffer = new StringBuffer ( ) ; for ( String doc : docBuffer . keySet ( ) ) { submissionBuffer . append ( docBuffer . get ( doc ) ) ; } if ( submissionBuffer . length ( ) > 0 ) { String submission = submissionBuffer . insert ( 0 , "<add>" ) . append ( "</add>" ) . toString ( ) ; try { solr . request ( new DirectXmlRequest ( "/update" , submission ) ) ; } catch ( Exception ex ) { log . error ( "Error submitting documents to Solr!" , ex ) ; } if ( autoCommit || forceCommit ) { log . info ( "Running forced commit!" ) ; try { if ( commit != null ) { solr . commit ( ) ; commit . commit ( ) ; } else { solr . commit ( ) ; } } catch ( Exception e ) { log . warn ( "Solr forced commit failed. Document will" + " not be visible until Solr autocommit fires." + " Error message: {}" , e ) ; } } } } purgeBuffer ( ) ; }
Submit all documents currently in the buffer to Solr then purge
16,487
public void setPriority ( int newPriority ) { if ( newPriority >= Thread . MIN_PRIORITY && newPriority <= Thread . MAX_PRIORITY ) { thread . setPriority ( newPriority ) ; } }
Sets the priority level for the thread . Used by the OS .
16,488
public static String insert ( String haystack , String needle , int index ) { StringBuffer val = new StringBuffer ( haystack ) ; val . insert ( index , needle ) ; return val . toString ( ) ; }
replaces the first occurrence of needle in haystack with newNeedle
16,489
public static void replaceFirst ( StringBuffer haystack , String needle , String newNeedle ) { int idx = haystack . indexOf ( needle ) ; if ( idx != - 1 ) { haystack . replace ( idx , idx + needle . length ( ) , newNeedle ) ; } }
replaces the first occurance of needle in haystack with newNeedle
16,490
public static void replaceLast ( StringBuffer haystack , String needle , String newNeedle ) { int idx = haystack . lastIndexOf ( needle ) ; if ( idx != - 1 ) { haystack . replace ( idx , idx + needle . length ( ) , newNeedle ) ; } }
replaces the last occurance of needle in haystack with newNeedle
16,491
public static String replaceAll ( String haystack , String [ ] needle , String newNeedle [ ] ) { if ( needle . length != newNeedle . length ) { throw new IllegalArgumentException ( "length of original and replace values do not match (" + needle . length + " != " + newNeedle . length + " )" ) ; } StringBuffer buf = new StringBuffer ( haystack ) ; for ( int i = 0 ; i < needle . length ; i ++ ) { replaceAll ( buf , needle [ i ] , newNeedle [ i ] ) ; } return buf . toString ( ) ; }
Replaces a series of possible occurrences by a series of substitutes .
16,492
public static void replaceAll ( StringBuffer haystack , String needle , String newNeedle ) { replaceAll ( haystack , needle , newNeedle , 0 ) ; }
replaces all occurrences of needle in haystack with newNeedle the input itself is not modified
16,493
public static void replaceAll ( StringBuffer haystack , String needle , String newNeedle , int interval ) { if ( needle == null ) { throw new IllegalArgumentException ( "string to replace can not be empty" ) ; } int idx = haystack . indexOf ( needle ) ; int nextIdx = - 1 ; int processedChunkSize = idx ; int needleLength = needle . length ( ) ; int newNeedleLength = newNeedle . length ( ) ; while ( idx != - 1 ) { if ( processedChunkSize >= interval ) { haystack . replace ( idx , idx + needleLength , newNeedle ) ; nextIdx = haystack . indexOf ( needle , idx + newNeedleLength ) ; processedChunkSize = nextIdx - idx ; idx = nextIdx ; } else { nextIdx = haystack . indexOf ( needle , idx + newNeedleLength ) ; processedChunkSize += nextIdx - idx ; idx = nextIdx ; if ( newNeedleLength == 0 ) { return ; } } } }
default is 0 which means that all found characters must be replaced
16,494
public static String removeAll ( String haystack , String ... needles ) { return replaceAll ( haystack , needles , ArraySupport . getFilledArray ( new String [ needles . length ] , "" ) ) ; }
removes all occurrences of needle in haystack
16,495
public static String esc ( String in ) { if ( in == null ) { return null ; } StringBuffer val = new StringBuffer ( in ) ; esc ( val ) ; return val . toString ( ) ; }
Escapes quotes double quotes ecape characters and end - of - line characters in strings .
16,496
public static void esc ( StringBuffer in ) { if ( in == null ) { return ; } replaceAll ( in , "\\" , "\\\\" ) ; replaceAll ( in , "'" , "\\'" ) ; replaceAll ( in , "\"" , "\\\"" ) ; replaceAll ( in , "\n" , "\\n" ) ; replaceAll ( in , "\r" , "\\r" ) ; }
Escapes quotes double quotes ecape characters and end - of - line characters in strings
16,497
public static boolean isNumeric ( String in ) { char c = 0 ; for ( int i = in . length ( ) ; i > 0 ; i -- ) { c = in . charAt ( i - 1 ) ; if ( ! Character . isDigit ( c ) ) { return false ; } } return true ; }
tells whether all characters in a String are digits
16,498
public static boolean isAlpha ( String in ) { char c = 0 ; for ( int i = in . length ( ) ; i > 0 ; i -- ) { c = in . charAt ( i - 1 ) ; if ( ! Character . isLetter ( c ) ) { return false ; } } return true ; }
tells whether all characters in a String are letters
16,499
public static boolean isAlphaNumeric ( String in ) { char c = 0 ; for ( int i = in . length ( ) ; i > 0 ; i -- ) { c = in . charAt ( i - 1 ) ; if ( ! Character . isLetterOrDigit ( c ) ) { return false ; } } return true ; }
tells whether all characters in a String are digits or letters