idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
16,200
public List < Meta > selectPostMeta ( final long postId ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; List < Meta > meta = Lists . newArrayListWithExpectedSize ( 8 ) ; Timer . Context ctx = metrics . selectPostMetaTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( selectPostMetaSQL ) ; stmt . setLong ( 1 , postId ) ; rs = stmt . executeQuery ( ) ; while ( rs . next ( ) ) { meta . add ( new Meta ( rs . getLong ( 1 ) , rs . getString ( 2 ) , rs . getString ( 3 ) ) ) ; } } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt , rs ) ; } return meta ; }
Selects metadata for a post .
16,201
public Meta selectPostMetaValue ( final long postId , final String metaKey ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; Timer . Context ctx = metrics . selectPostMetaTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( selectPostMetaValueSQL ) ; stmt . setLong ( 1 , postId ) ; stmt . setString ( 2 , metaKey ) ; rs = stmt . executeQuery ( ) ; return rs . next ( ) ? new Meta ( rs . getLong ( 1 ) , rs . getString ( 2 ) , rs . getString ( 3 ) ) : null ; } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt , rs ) ; } }
Selects a single post meta value .
16,202
public void updatePostMetaValue ( final long postId , final String metaKey , final String metaValue ) throws SQLException { Meta currMeta = selectPostMetaValue ( postId , metaKey ) ; if ( currMeta == null ) { Connection conn = null ; PreparedStatement stmt = null ; Timer . Context ctx = metrics . setPostMetaTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( insertPostMetaSQL ) ; stmt . setLong ( 1 , postId ) ; stmt . setString ( 2 , metaKey ) ; stmt . setString ( 3 , metaValue ) ; stmt . executeUpdate ( ) ; } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt ) ; } } else { Connection conn = null ; PreparedStatement stmt = null ; Timer . Context ctx = metrics . setPostMetaTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( updatePostMetaValueSQL ) ; stmt . setString ( 1 , metaValue ) ; stmt . setString ( 2 , metaKey ) ; stmt . setLong ( 3 , postId ) ; stmt . executeUpdate ( ) ; } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt ) ; } } }
Updates a post meta value if it exists or inserts if it does not .
16,203
public void clearTermMeta ( final long termId ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; Timer . Context ctx = metrics . clearTermMetaTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( deleteTermMetaSQL ) ; stmt . setLong ( 1 , termId ) ; stmt . executeUpdate ( ) ; } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt ) ; } }
Clears all metadata for a term .
16,204
public List < Meta > selectTermMeta ( final long termId ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; List < Meta > meta = Lists . newArrayListWithExpectedSize ( 8 ) ; Timer . Context ctx = metrics . selectTermMetaTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( selectTermMetaSQL ) ; stmt . setLong ( 1 , termId ) ; rs = stmt . executeQuery ( ) ; while ( rs . next ( ) ) { meta . add ( new Meta ( rs . getLong ( 1 ) , rs . getString ( 2 ) , rs . getString ( 3 ) ) ) ; } } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt , rs ) ; } return meta ; }
Selects metadata for a term .
16,205
public Set < Long > selectTermIds ( final String name ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; Set < Long > ids = Sets . newHashSetWithExpectedSize ( 4 ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( selectTermIdsSQL ) ; stmt . setString ( 1 , name ) ; rs = stmt . executeQuery ( ) ; while ( rs . next ( ) ) { ids . add ( rs . getLong ( 1 ) ) ; } return ids ; } finally { SQLUtil . closeQuietly ( conn , stmt , rs ) ; } }
Selects the term ids for all with the specified name .
16,206
public Term createTerm ( final String name , final String slug ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; Timer . Context ctx = metrics . createTermTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( insertTermSQL , Statement . RETURN_GENERATED_KEYS ) ; stmt . setString ( 1 , name ) ; stmt . setString ( 2 , slug ) ; stmt . executeUpdate ( ) ; rs = stmt . getGeneratedKeys ( ) ; if ( rs . next ( ) ) { return new Term ( rs . getLong ( 1 ) , name , slug ) ; } else { throw new SQLException ( "Problem creating term (no generated id)" ) ; } } finally { ctx . stop ( ) ; closeQuietly ( conn , stmt , rs ) ; } }
Creates a term .
16,207
public Term selectTerm ( final long id ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; Timer . Context ctx = metrics . selectTermTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( selectTermIdSQL ) ; stmt . setLong ( 1 , id ) ; rs = stmt . executeQuery ( ) ; return rs . next ( ) ? new Term ( id , rs . getString ( 1 ) , rs . getString ( 2 ) ) : null ; } finally { ctx . stop ( ) ; closeQuietly ( conn , stmt , rs ) ; } }
Selects a term by id .
16,208
public boolean deleteTerm ( final long id ) throws SQLException { try ( Connection conn = connectionSupplier . getConnection ( ) ; PreparedStatement stmt = conn . prepareStatement ( deleteTermIdSQL ) ) { stmt . setLong ( 1 , id ) ; return stmt . executeUpdate ( ) > 0 ; } }
Deletes a term by id .
16,209
public List < Term > selectSlugTerms ( final String slug ) throws SQLException { try ( Connection conn = connectionSupplier . getConnection ( ) ; PreparedStatement stmt = conn . prepareStatement ( selectTermSlugSQL ) ; Timer . Context ctx = metrics . selectTermTimer . time ( ) ) { stmt . setString ( 1 , slug ) ; try ( ResultSet rs = stmt . executeQuery ( ) ) { List < Term > terms = Lists . newArrayListWithExpectedSize ( 2 ) ; while ( rs . next ( ) ) { terms . add ( new Term ( rs . getLong ( 1 ) , rs . getString ( 2 ) , rs . getString ( 3 ) ) ) ; } return terms ; } } }
Selects terms with a matching slug .
16,210
public TaxonomyTerm selectTaxonomyTerm ( final String taxonomy , final String name ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; long taxonomyTermId = 0L ; long termId = 0L ; String description = "" ; Timer . Context ctx = metrics . selectTaxonomyTermTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( selectTaxonomyTermSQL ) ; stmt . setString ( 1 , name ) ; stmt . setString ( 2 , taxonomy ) ; rs = stmt . executeQuery ( ) ; if ( rs . next ( ) ) { taxonomyTermId = rs . getLong ( 1 ) ; termId = rs . getLong ( 2 ) ; description = rs . getString ( 3 ) ; } else { return null ; } } finally { ctx . stop ( ) ; closeQuietly ( conn , stmt , rs ) ; } return new TaxonomyTerm ( taxonomyTermId , taxonomy , selectTerm ( termId ) , description ) ; }
Selects a taxonomy term .
16,211
public boolean setTaxonomyTermDescription ( final String taxonomy , final String name , final String description ) throws SQLException { TaxonomyTerm term = selectTaxonomyTerm ( taxonomy , name ) ; if ( term == null || term . term == null ) { return false ; } Connection conn = null ; PreparedStatement stmt = null ; Timer . Context ctx = metrics . updateTaxonomyTermTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( updateTaxonomyTermDescriptionSQL ) ; stmt . setString ( 1 , Strings . nullToEmpty ( description ) ) ; stmt . setLong ( 2 , term . term . id ) ; stmt . setString ( 3 , taxonomy ) ; return stmt . executeUpdate ( ) > 0 ; } finally { ctx . stop ( ) ; closeQuietly ( conn , stmt ) ; } }
Sets the description for a taxonomy term .
16,212
public TaxonomyTerm createTaxonomyTerm ( final String taxonomy , final String name , final String slug , final String description ) throws SQLException { Term term = createTerm ( name , slug ) ; Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; Timer . Context ctx = metrics . createTaxonomyTermTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( insertTaxonomyTermSQL , Statement . RETURN_GENERATED_KEYS ) ; stmt . setLong ( 1 , term . id ) ; stmt . setString ( 2 , taxonomy ) ; stmt . setString ( 3 , Strings . nullToEmpty ( description ) ) ; stmt . executeUpdate ( ) ; rs = stmt . getGeneratedKeys ( ) ; if ( rs . next ( ) ) { return new TaxonomyTerm ( rs . getLong ( 1 ) , taxonomy , term , description ) ; } else { throw new SQLException ( "Problem creating taxonomy term (no generated id)" ) ; } } finally { ctx . stop ( ) ; closeQuietly ( conn , stmt , rs ) ; } }
Creates a taxonomy term .
16,213
public TaxonomyTerm resolveTaxonomyTerm ( final String taxonomy , final String name ) throws SQLException { TaxonomyTerm term ; Cache < String , TaxonomyTerm > taxonomyTermCache = taxonomyTermCaches . get ( taxonomy ) ; if ( taxonomyTermCache != null ) { metrics . taxonomyTermCacheTries . mark ( ) ; term = taxonomyTermCache . getIfPresent ( name ) ; if ( term != null ) { metrics . taxonomyTermCacheHits . mark ( ) ; return term ; } } term = selectTaxonomyTerm ( taxonomy , name ) ; if ( term != null && taxonomyTermCache != null ) { taxonomyTermCache . put ( name , term ) ; } return term ; }
Resolves a taxonomy term .
16,214
public void clearPostTerm ( final long postId , final long taxonomyTermId ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; Timer . Context ctx = metrics . postTermsClearTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( clearPostTermSQL ) ; stmt . setLong ( 1 , postId ) ; stmt . setLong ( 2 , taxonomyTermId ) ; stmt . executeUpdate ( ) ; } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt ) ; } }
Clears a single taxonomy term associated with a post .
16,215
public void clearPostTerms ( final long postId , final String taxonomy ) throws SQLException { List < TaxonomyTerm > terms = selectPostTerms ( postId , taxonomy ) ; for ( TaxonomyTerm term : terms ) { clearPostTerm ( postId , term . id ) ; } }
Clears all terms associated with a post with a specified taxonomy .
16,216
public boolean addPostTerm ( final long postId , final TaxonomyTerm taxonomyTerm ) throws SQLException { List < TaxonomyTerm > currTerms = selectPostTerms ( postId , taxonomyTerm . taxonomy ) ; for ( TaxonomyTerm currTerm : currTerms ) { if ( currTerm . term . name . equals ( taxonomyTerm . term . name ) ) { return false ; } } Connection conn = null ; PreparedStatement stmt = null ; Timer . Context ctx = metrics . postTermsSetTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( insertPostTermSQL ) ; stmt . setLong ( 1 , postId ) ; stmt . setLong ( 2 , taxonomyTerm . id ) ; stmt . setInt ( 3 , currTerms . size ( ) ) ; return stmt . executeUpdate ( ) > 0 ; } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt ) ; } }
Adds a term at the end of the current terms if it does not already exist .
16,217
public List < TaxonomyTerm > selectPostTerms ( final long postId , final String taxonomy ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; List < Long > termIds = Lists . newArrayListWithExpectedSize ( 8 ) ; Timer . Context ctx = metrics . postTermsSelectTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( selectPostTermsSQL ) ; stmt . setLong ( 1 , postId ) ; rs = stmt . executeQuery ( ) ; while ( rs . next ( ) ) { termIds . add ( rs . getLong ( 1 ) ) ; } } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt , rs ) ; } if ( termIds . size ( ) == 0 ) { return ImmutableList . of ( ) ; } List < TaxonomyTerm > terms = Lists . newArrayListWithExpectedSize ( termIds . size ( ) ) ; for ( long termId : termIds ) { TaxonomyTerm term = resolveTaxonomyTerm ( termId ) ; if ( term != null && ( taxonomy == null || term . taxonomy . equals ( taxonomy ) ) ) { terms . add ( term ) ; } } return terms ; }
Selects all terms associated with a post .
16,218
public String selectOption ( final String optionName , final String defaultValue ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; Timer . Context ctx = metrics . optionSelectTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( selectOptionSQL ) ; stmt . setString ( 1 , optionName ) ; rs = stmt . executeQuery ( ) ; if ( rs . next ( ) ) { String val = rs . getString ( 1 ) ; return val != null ? val . trim ( ) : defaultValue ; } else { return defaultValue ; } } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt , rs ) ; } }
Gets a configuration option with a default value .
16,219
public Site selectSite ( ) throws SQLException { String baseURL = selectOption ( "home" ) ; String title = selectOption ( "blogname" ) ; String description = selectOption ( "blogdescription" ) ; String permalinkStructure = selectOption ( "permalink_structure" , "/?p=%postid%" ) ; long defaultCategoryId = Long . parseLong ( selectOption ( "default_category" , "0" ) ) ; TaxonomyTerm defaultCategoryTerm = resolveTaxonomyTerm ( defaultCategoryId ) ; if ( defaultCategoryTerm == null ) { defaultCategoryTerm = new TaxonomyTerm ( 0L , CATEGORY_TAXONOMY , new Term ( 0L , "Uncategorized" , "uncategorized" ) , "" ) ; } return new Site ( siteId , baseURL , title , description , permalinkStructure , defaultCategoryTerm . term ) ; }
Selects the site metadata from the options table .
16,220
private Blog blogFromResultSet ( final ResultSet rs ) throws SQLException { long registeredTimestamp = 0L ; long lastUpdatedTimestamp = 0L ; try { registeredTimestamp = rs . getTimestamp ( 5 ) . getTime ( ) ; } catch ( SQLException se ) { registeredTimestamp = 0L ; } try { lastUpdatedTimestamp = rs . getTimestamp ( 6 ) . getTime ( ) ; } catch ( SQLException se ) { lastUpdatedTimestamp = 0L ; } return new Blog ( rs . getLong ( 1 ) , rs . getLong ( 2 ) , rs . getString ( 3 ) , rs . getString ( 4 ) , registeredTimestamp , lastUpdatedTimestamp ) ; }
Creates a blog from a result set .
16,221
public List < Blog > selectPublicBlogs ( ) throws SQLException { Connection conn = null ; PreparedStatement stmt = null ; ResultSet rs = null ; List < Blog > blogs = Lists . newArrayListWithExpectedSize ( 4 ) ; Timer . Context ctx = metrics . selectBlogsTimer . time ( ) ; try { conn = connectionSupplier . getConnection ( ) ; stmt = conn . prepareStatement ( selectPublicBlogsSQL ) ; rs = stmt . executeQuery ( ) ; while ( rs . next ( ) ) { blogs . add ( blogFromResultSet ( rs ) ) ; } } finally { ctx . stop ( ) ; SQLUtil . closeQuietly ( conn , stmt , rs ) ; } return blogs ; }
Selects all public enabled blogs .
16,222
public void surveyPage ( PageFormat pageFormat , Graphics2D g2d , boolean bPrintHeader ) { pageRect = new Rectangle ( ( int ) pageFormat . getImageableX ( ) , ( int ) pageFormat . getImageableY ( ) , ( int ) pageFormat . getImageableWidth ( ) , ( int ) pageFormat . getImageableHeight ( ) ) ; FontMetrics fm = g2d . getFontMetrics ( ) ; int textHeight = fm . getHeight ( ) ; if ( bPrintHeader ) { headerHeight = textHeight + HEADER_MARGIN + BORDER ; footerHeight = textHeight + HEADER_MARGIN + BORDER ; } }
Save basic page information .
16,223
protected void printHeader ( Graphics2D g2d , String headerText ) { FontMetrics fm = g2d . getFontMetrics ( ) ; int textHeight = fm . getHeight ( ) ; int stringWidth = fm . stringWidth ( headerText ) ; int textX = ( pageRect . width - stringWidth ) / 2 + pageRect . x ; int textY = pageRect . y + textHeight + BORDER ; g2d . drawString ( headerText , textX , textY ) ; }
Print the page header .
16,224
protected void printFooter ( Graphics2D g2d , String footerText ) { FontMetrics fm = g2d . getFontMetrics ( ) ; int stringWidth = fm . stringWidth ( footerText ) ; int textX = ( pageRect . width - stringWidth ) / 2 + pageRect . x ; int textY = pageRect . y + pageRect . height - BORDER ; g2d . drawString ( footerText , textX , textY ) ; }
Print the page footer .
16,225
public Path build ( Path base ) throws IOException { this . dir = base . resolve ( name + "-" + version ) ; this . debian = dir . resolve ( "debian" ) ; control . setStandardsVersion ( STANDARDS_VERSION ) ; changeLog . set ( name , version , release , maintainer ) ; control . setSource ( name ) ; for ( FileBuilder fb : fileBuilders ) { fb . build ( ) ; } copyright . save ( debian ) ; control . save ( debian ) ; changeLog . save ( debian ) ; Path compat = debian . resolve ( "compat" ) ; try ( BufferedWriter bf = Files . newBufferedWriter ( compat , UTF_8 ) ) { bf . append ( String . format ( "%d\n" , compatibility ) ) ; } for ( MaintainerScript ms : maintainerScripts ) { ms . save ( ) ; } Path rules = debian . resolve ( "rules" ) ; FileUtil . copyResource ( "/rules" , rules , DEBBuilder . class ) ; PosixHelp . setPermission ( rules , "-rwxr-xr-x" ) ; Path source = debian . resolve ( "source" ) ; Files . createDirectories ( source ) ; Path format = source . resolve ( "format" ) ; try ( BufferedWriter bf = Files . newBufferedWriter ( format , UTF_8 ) ) { bf . append ( SOURCE_FORMAT ) ; } conffiles . save ( debian ) ; docs . save ( debian ) ; try { OSProcess . call ( dir , null , "dpkg-buildpackage -us -uc" ) ; } catch ( InterruptedException ex ) { throw new IOException ( ex ) ; } return dir ; }
Creates name - version directory creates debian source files and runs dpkg - buildpackage - us - uc
16,226
public void execute ( ) throws MojoExecutionException { if ( properties == null ) { getLog ( ) . warn ( "run-script failed: No properties supplied" ) ; return ; } boolean bSuccess = false ; Environment env = null ; RunScriptProcess process = null ; try { env = new Environment ( properties ) ; Application app = new ThinApplication ( env , properties , null ) ; Task task = new AutoTask ( app , null , null ) ; process = new RunScriptProcess ( task , null , null ) ; bSuccess = ( process . doRunCommand ( null , properties ) == DBConstants . NORMAL_RETURN ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { if ( process != null ) process . free ( ) ; if ( env != null ) env . free ( ) ; } if ( bSuccess ) getLog ( ) . info ( "run-script ran successfully: " + properties . get ( DBParams . PROCESS ) ) ; else getLog ( ) . warn ( "run-script failed: " + properties . get ( DBParams . PROCESS ) ) ; }
Execute the script mojo .
16,227
public HiltItemStack setName ( String name ) { createItemMeta ( ) ; ItemMeta itemMeta = getItemMeta ( ) ; itemMeta . setDisplayName ( name != null ? name . replace ( "\\s+" , " " ) : null ) ; setItemMeta ( itemMeta ) ; return this ; }
Sets the name of this ItemStack . Use null to remove name .
16,228
public List < String > getLore ( ) { createItemMeta ( ) ; if ( getItemMeta ( ) . hasLore ( ) ) { return new ArrayList < > ( getItemMeta ( ) . getLore ( ) ) ; } return new ArrayList < > ( ) ; }
Gets and returns the lore of this HiltItemStack .
16,229
public HiltItemStack setLore ( List < String > lore ) { createItemMeta ( ) ; ItemMeta itemMeta = getItemMeta ( ) ; itemMeta . setLore ( lore ) ; setItemMeta ( itemMeta ) ; return this ; }
Sets the lore of this ItemStack . Use null to remove lore .
16,230
public boolean isSoftDeleteThisRecord ( ) { Record recDetailOld = m_recDetail ; Record recDetail = this . getDetailRecord ( Record . findRecordOwner ( this . getOwner ( ) ) ) ; if ( m_recDetail != null ) if ( recDetailOld != m_recDetail ) { recDetail . getRecordOwner ( ) . removeRecord ( recDetail ) ; this . getOwner ( ) . addListener ( new FreeOnFreeHandler ( recDetail ) ) ; } if ( recDetail != null ) { if ( recDetail . getListener ( SubFileFilter . class ) == null ) { recDetail . addListener ( new SubFileFilter ( this . getOwner ( ) ) ) ; } try { recDetail . close ( ) ; if ( ! recDetail . hasNext ( ) ) return false ; } catch ( DBException ex ) { ex . printStackTrace ( ) ; } } return super . isSoftDeleteThisRecord ( ) ; }
Soft delete this record? Override this to decide whether to soft delete or physically delete the record . Soft delete if there are any detail record otherwise hard delete this record .
16,231
protected void setParameterToConfigured ( final String parameter ) { if ( configuredParameters == null ) configuredParameters = new ArrayList < String > ( ) ; if ( ! configuredParameters . contains ( parameter ) ) configuredParameters . add ( parameter ) ; }
This is a convenience method that adds a value to the configuredParameters collection
16,232
public void reset ( ) { xMin = Double . NaN ; xMax = Double . NaN ; yMin = Double . NaN ; yMax = Double . NaN ; }
Resets the limits .
16,233
public void update ( double x , double y , double radius ) { update ( x , y ) ; update ( x - radius , y - radius ) ; update ( x + radius , y - radius ) ; update ( x - radius , y + radius ) ; update ( x + radius , y + radius ) ; }
Updates limits so that circle is visible .
16,234
private void calculateCollectionPartDescriptions ( ) { collectionPartIds = new CollectionPartDescription [ this . getNrofParts ( ) ] ; int displayOffset = 0 ; int count = 0 ; for ( count = 0 ; count < getNrofParts ( ) - 1 ; count ++ ) { displayOffset = count * maxPartSize ; if ( displayOffset != offset ) { collectionPartIds [ count ] = new CollectionPartDescription ( displayOffset , maxPartSize , false ) ; } else { collectionPartIds [ count ] = new CollectionPartDescription ( displayOffset , maxPartSize , true ) ; currentCollectionPartIdIndex = count ; } } displayOffset = count * maxPartSize ; if ( displayOffset != offset ) { collectionPartIds [ count ] = new CollectionPartDescription ( displayOffset , getLastPartSize ( ) , false ) ; } else { collectionPartIds [ count ] = new CollectionPartDescription ( displayOffset , getLastPartSize ( ) , true ) ; currentCollectionPartIdIndex = count ; } }
Calculates offsets and sizes of all collection parts the complete collection is divided in .
16,235
@ SuppressWarnings ( { "ConstantConditions" } ) private Map < String , String > buildEpisodeMap ( String [ ] showIds , String [ ] episodeIds , String searchTerm , SearchType searchType , TagMode tagMode , Episode . EpisodeStatus status , SortBy sortBy , SortDir sortDir , Boolean includeViews , Integer page , Integer perPage , Integer embedWidth , Integer embedHeight ) { Map < String , String > map = new HashMap < String , String > ( ) ; map . put ( "expires" , expires ( ) ) ; if ( showIds != null ) map . put ( "show_id" , join ( showIds ) ) ; if ( episodeIds != null ) map . put ( "id" , join ( episodeIds ) ) ; if ( searchTerm != null ) map . put ( "search_type" , searchType . name ( ) ) ; if ( tagMode != null ) map . put ( "tag_mode" , tagMode . name ( ) ) ; if ( status != null ) map . put ( "status" , status . name ( ) ) ; if ( sortBy != null ) map . put ( "sort_by" , sortBy . name ( ) ) ; if ( sortDir != null ) map . put ( "sort_dir" , sortDir . name ( ) ) ; if ( includeViews != null ) map . put ( "include_views" , includeViews . toString ( ) ) ; if ( page != null ) map . put ( "page" , page . toString ( ) ) ; if ( perPage != null ) map . put ( "per_page" , perPage . toString ( ) ) ; if ( embedWidth != null ) map . put ( "embed_width" , embedWidth . toString ( ) ) ; if ( embedHeight != null ) map . put ( "embed_height" , embedHeight . toString ( ) ) ; return map ; }
split out because episode map method was too complex for intellij
16,236
public static Calendar toCalendar ( final long millis ) { final Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeInMillis ( millis ) ; return calendar ; }
Converts the given long value to a calendar object .
16,237
public static Timestamp toTimestamp ( final Date date ) { final Calendar cal = new GregorianCalendar ( ) ; cal . setTime ( date ) ; cal . set ( Calendar . HOUR_OF_DAY , 0 ) ; cal . set ( Calendar . MINUTE , 0 ) ; cal . set ( Calendar . SECOND , 0 ) ; cal . set ( Calendar . MILLISECOND , 0 ) ; return new Timestamp ( cal . getTime ( ) . getTime ( ) ) ; }
Converts a Date to a Timestamp - object .
16,238
protected void appendField ( final StringBuilder builder , final String key , final int value ) { if ( builder . length ( ) > 0 ) { builder . append ( "&" ) ; } builder . append ( key ) . append ( "=" ) . append ( value ) ; }
Append an integer field to the form .
16,239
protected void appendField ( final StringBuilder builder , final String key , final LocalDate value ) { appendField ( builder , key , value . toString ( ) ) ; }
Append a LocalDate field to the form .
16,240
public static < T > List < T > collect ( Iterator < T > iterator ) { List < T > list = new ArrayList < T > ( ) ; while ( iterator . hasNext ( ) ) { list . add ( iterator . next ( ) ) ; } return list ; }
Collect an iterator s elements into a List .
16,241
public static < T > void parallelBatch ( Iterator < ? extends T > iterator , final Consumer < Iterator < ? extends T > > consumer , int batchSize ) throws InterruptedException , ExecutionException { List < Callable < Boolean > > callables = new ArrayList < Callable < Boolean > > ( ) ; while ( iterator . hasNext ( ) ) { Iterator < T > i = next ( iterator , batchSize ) ; final List < T > list = collect ( i ) ; callables . add ( new Callable < Boolean > ( ) { public Boolean call ( ) throws Exception { consumer . accept ( list . iterator ( ) ) ; return true ; } } ) ; } List < Future < Boolean > > futures = EXECUTOR_SERVICE . invokeAll ( callables ) ; for ( Future < Boolean > future : futures ) { future . get ( ) ; } }
Break an iterator s elements into batches and invoke the consumer on these batches in a thread pool .
16,242
public static < T > Iterator < T > concat ( final Iterator < ? extends T > ... iterators ) { return new ImmutableIterator < T > ( ) { int current = 0 ; public boolean hasNext ( ) { advance ( ) ; return current < iterators . length ; } public T next ( ) { advance ( ) ; try { return iterators [ current ] . next ( ) ; } catch ( ArrayIndexOutOfBoundsException e ) { throw new NoSuchElementException ( ) ; } } private void advance ( ) { while ( current < iterators . length && ! iterators [ current ] . hasNext ( ) ) { current ++ ; } } } ; }
Create an iterator which sequentially iterates over a collection of iterators .
16,243
protected void grow ( ) { int newSize = newSize ( ) ; ring = ( double [ ] ) newArray ( ring , size , new double [ newSize ] ) ; size = newSize ; }
Grows ring buffer
16,244
public void setDependentListener ( BaseListener dependentListener ) { if ( dependentListener == null ) return ; boolean bAddToList = true ; for ( BaseListener listener : m_BehaviorList ) { if ( listener == dependentListener ) ; bAddToList = false ; ; } if ( bAddToList ) m_BehaviorList . addElement ( dependentListener ) ; if ( dependentListener != null ) if ( dependentListener . getDependentListener ( ) == null ) dependentListener . setDependentListener ( this ) ; }
Set this listener to be dependent on this .
16,245
public int split ( T obj , int start , int length ) throws IOException { int count = 0 ; if ( length > 0 ) { int end = ( start + length ) % size ; if ( start < end ) { count = op ( obj , start , end ) ; } else { if ( end > 0 ) { count = op ( obj , start , size , 0 , end ) ; } else { count = op ( obj , start , size ) ; } } } assert count <= length ; return count ; }
Calls either of two op methods depending on start + length > size . If so calls op with 5 parameters otherwise op with 3 parameters .
16,246
public void init ( ) { sebLabel = context . getSeb ( ) . getLabel ( ) ; label = generateLabel ( ) ; filePrefix = context . getUtils ( ) . join ( Seb . LABEL_DELIMITER , time . format ( Seb . FILE_DATE_FORMATTER ) , sebLabel , context . getClass ( ) . getSimpleName ( ) , label ) ; }
Is called before event is triggered .
16,247
public boolean hasTranslationErrors ( ) { for ( final TopicErrorDatabase . ErrorType type : errorTypes ) { if ( TopicErrorDatabase . TRANSLATION_ERROR_TYPES . contains ( type ) ) { return true ; } } return false ; }
Checks to see if the Topic has any translation based errors set against it .
16,248
public boolean hasFatalErrors ( ) { for ( final TopicErrorDatabase . ErrorType type : errorTypes ) { if ( TopicErrorDatabase . FATAL_ERROR_TYPES . contains ( type ) ) { return true ; } } return false ; }
Checks to see if the Topic has any regular errors set against it .
16,249
public void updateDatesAndCalendar ( ) { if ( ( this . getEditMode ( ) == DBConstants . EDIT_NONE ) || ( this . getEditMode ( ) == DBConstants . EDIT_ADD ) ) return ; boolean bUpdateDates = false ; int iUpdateDays = ( int ) this . getField ( CalendarControl . UPDATE_DAYS ) . getValue ( ) ; Calendar calNow = new GregorianCalendar ( ) ; if ( ( this . getField ( CalendarControl . START_ANNIV_DATE ) . isNull ( ) ) || ( this . getField ( CalendarControl . END_ANNIV_DATE ) . isNull ( ) ) ) bUpdateDates = true ; else { Calendar calCutoff = ( ( DateTimeField ) this . getField ( CalendarControl . LAST_UPDATE_DATE ) ) . getCalendar ( ) ; calCutoff . add ( Calendar . DAY_OF_YEAR , iUpdateDays ) ; if ( calNow . after ( calCutoff ) ) bUpdateDates = true ; } if ( bUpdateDates ) { int iBackDays = ( int ) this . getField ( CalendarControl . ANNIV_BACK_DAYS ) . getValue ( ) ; int iRangeDays = ( int ) this . getField ( CalendarControl . ANNIVERSARY_DAYS ) . getValue ( ) ; Calendar calStart = ( Calendar ) calNow . clone ( ) ; calStart . add ( Calendar . DAY_OF_YEAR , - iBackDays ) ; Calendar calEnd = ( Calendar ) calStart . clone ( ) ; calEnd . add ( Calendar . DAY_OF_YEAR , iRangeDays - iBackDays ) ; Calendar calOldEnd = ( ( DateTimeField ) this . getField ( CalendarControl . END_ANNIV_DATE ) ) . getCalendar ( ) ; if ( calOldEnd == null ) calOldEnd = calNow ; ( ( DateTimeField ) this . getField ( CalendarControl . START_ANNIV_DATE ) ) . setCalendar ( calStart , true , DBConstants . SCREEN_MOVE ) ; ( ( DateTimeField ) this . getField ( CalendarControl . END_ANNIV_DATE ) ) . setCalendar ( calEnd , true , DBConstants . SCREEN_MOVE ) ; ( ( DateTimeField ) this . getField ( CalendarControl . LAST_UPDATE_DATE ) ) . setCalendar ( calNow , true , DBConstants . SCREEN_MOVE ) ; this . updateCalendar ( calOldEnd , calEnd ) ; try { this . writeAndRefresh ( ) ; } catch ( DBException ex ) { ex . printStackTrace ( ) ; } } }
UpdateDatesAndCalendar Method .
16,250
public void updateCalendar ( Calendar calStart , Calendar calEnd ) { Anniversary recAnniversary = new Anniversary ( this . getRecordOwner ( ) ) ; AnnivMaster recAnnivMaster = new AnnivMaster ( this . getRecordOwner ( ) ) ; recAnniversary . setKeyArea ( Anniversary . START_DATE_TIME_KEY ) ; try { while ( recAnniversary . hasNext ( ) ) { recAnniversary . next ( ) ; if ( recAnniversary . getField ( Anniversary . START_DATE_TIME ) . compareTo ( this . getField ( CalendarControl . START_ANNIV_DATE ) ) > 0 ) break ; recAnniversary . edit ( ) ; recAnniversary . remove ( ) ; } while ( recAnnivMaster . hasNext ( ) ) { recAnnivMaster . next ( ) ; recAnnivMaster . addAppointments ( recAnniversary , calStart , calEnd ) ; } } catch ( DBException ex ) { ex . printStackTrace ( ) ; } finally { recAnniversary . free ( ) ; recAnnivMaster . free ( ) ; } }
UpdateCalendar Method .
16,251
public BaseMessageFilter createDefaultFilter ( JMessageListener listener ) { BaseMessageFilter messageFilter = null ; String strQueueName = MessageConstants . RECORD_QUEUE_NAME ; String strQueueType = MessageConstants . INTRANET_QUEUE ; if ( m_baseMessageQueue != null ) { strQueueName = m_baseMessageQueue . getQueueName ( ) ; strQueueType = m_baseMessageQueue . getQueueType ( ) ; } messageFilter = new BaseMessageFilter ( strQueueName , strQueueType , null , null ) ; messageFilter . addMessageListener ( listener ) ; return messageFilter ; }
Create a message filter that will send all messages to this listener .
16,252
public void run ( ) { m_thread = this ; while ( m_thread != null ) { int iErrorCode = Constant . NORMAL_RETURN ; BaseMessage message = ( BaseMessage ) this . receiveMessage ( ) ; if ( ( message == null ) || ( m_thread == null ) ) return ; Iterator < BaseMessageFilter > iterator = this . getFilterList ( message . getMessageHeader ( ) ) ; while ( iterator . hasNext ( ) ) { if ( message . isConsumed ( ) ) break ; try { BaseMessageFilter filter = iterator . next ( ) ; if ( filter . isFilterMatch ( message . getMessageHeader ( ) ) ) { BaseMessage messageToSend = message ; for ( int i = 0 ; ; i ++ ) { JMessageListener listener = filter . getMessageListener ( i ) ; if ( listener == null ) break ; if ( filter . isThinTarget ( ) ) if ( listener . isThinListener ( ) ) { if ( messageToSend == message ) messageToSend = message . convertToThinMessage ( ) ; else messageToSend = messageToSend . convertToThinMessage ( ) ; } if ( listener instanceof org . jbundle . model . Remote ) if ( filter . getRegistryID ( ) != null ) if ( messageToSend . getMessageHeader ( ) != null ) if ( messageToSend . getMessageHeader ( ) . getRegistryIDMatch ( ) == null ) { try { if ( messageToSend == message ) messageToSend = ( BaseMessage ) messageToSend . clone ( ) ; } catch ( CloneNotSupportedException e ) { e . printStackTrace ( ) ; } messageToSend . getMessageHeader ( ) . setRegistryIDMatch ( filter . getRegistryID ( ) ) ; } iErrorCode = listener . handleMessage ( messageToSend ) ; if ( iErrorCode != Constant . NORMAL_RETURN ) break ; message . setConsumed ( messageToSend . isConsumed ( ) ) ; if ( message . isConsumed ( ) ) break ; } } } catch ( ConcurrentModificationException ex ) { Util . getLogger ( ) . warning ( "Message filter Concurrent Modification" ) ; iterator = this . getFilterList ( message . getMessageHeader ( ) ) ; } } } }
Start running this thread . This method hangs on receiveMessage then processes the message if it matches the filter and continues with the next message .
16,253
public Set < String > getUnclaimed ( ) { synchronized ( cluster . allWorkUnits ) { LinkedHashSet < String > result = new LinkedHashSet < String > ( cluster . allWorkUnits . keySet ( ) ) ; result . removeAll ( cluster . workUnitMap . keySet ( ) ) ; result . addAll ( cluster . getHandoffWorkUnits ( ) ) ; result . removeAll ( cluster . getHandoffResultWorkUnits ( ) ) ; result . removeAll ( cluster . myWorkUnits ) ; return result ; } }
Returns a set of work units which are unclaimed throughout the cluster .
16,254
public boolean isFairGame ( String workUnit ) { ObjectNode workUnitData = cluster . allWorkUnits . get ( workUnit ) ; if ( workUnitData == null || workUnitData . size ( ) == 0 ) { return true ; } try { JsonNode pegged = workUnitData . get ( cluster . name ) ; if ( pegged == null ) { return true ; } LOG . debug ( "Pegged status for {}: {}." , workUnit , pegged ) ; return pegged . asText ( ) . equals ( cluster . myNodeID ) ; } catch ( Exception e ) { LOG . error ( String . format ( "Error parsing mapping for %s: %s" , workUnit , workUnitData ) , e ) ; return true ; } }
Determines whether or not a given work unit is designated claimable by this node . If the ZNode for this work unit is empty or contains JSON mapping this node to that work unit it s considered claimable .
16,255
public boolean isPeggedToMe ( String workUnitId ) { ObjectNode zkWorkData = cluster . allWorkUnits . get ( workUnitId ) ; if ( zkWorkData == null || zkWorkData . size ( ) == 0 ) { cluster . workUnitsPeggedToMe . remove ( workUnitId ) ; return false ; } try { JsonNode pegged = zkWorkData . get ( cluster . name ) ; final boolean isPegged = ( pegged != null ) && pegged . asText ( ) . equals ( cluster . myNodeID ) ; if ( isPegged ) { cluster . workUnitsPeggedToMe . add ( workUnitId ) ; } else { cluster . workUnitsPeggedToMe . remove ( workUnitId ) ; } return isPegged ; } catch ( Exception e ) { LOG . error ( String . format ( "Error parsing mapping for %s: %s" , workUnitId , zkWorkData ) , e ) ; return false ; } }
Determines whether or not a given work unit is pegged to this instance .
16,256
boolean attemptToClaim ( String workUnit , boolean claimForHandoff ) throws InterruptedException { LOG . debug ( "Attempting to claim {}. For handoff? {}" , workUnit , claimForHandoff ) ; String path = claimForHandoff ? String . format ( "/%s/handoff-result/%s" , cluster . name , workUnit ) : cluster . workUnitClaimPath ( workUnit ) ; final boolean created = ZKUtils . createEphemeral ( cluster . zk , path , cluster . myNodeID ) ; if ( created ) { if ( claimForHandoff ) { cluster . claimedForHandoff . add ( workUnit ) ; } cluster . startWork ( workUnit ) ; return true ; } if ( isPeggedToMe ( workUnit ) ) { claimWorkPeggedToMe ( workUnit ) ; return true ; } return false ; }
Attempts to claim a given work unit by creating an ephemeral node in ZooKeeper with this node s ID . If the claim succeeds start work . If not move on .
16,257
protected void drainToCount ( final int targetCount , final boolean doShutdown , final boolean useHandoff , final CountDownLatch latch ) { String msg = useHandoff ? " with handoff" : "" ; LOG . info ( String . format ( "Draining %s%s. Target count: %s, Current: %s" , config . workUnitName , msg , targetCount , cluster . myWorkUnits . size ( ) ) ) ; if ( targetCount >= cluster . myWorkUnits . size ( ) ) { if ( ! doShutdown ) { return ; } } else if ( targetCount == 0 && doShutdown ) { cluster . completeShutdown ( ) ; } final int amountToDrain = cluster . myWorkUnits . size ( ) - targetCount ; String msgPrefix = ( useHandoff ) ? "Requesting handoff for" : "Shutting down" ; LOG . info ( "{} {} of {} {} over {} seconds" , msgPrefix , amountToDrain , cluster . myWorkUnits . size ( ) , config . workUnitName , config . drainTime ) ; LinkedHashSet < String > wuList = new LinkedHashSet < String > ( cluster . myWorkUnits ) ; wuList . removeAll ( cluster . workUnitsPeggedToMe ) ; final ArrayList < String > toHandOff = new ArrayList < String > ( ) ; Iterator < String > it = wuList . iterator ( ) ; for ( int i = amountToDrain ; it . hasNext ( ) && i > 0 ; -- i ) { toHandOff . add ( it . next ( ) ) ; } final int drainInterval = ( int ) ( ( ( double ) config . drainTime / ( double ) toHandOff . size ( ) ) * 1000 ) ; final Iterator < String > drainIt = toHandOff . iterator ( ) ; TimerTask handoffTask = new TimerTask ( ) { public void run ( ) { if ( ! drainIt . hasNext ( ) ) { if ( targetCount == 0 && doShutdown ) { cluster . completeShutdown ( ) ; } if ( latch != null ) { latch . countDown ( ) ; } return ; } String workUnit = drainIt . next ( ) ; if ( useHandoff && ! isPeggedToMe ( workUnit ) ) { try { cluster . requestHandoff ( workUnit ) ; } catch ( Exception e ) { LOG . warn ( "Problems trying to request handoff of " + workUnit , e ) ; } } else { cluster . shutdownWork ( workUnit , true ) ; } cluster . schedule ( this , drainInterval , TimeUnit . MILLISECONDS ) ; } } ; LOG . info ( "Releasing {} / {} work units over {} seconds: {}" , amountToDrain , cluster . myWorkUnits . size ( ) , config . drainTime , Strings . mkstring ( toHandOff , ", " ) ) ; if ( ! cluster . myWorkUnits . isEmpty ( ) ) { cluster . schedule ( handoffTask , 0 , TimeUnit . SECONDS ) ; } }
Drains this node s share of the cluster workload down to a specific number of work units over a period of time specified in the configuration with soft handoff if enabled ..
16,258
public void runCalendarEntry ( Map < String , Object > properties ) { ProcessRunnerTask task = new ProcessRunnerTask ( null , null , properties ) ; ( ( Application ) this . getTask ( ) . getApplication ( ) ) . getTaskScheduler ( ) . addTask ( task ) ; }
RunCalendarEntry Method .
16,259
public String getNewCalendarPath ( File file ) { StringTokenizer st = new StringTokenizer ( file . getName ( ) ) ; int iPlace = 0 , iMonth = 0 , iYear = 0 ; while ( st . hasMoreTokens ( ) ) { String strToken = st . nextToken ( ) ; if ( strToken . length ( ) > 2 ) break ; if ( ! Utility . isNumeric ( strToken ) ) break ; if ( strToken . indexOf ( '.' ) != - 1 ) break ; int iNumber = Integer . parseInt ( strToken ) ; iPlace ++ ; if ( iPlace == 1 ) { if ( ( iNumber < 1 ) || ( iNumber > 12 ) ) break ; iMonth = iNumber ; } else if ( iPlace == 2 ) { if ( ( iNumber < 1 ) || ( iNumber > 31 ) ) break ; } else if ( iPlace == 3 ) { if ( ( iNumber < 1 ) || ( iNumber > 2020 ) ) break ; iYear = iNumber ; if ( iYear <= 20 ) iYear = iYear + 2000 ; return Integer . toString ( iYear ) + '/' + m_rgstrMonths [ iMonth - 1 ] ; } } return null ; }
GetNewCalendarPath Method .
16,260
public ContactType getContactType ( Person recPerson ) { if ( m_recContactType == null ) { m_recContactType = ( ContactType ) Record . makeRecordFromClassName ( ContactTypeModel . CONTACT_TYPE_FILE , this . getOwner ( ) . getRecord ( ) . findRecordOwner ( ) ) ; if ( ( ( Record ) m_recContactType ) . getRecordOwner ( ) != null ) ( ( Record ) m_recContactType ) . getRecordOwner ( ) . removeRecord ( ( Record ) m_recContactType ) ; } return m_recContactType . getContactType ( recPerson ) ; }
GetContactType Method .
16,261
public void init ( BaseSession parentSessionObject , Record record , Map < String , Object > objectID ) { if ( m_application == null ) m_application = new MainApplication ( null , null , null ) ; this . addToApplication ( ) ; super . init ( parentSessionObject , record , objectID ) ; }
Build a new task session .
16,262
public void removeFromApplication ( boolean bFreeIfDone ) { if ( m_application == null ) return ; Application app = m_application ; m_application = null ; boolean bEmptyTaskList = app . removeTask ( this ) ; if ( bFreeIfDone ) if ( bEmptyTaskList ) app . free ( ) ; }
Remove this task or session to my parent application .
16,263
public Convert getFieldInfo ( int iColumnIndex ) { Converter converter = m_table . getRecord ( ) . getField ( iColumnIndex ) ; if ( converter != null ) converter = converter . getFieldConverter ( ) ; return converter ; }
Returns the field at columnIndex . This should be overidden if don t want to just return the corresponding field in the record .
16,264
public String getColumnName ( int iColumnIndex ) { Convert fieldInfo = this . getFieldInfo ( iColumnIndex ) ; if ( fieldInfo != null ) return fieldInfo . getFieldDesc ( ) ; return Constants . BLANK ; }
Returns the name of the column at columnIndex .
16,265
public Iterator < String > keySet ( ) { Node node = getNode ( true ) ; NodeList nodeList = node . getChildNodes ( ) ; return new NodeIterator ( nodeList ) ; }
Get a Iterator of the keys in this message .
16,266
public int getNodeCount ( String strKey ) { int iCount = 0 ; Node node = this . getNode ( null , strKey , CreateMode . DONT_CREATE , false ) ; if ( node != null ) { String key = strKey ; if ( key . lastIndexOf ( '/' ) != - 1 ) key = key . substring ( key . lastIndexOf ( '/' ) + 1 ) ; Node nodeStart = node . getParentNode ( ) ; NodeList nodeList = ( ( Element ) nodeStart ) . getElementsByTagName ( key ) ; if ( nodeList != null ) { for ( int i = 0 ; i < nodeList . getLength ( ) ; i ++ ) { if ( nodeList . item ( i ) . getParentNode ( ) == nodeStart ) iCount ++ ; } } } return iCount ; }
Get the number of data nodes at this path in the data .
16,267
public void start ( boolean isDaemon ) { synchronized ( this ) { if ( ! isUsed ) { isUsed = true ; isRunning = true ; Thread thread = new Thread ( new RunnableImpl ( ) ) ; thread . setDaemon ( isDaemon ) ; thread . start ( ) ; } else { throw new IllegalStateException ( "Async runner has been already used once." ) ; } } }
Starts processing the items queue . This method can be called only once .
16,268
public void addItems ( Iterable < T > items ) { synchronized ( this ) { for ( T i : items ) { this . items . add ( i ) ; } semaphore . release ( ) ; } }
Adds multiple items to the processing queue . Can be called even before the start . This method is preferred to calling addItem multiple times in row because it will make synchronization only once .
16,269
public static String extractSqlColumns ( final String [ ] headers ) { final StringBuffer sqlColumns = new StringBuffer ( ) ; sqlColumns . append ( "" ) ; for ( int i = 0 ; i < headers . length ; i ++ ) { sqlColumns . append ( headers [ i ] ) ; if ( i < headers . length - 1 ) { sqlColumns . append ( ", " ) ; } else { sqlColumns . append ( "" ) ; } } return sqlColumns . toString ( ) ; }
Extract sql columns .
16,270
public static String reindentGameDescription ( String gameRules ) throws Exception { List < Symbol > tokens = ParserHelper . scan ( gameRules , true ) ; tokens = collapseWhitespaceTokens ( tokens ) ; StringBuilder result = new StringBuilder ( ) ; int parensLevel = 0 ; int nestingLevel = 0 ; for ( int i = 0 ; i < tokens . size ( ) ; i ++ ) { Symbol token = tokens . get ( i ) ; switch ( token . sym ) { case Symbols . CONSTANT : case Symbols . VARIABLE : result . append ( token . value ) ; break ; case Symbols . POPEN : result . append ( "(" ) ; parensLevel ++ ; break ; case Symbols . PCLOSE : result . append ( ")" ) ; if ( parensLevel > 0 ) { parensLevel -- ; } if ( nestingLevel > parensLevel ) { nestingLevel = parensLevel ; } break ; case Symbols . IMPLIES : result . append ( "<=" ) ; nestingLevel ++ ; break ; case Symbols . NOT : result . append ( "not" ) ; break ; case Symbols . DISTINCT : result . append ( "distinct" ) ; break ; case Symbols . OR : result . append ( "or" ) ; nestingLevel ++ ; break ; case Symbols . EOF : break ; case Symbols2 . COMMENT : result . append ( token . value ) ; break ; case Symbols2 . WHITESPACE : result . append ( rewriteWhitespace ( ( String ) token . value , tokens , i , parensLevel , nestingLevel ) ) ; break ; } } return result . toString ( ) ; }
Returns null if the indentation fails .
16,271
public Record getReferenceRecord ( ) { Record recordReference = this . getReferenceRecord ( null ) ; if ( recordReference != null ) if ( recordReference . getRecordOwner ( ) == null ) { RecordOwner recordOwner = null ; if ( this . getRecord ( ) != null ) recordOwner = Record . findRecordOwner ( this . getRecord ( ) ) ; if ( recordOwner != null ) recordOwner . addRecord ( recordReference , false ) ; if ( this . getRecord ( ) != null ) { FreeOnFreeHandler listener = ( FreeOnFreeHandler ) this . getRecord ( ) . getListener ( FreeOnFreeHandler . class ) ; while ( listener != null ) { if ( listener . getDependentObject ( ) == recordReference ) break ; listener = ( FreeOnFreeHandler ) listener . getListener ( FreeOnFreeHandler . class ) ; } if ( listener == null ) this . getRecord ( ) . addListener ( new FreeOnFreeHandler ( recordReference ) ) ; } } return recordReference ; }
Get the record that this field references . This is the default method so if a record by this name doesn t belong to this screen add this one!
16,272
public Record getReferenceRecord ( RecordOwner screen , boolean bCreateIfNotFound ) { if ( ( m_recordReference == null ) && ( bCreateIfNotFound ) ) { RecordOwner recordOwner = screen ; if ( recordOwner == null ) if ( this . getRecord ( ) != null ) recordOwner = Record . findRecordOwner ( this . getRecord ( ) ) ; this . setReferenceRecord ( this . makeReferenceRecord ( recordOwner ) ) ; if ( m_recordReference != null ) { m_recordReference . setOpenMode ( m_recordReference . getOpenMode ( ) | DBConstants . OPEN_READ_ONLY ) ; if ( screen == null ) if ( recordOwner != null ) { recordOwner . removeRecord ( m_recordReference ) ; if ( this . getRecord ( ) != null ) { FreeOnFreeHandler listener = ( FreeOnFreeHandler ) this . getRecord ( ) . getListener ( FreeOnFreeHandler . class ) ; while ( listener != null ) { if ( listener . getDependentObject ( ) == m_recordReference ) break ; listener = ( FreeOnFreeHandler ) listener . getListener ( FreeOnFreeHandler . class ) ; } if ( listener == null ) this . getRecord ( ) . addListener ( new FreeOnFreeHandler ( m_recordReference ) ) ; } } } } else if ( ( m_recordReference != null ) && ( m_recordReference . getRecordOwner ( ) == null ) && ( screen != null ) ) { screen . addRecord ( m_recordReference , false ) ; m_recordReference . setRecordOwner ( screen ) ; } return m_recordReference ; }
Get the record that this field references .
16,273
public void setReferenceRecord ( Record record ) { if ( m_recordReference != record ) { if ( m_recordReference != null ) { if ( this . getRecord ( ) != null ) { FreeOnFreeHandler freeListener = ( FreeOnFreeHandler ) this . getRecord ( ) . getListener ( FreeOnFreeHandler . class ) ; while ( freeListener != null ) { if ( freeListener . getDependentObject ( ) == m_recordReference ) { freeListener . setDependentObject ( null ) ; this . getRecord ( ) . removeListener ( freeListener , true ) ; break ; } freeListener = ( FreeOnFreeHandler ) freeListener . getListener ( FreeOnFreeHandler . class ) ; } } ClearFieldReferenceOnCloseHandler listener = ( ClearFieldReferenceOnCloseHandler ) m_recordReference . getListener ( ClearFieldReferenceOnCloseHandler . class . getName ( ) ) ; while ( listener != null ) { if ( listener . getField ( ) == this ) { Record recordTemp = m_recordReference ; m_recordReference = null ; recordTemp . removeListener ( listener , true ) ; listener = null ; } else listener = ( ClearFieldReferenceOnCloseHandler ) listener . getListener ( ClearFieldReferenceOnCloseHandler . class . getName ( ) ) ; } } if ( record != null ) { record . addListener ( new ClearFieldReferenceOnCloseHandler ( this ) ) ; } m_recordReference = record ; } }
Set the record that this field references .
16,274
public void init ( File jsonFile ) throws SubscriberException { try { setConfig ( new JsonSimpleConfig ( jsonFile ) ) ; } catch ( IOException ioe ) { throw new SubscriberException ( ioe ) ; } }
Initializes the plugin using the specified JSON configuration
16,275
private void setConfig ( JsonSimpleConfig config ) throws SubscriberException { try { uri = new URI ( config . getString ( null , "subscriber" , getId ( ) , "uri" ) ) ; if ( uri == null ) { throw new SubscriberException ( "No Solr URI provided" ) ; } core = new CommonsHttpSolrServer ( uri . toURL ( ) ) ; boolean serverOnline = false ; int retryCount = 0 ; while ( ! serverOnline ) { Thread . sleep ( 200 ) ; try { core . ping ( ) ; serverOnline = true ; } catch ( Exception ex ) { retryCount ++ ; log . error ( "Server not yet online. Attempt: " + retryCount + " of " + SOLR_SERVER_RETRY_COUNT , ex ) ; if ( retryCount == SOLR_SERVER_RETRY_COUNT ) { throw ex ; } } } docBuffer = new ArrayList < String > ( ) ; bufferSize = 0 ; bufferOldest = 0 ; bufferDocLimit = config . getInteger ( BUFFER_LIMIT_DOCS , "subscriber" , getId ( ) , "buffer" , "docLimit" ) ; bufferSizeLimit = config . getInteger ( BUFFER_LIMIT_SIZE , "subscriber" , getId ( ) , "buffer" , "sizeLimit" ) ; bufferTimeLimit = config . getInteger ( BUFFER_LIMIT_TIME , "subscriber" , getId ( ) , "buffer" , "timeLimit" ) ; timer = new Timer ( "SolrEventLog:" + this . toString ( ) , true ) ; timer . scheduleAtFixedRate ( new TimerTask ( ) { public void run ( ) { checkTimeout ( ) ; } } , 0 , 10000 ) ; } catch ( Exception ex ) { throw new SubscriberException ( ex ) ; } }
Initialization of Solr Access Control plugin
16,276
private void checkBuffer ( ) { if ( docBuffer . size ( ) >= bufferDocLimit ) { log . debug ( "=== Buffer check: Doc limit reached '{}'" , docBuffer . size ( ) ) ; submitBuffer ( false ) ; return ; } if ( bufferSize > bufferSizeLimit ) { log . debug ( "=== Buffer check: Size exceeded '{}'" , bufferSize ) ; submitBuffer ( false ) ; return ; } long age = ( ( new Date ( ) . getTime ( ) ) - bufferOldest ) / 1000 ; if ( age > bufferTimeLimit ) { log . debug ( "=== Buffer check: Age exceeded '{}s'" , age ) ; submitBuffer ( false ) ; return ; } }
Assess the document buffer and decide is it is ready to submit
16,277
private void addToIndex ( Map < String , String > param ) throws Exception { String doc = writeUpdateString ( param ) ; addToBuffer ( doc ) ; }
Add the event to the index
16,278
private String writeUpdateString ( Map < String , String > param ) { StringBuffer fieldStringBuffer = new StringBuffer ( ) ; for ( Entry < String , String > entry : param . entrySet ( ) ) { fieldStringBuffer . append ( "<field name=\"" ) . append ( entry . getKey ( ) ) . append ( "\">" ) . append ( StringEscapeUtils . escapeXml ( entry . getValue ( ) ) ) . append ( "</field>" ) ; } fieldStringBuffer . insert ( 0 , "<add><doc>" ) . append ( "</doc></add>" ) ; return fieldStringBuffer . toString ( ) ; }
Turn a a message into a Solr document
16,279
public void onEvent ( Map < String , String > param ) throws SubscriberException { try { addToIndex ( param ) ; } catch ( Exception e ) { throw new SubscriberException ( "Fail to add log to solr" + e . getMessage ( ) ) ; } }
Method to fire for incoming events
16,280
public Iterator < T > iterator ( ) { writeLock . lock ( ) ; if ( iterator == null ) { iterator = new Iter ( ) ; } else { iterator . reset ( ) ; } return iterator ; }
Returned iterator is write - locked until hasNext returns false or unlock method is called .
16,281
public void printHtmlData ( PrintWriter out , InputStream streamIn ) { String str = null ; if ( streamIn != null ) str = Utility . transferURLStream ( null , null , new InputStreamReader ( streamIn ) ) ; if ( ( str == null ) || ( str . length ( ) == 0 ) ) str = this . getDefaultXML ( ) ; this . parseHtmlData ( out , str ) ; }
Output this screen using HTML . Override this to print your XML .
16,282
public String getTagData ( String strData , String strTag ) { int iStartData = strData . indexOf ( '<' + strTag + '>' ) ; if ( iStartData == - 1 ) return null ; iStartData = iStartData + strTag . length ( ) + 2 ; int iEndData = strData . indexOf ( "</" + strTag + '>' ) ; if ( iStartData == - 1 ) return null ; return strData . substring ( iStartData , iEndData ) ; }
Find the data between these XML tags .
16,283
public String getProperty ( String strProperty , String strParams ) { String strValue = null ; strValue = this . parseArg ( strProperty , strParams ) ; if ( strValue == null ) strValue = this . getRecordOwner ( ) . getProperty ( strProperty ) ; return strValue ; }
Get this property . First see if it s in the param tag then work your way up the hierarchy .
16,284
public String parseArg ( String strProperty , String strURL ) { if ( ( strURL == null ) || ( strProperty == null ) ) return null ; int iStartIndex = strURL . toUpperCase ( ) . indexOf ( strProperty . toUpperCase ( ) + '=' ) ; if ( iStartIndex == - 1 ) return null ; iStartIndex = iStartIndex + strProperty . length ( ) + 1 ; if ( iStartIndex < strURL . length ( ) ) if ( strURL . charAt ( iStartIndex ) == '\"' ) iStartIndex ++ ; int iEndIndex = strURL . indexOf ( ' ' , iStartIndex ) ; if ( iEndIndex == - 1 ) iEndIndex = strURL . length ( ) ; if ( strURL . charAt ( iEndIndex - 1 ) == '\"' ) iEndIndex -- ; return strURL . substring ( iStartIndex , iEndIndex ) ; }
Parse this URL formatted string into properties .
16,285
public static < E extends Comparable < E > > void sort ( List < E > list ) { boolean swapped = true ; while ( swapped ) { swapped = false ; for ( int i = 0 ; i < ( list . size ( ) - 1 ) ; i ++ ) { if ( list . get ( i ) . compareTo ( list . get ( i + 1 ) ) > 0 ) { TrivialSwap . swap ( list , i , i + 1 ) ; swapped = true ; } } } }
Sort the list in ascending order using this algorithm . The run time of this algorithm depends on the implementation of the list since it has elements added and removed from it .
16,286
public boolean offer ( T t ) { try { return queue . offer ( t , offerTimeout , timeUnit ) ; } catch ( InterruptedException ex ) { throw new IllegalArgumentException ( ex ) ; } }
Offers new item . Return true if item was consumed . False if another thread was not waiting for the item .
16,287
public Optional < ZipErrorCodes > zip ( ) { try ( FileOutputStream fos = new FileOutputStream ( this . zipFile ) ; ZipOutputStream zos = new ZipOutputStream ( fos ) ; ) { if ( ! this . directoryToZip . exists ( ) ) { return Optional . of ( ZipErrorCodes . DIRECTORY_TO_ZIP_DOES_NOT_EXIST ) ; } if ( ! this . zipFile . exists ( ) ) { return Optional . of ( ZipErrorCodes . ZIP_FILE_DOES_NOT_EXIST ) ; } if ( 0 < this . zipLevel ) { zos . setLevel ( this . zipLevel ) ; } else { zos . setLevel ( 9 ) ; } if ( null != this . zipFileComment ) { zos . setComment ( this . zipFileComment ) ; } if ( 0 < this . compressionMethod ) { zos . setMethod ( this . compressionMethod ) ; } this . zipFiles ( this . directoryToZip , zos ) ; zos . flush ( ) ; zos . finish ( ) ; fos . flush ( ) ; } catch ( IOException e ) { log . log ( Level . SEVERE , e . getLocalizedMessage ( ) , e ) ; return Optional . of ( ZipErrorCodes . IO_ERROR ) ; } return Optional . empty ( ) ; }
Zip the given files of this objects
16,288
protected boolean setConnector ( ) { if ( this . host == null ) { log . error ( "No host value set, cannot set up socket connector." ) ; return false ; } if ( this . port < 0 || this . port > 65535 ) { log . error ( "Port value is invalid {}." , Integer . valueOf ( this . port ) ) ; return false ; } if ( this . executors == null ) { this . executors = new ExecutorFilter ( 1 ) ; } this . connector = new NioSocketConnector ( ) ; this . connector . getSessionConfig ( ) . setWriterIdleTime ( SolverWorldModelInterface . TIMEOUT_PERIOD / 2 ) ; this . connector . getSessionConfig ( ) . setReaderIdleTime ( ( int ) Math . ceil ( TIMEOUT_PERIOD * 1.1 ) ) ; if ( ! this . connector . getFilterChain ( ) . contains ( WorldModelSolverProtocolCodecFactory . CODEC_NAME ) ) { this . connector . getFilterChain ( ) . addLast ( WorldModelSolverProtocolCodecFactory . CODEC_NAME , new ProtocolCodecFilter ( new WorldModelSolverProtocolCodecFactory ( true ) ) ) ; } this . connector . getFilterChain ( ) . addLast ( "ExecutorPool" , this . executors ) ; this . connector . setHandler ( this . ioHandler ) ; log . debug ( "Connector set up successful." ) ; return true ; }
Sets the MINA connector and establishes the connection to the world model . Adds protocol filters .
16,289
protected void announceAttributes ( ) { if ( this . originString == null ) { log . error ( "Unable to announce solution types, no Origin String set." ) ; return ; } this . sentAttrSpecifications = true ; if ( this . attributes . size ( ) > 0 ) { AttributeAnnounceMessage message = new AttributeAnnounceMessage ( ) ; message . setOrigin ( this . originString ) ; ArrayList < AttributeSpecification > specificationList = new ArrayList < AttributeSpecification > ( ) ; specificationList . addAll ( this . attributes ) ; AttributeSpecification [ ] specs = new AttributeSpecification [ specificationList . size ( ) ] ; int specAlias = 0 ; for ( AttributeSpecification spec : specificationList ) { specs [ specAlias ] = spec ; spec . setAlias ( specAlias ++ ) ; this . attributeAliases . put ( spec . getAttributeName ( ) , Integer . valueOf ( spec . getAlias ( ) ) ) ; } message . setTypeSpecifications ( specs ) ; this . session . write ( message ) ; this . sentAttrSpecifications = true ; } }
Sends the Attribute aliases to the world model .
16,290
public boolean updateAttribute ( final Attribute attribute ) { if ( ! this . sentAttrSpecifications ) { log . error ( "Haven't sent type specifications yet, can't send solutions." ) ; return false ; } AttributeUpdateMessage message = new AttributeUpdateMessage ( ) ; message . setCreateId ( this . createIds ) ; message . setAttributes ( new Attribute [ ] { attribute } ) ; Integer attributeAlias = this . attributeAliases . get ( attribute . getAttributeName ( ) ) ; if ( attributeAlias == null ) { log . error ( "Cannot update attribute: Unregistered attribute type: {}" , attribute . getAttributeName ( ) ) ; return false ; } attribute . setAttributeNameAlias ( attributeAlias . intValue ( ) ) ; this . session . write ( message ) ; log . debug ( "Sent {} to {}" , message , this ) ; return true ; }
Sends a single Attribute update message to the world model .
16,291
public boolean updateAttributes ( final Collection < Attribute > attrToSend ) { if ( ! this . sentAttrSpecifications ) { log . error ( "Haven't sent type specifications yet, can't send solutions." ) ; return false ; } for ( Iterator < Attribute > iter = attrToSend . iterator ( ) ; iter . hasNext ( ) ; ) { Attribute soln = iter . next ( ) ; Integer solutionTypeAlias = this . attributeAliases . get ( soln . getAttributeName ( ) ) ; if ( solutionTypeAlias == null ) { log . error ( "Cannot send solution: Unregistered attribute type: {}" , soln . getAttributeName ( ) ) ; iter . remove ( ) ; continue ; } soln . setAttributeNameAlias ( solutionTypeAlias . intValue ( ) ) ; } AttributeUpdateMessage message = new AttributeUpdateMessage ( ) ; message . setCreateId ( this . createIds ) ; message . setAttributes ( attrToSend . toArray ( new Attribute [ ] { } ) ) ; this . session . write ( message ) ; log . debug ( "Sent {} to {}" , message , this ) ; return true ; }
Sends a multiple Attribute update messages to the world model .
16,292
public void addAttribute ( AttributeSpecification specification ) { synchronized ( this . attributes ) { if ( ! this . attributes . contains ( specification ) ) { this . attributes . add ( specification ) ; if ( this . sentAttrSpecifications ) { this . announceAttributes ( ) ; } } } }
Adds an attribute specification to the world model session .
16,293
public void setOriginString ( String originString ) { this . originString = originString ; if ( this . sentAttrSpecifications ) { AttributeAnnounceMessage msg = new AttributeAnnounceMessage ( ) ; msg . setOrigin ( originString ) ; this . session . write ( msg ) ; } }
Sets the origin value for this connection .
16,294
public boolean expireId ( final String identifier , final long expirationTime ) { if ( identifier == null ) { log . error ( "Unable to expire a null Identifier value." ) ; return false ; } if ( this . originString == null ) { log . error ( "Origin has not been set. Cannot expire Ids without a valid origin." ) ; return false ; } ExpireIdentifierMessage message = new ExpireIdentifierMessage ( ) ; message . setOrigin ( this . originString ) ; message . setId ( identifier ) ; message . setExpirationTime ( expirationTime ) ; this . session . write ( message ) ; log . debug ( "Sent {}" , message ) ; return true ; }
Expires all Attributes for an Identifier in the world model .
16,295
public boolean expireAttribute ( final String identifier , final String attribute , final long expirationTime ) { if ( identifier == null ) { log . error ( "Unable to expire an attribute with a null Identifier value." ) ; return false ; } if ( attribute == null ) { log . error ( "Unable to expire a null attribute." ) ; return false ; } if ( this . originString == null ) { log . error ( "Origin has not been set. Cannot expire attributes without a valid origin." ) ; return false ; } ExpireAttributeMessage message = new ExpireAttributeMessage ( ) ; message . setId ( identifier ) ; message . setAttributeName ( attribute ) ; message . setExpirationTime ( expirationTime ) ; message . setOrigin ( this . originString ) ; this . session . write ( message ) ; log . debug ( "Sent {}" , message ) ; return true ; }
Expire a particular Attribute for an Identifier in the world model .
16,296
public boolean deleteId ( final String identifier ) { if ( identifier == null ) { log . error ( "Unable to delete a null Identifier value." ) ; return false ; } if ( this . originString == null ) { log . error ( "Origin has not been set. Cannot delete Identifiers without a valid origin." ) ; return false ; } DeleteIdentifierMessage message = new DeleteIdentifierMessage ( ) ; message . setOrigin ( this . originString ) ; message . setId ( identifier ) ; this . session . write ( message ) ; log . debug ( "Sent {}" , message ) ; return true ; }
Deletes an Identifier and all of its Attributes from the world model . All data for the Identifier will be removed permanently . Callers may also wish to consider expiring the Identifier instead .
16,297
public boolean deleteAttribute ( final String identifier , final String attribute ) { if ( identifier == null ) { log . error ( "Unable to delete an attribute with a null Identifier value." ) ; return false ; } if ( attribute == null ) { log . error ( "Unable to delete a null attribute." ) ; return false ; } if ( this . originString == null ) { log . error ( "Origin has not been set. Cannot delete attributes without a valid origin." ) ; return false ; } DeleteAttributeMessage message = new DeleteAttributeMessage ( ) ; message . setOrigin ( this . originString ) ; message . setId ( identifier ) ; message . setAttributeName ( attribute ) ; this . session . write ( message ) ; log . debug ( "Sent {}" , message ) ; return true ; }
Deletes an Attribute and its entire history from the world model . Callers may wish to expire the Attribute value instead .
16,298
public boolean createId ( final String identifier ) { if ( identifier == null ) { log . error ( "Unable to create a null Identifier." ) ; return false ; } if ( this . originString == null ) { log . error ( "Origin has not been set. Cannot create Identifiers without a valid origin." ) ; return false ; } CreateIdentifierMessage message = new CreateIdentifierMessage ( ) ; message . setCreationTime ( System . currentTimeMillis ( ) ) ; message . setOrigin ( this . originString ) ; message . setId ( identifier ) ; this . session . write ( message ) ; log . debug ( "Sent {}" , message ) ; return true ; }
Creates a new Identifier in the world model .
16,299
public AbstractThinTableModel getModel ( JTable table ) { AbstractThinTableModel model = null ; if ( table != null ) model = ( AbstractThinTableModel ) table . getModel ( ) ; return model ; }
Get the model in this screen s sub - screen . Override if the model is not in the sub - screen .