idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
19,800
public static boolean setEquals ( List < String > a , List < String > b ) { if ( a == null ) { a = new ArrayList < > ( ) ; } if ( b == null ) { b = new ArrayList < > ( ) ; } if ( a . size ( ) != b . size ( ) ) { return false ; } Collections . sort ( a ) ; Collections . sort ( b ) ; for ( int i = 0 ; i < a . size ( ) ; i ++ ) { if ( ! a . get ( i ) . equals ( b . get ( i ) ) ) { return false ; } } return true ; }
setEquals determines whether two string sets are identical .
19,801
boolean addPolicy ( String sec , String ptype , List < String > rule ) { boolean ruleAdded = model . addPolicy ( sec , ptype , rule ) ; if ( ! ruleAdded ) { return false ; } if ( adapter != null && autoSave ) { try { adapter . addPolicy ( sec , ptype , rule ) ; } catch ( Error e ) { if ( ! e . getMessage ( ) . equals ( "not implemented" ) ) { throw e ; } } if ( watcher != null ) { watcher . update ( ) ; } } return true ; }
addPolicy adds a rule to the current policy .
19,802
boolean removeFilteredPolicy ( String sec , String ptype , int fieldIndex , String ... fieldValues ) { boolean ruleRemoved = model . removeFilteredPolicy ( sec , ptype , fieldIndex , fieldValues ) ; if ( ! ruleRemoved ) { return false ; } if ( adapter != null && autoSave ) { try { adapter . removeFilteredPolicy ( sec , ptype , fieldIndex , fieldValues ) ; } catch ( Error e ) { if ( ! e . getMessage ( ) . equals ( "not implemented" ) ) { throw e ; } } if ( watcher != null ) { watcher . update ( ) ; } } return true ; }
removeFilteredPolicy removes rules based on field filters from the current policy .
19,803
public void loadPolicy ( Model model ) { if ( filePath . equals ( "" ) ) { return ; } loadPolicyFile ( model , Helper :: loadPolicyLine ) ; }
loadPolicy loads all policy rules from the storage .
19,804
public void savePolicy ( Model model ) { if ( filePath . equals ( "" ) ) { throw new Error ( "invalid file path, file path cannot be empty" ) ; } StringBuilder tmp = new StringBuilder ( ) ; for ( Map . Entry < String , Assertion > entry : model . model . get ( "p" ) . entrySet ( ) ) { String ptype = entry . getKey ( ) ; Assertion ast = entry . getValue ( ) ; for ( List < String > rule : ast . policy ) { tmp . append ( ptype + ", " ) ; tmp . append ( Util . arrayToString ( rule ) ) ; tmp . append ( "\n" ) ; } } for ( Map . Entry < String , Assertion > entry : model . model . get ( "g" ) . entrySet ( ) ) { String ptype = entry . getKey ( ) ; Assertion ast = entry . getValue ( ) ; for ( List < String > rule : ast . policy ) { tmp . append ( ptype + ", " ) ; tmp . append ( Util . arrayToString ( rule ) ) ; tmp . append ( "\n" ) ; } } savePolicyFile ( tmp . toString ( ) . trim ( ) ) ; }
savePolicy saves all policy rules to the storage .
19,805
public void addPolicy ( String sec , String ptype , List < String > rule ) { throw new Error ( "not implemented" ) ; }
addPolicy adds a policy rule to the storage .
19,806
public void removePolicy ( String sec , String ptype , List < String > rule ) { throw new Error ( "not implemented" ) ; }
removePolicy removes a policy rule from the storage .
19,807
public void removeFilteredPolicy ( String sec , String ptype , int fieldIndex , String ... fieldValues ) { throw new Error ( "not implemented" ) ; }
removeFilteredPolicy removes policy rules that match the filter from the storage .
19,808
public static FunctionMap loadFunctionMap ( ) { FunctionMap fm = new FunctionMap ( ) ; fm . fm = new HashMap < > ( ) ; fm . addFunction ( "keyMatch" , new KeyMatchFunc ( ) ) ; fm . addFunction ( "keyMatch2" , new KeyMatch2Func ( ) ) ; fm . addFunction ( "regexMatch" , new RegexMatchFunc ( ) ) ; fm . addFunction ( "ipMatch" , new IPMatchFunc ( ) ) ; return fm ; }
loadFunctionMap loads an initial function map .
19,809
public static Config newConfig ( String confName ) { Config c = new Config ( ) ; c . parse ( confName ) ; return c ; }
newConfig create an empty configuration representation from file .
19,810
public static Config newConfigFromText ( String text ) { Config c = new Config ( ) ; c . parseBuffer ( new BufferedReader ( new StringReader ( text ) ) ) ; return c ; }
newConfigFromText create an empty configuration representation from text .
19,811
public boolean addDef ( String sec , String key , String value ) { Assertion ast = new Assertion ( ) ; ast . key = key ; ast . value = value ; if ( ast . value . equals ( "" ) ) { return false ; } if ( sec . equals ( "r" ) || sec . equals ( "p" ) ) { ast . tokens = ast . value . split ( ", " ) ; for ( int i = 0 ; i < ast . tokens . length ; i ++ ) { ast . tokens [ i ] = key + "_" + ast . tokens [ i ] ; } } else { ast . value = Util . removeComments ( Util . escapeAssertion ( ast . value ) ) ; } if ( ! model . containsKey ( sec ) ) { model . put ( sec , new HashMap < > ( ) ) ; } model . get ( sec ) . put ( key , ast ) ; return true ; }
addDef adds an assertion to the model .
19,812
public void loadModel ( String path ) { Config cfg = Config . newConfig ( path ) ; loadSection ( this , cfg , "r" ) ; loadSection ( this , cfg , "p" ) ; loadSection ( this , cfg , "e" ) ; loadSection ( this , cfg , "m" ) ; loadSection ( this , cfg , "g" ) ; }
loadModel loads the model from model CONF file .
19,813
public void loadModelFromText ( String text ) { Config cfg = Config . newConfigFromText ( text ) ; loadSection ( this , cfg , "r" ) ; loadSection ( this , cfg , "p" ) ; loadSection ( this , cfg , "e" ) ; loadSection ( this , cfg , "m" ) ; loadSection ( this , cfg , "g" ) ; }
loadModelFromText loads the model from the text .
19,814
public void printModel ( ) { Util . logPrint ( "Model:" ) ; for ( Map . Entry < String , Map < String , Assertion > > entry : model . entrySet ( ) ) { for ( Map . Entry < String , Assertion > entry2 : entry . getValue ( ) . entrySet ( ) ) { Util . logPrintf ( "%s.%s: %s" , entry . getKey ( ) , entry2 . getKey ( ) , entry2 . getValue ( ) . value ) ; } } }
printModel prints the model to the log .
19,815
public boolean mergeEffects ( String expr , Effect [ ] effects , float [ ] results ) { boolean result ; if ( expr . equals ( "some(where (p_eft == allow))" ) ) { result = false ; for ( Effect eft : effects ) { if ( eft == Effect . Allow ) { result = true ; break ; } } } else if ( expr . equals ( "!some(where (p_eft == deny))" ) ) { result = true ; for ( Effect eft : effects ) { if ( eft == Effect . Deny ) { result = false ; break ; } } } else if ( expr . equals ( "some(where (p_eft == allow)) && !some(where (p_eft == deny))" ) ) { result = false ; for ( Effect eft : effects ) { if ( eft == Effect . Allow ) { result = true ; } else if ( eft == Effect . Deny ) { result = false ; break ; } } } else if ( expr . equals ( "priority(p_eft) || deny" ) ) { result = false ; for ( Effect eft : effects ) { if ( eft != Effect . Indeterminate ) { if ( eft == Effect . Allow ) { result = true ; } else { result = false ; } break ; } } } else { throw new Error ( "unsupported effect" ) ; } return result ; }
mergeEffects merges all matching results collected by the enforcer into a single decision .
19,816
public List < List < String > > getFilteredPolicy ( int fieldIndex , String ... fieldValues ) { return getFilteredNamedPolicy ( "p" , fieldIndex , fieldValues ) ; }
getFilteredPolicy gets all the authorization rules in the policy field filters can be specified .
19,817
public List < List < String > > getFilteredNamedPolicy ( String ptype , int fieldIndex , String ... fieldValues ) { return model . getFilteredPolicy ( "p" , ptype , fieldIndex , fieldValues ) ; }
getFilteredNamedPolicy gets all the authorization rules in the named policy field filters can be specified .
19,818
public List < List < String > > getFilteredGroupingPolicy ( int fieldIndex , String ... fieldValues ) { return getFilteredNamedGroupingPolicy ( "g" , fieldIndex , fieldValues ) ; }
getFilteredGroupingPolicy gets all the role inheritance rules in the policy field filters can be specified .
19,819
public List < List < String > > getFilteredNamedGroupingPolicy ( String ptype , int fieldIndex , String ... fieldValues ) { return model . getFilteredPolicy ( "g" , ptype , fieldIndex , fieldValues ) ; }
getFilteredNamedGroupingPolicy gets all the role inheritance rules in the policy field filters can be specified .
19,820
public boolean addNamedPolicy ( String ptype , String ... params ) { return addNamedPolicy ( ptype , Arrays . asList ( params ) ) ; }
AddNamedPolicy adds an authorization rule to the current named policy . If the rule already exists the function returns false and the rule will not be added . Otherwise the function returns true by adding the new rule .
19,821
public boolean removeNamedPolicy ( String ptype , String ... params ) { return removeNamedPolicy ( ptype , Arrays . asList ( params ) ) ; }
removeNamedPolicy removes an authorization rule from the current named policy .
19,822
public boolean removeFilteredNamedPolicy ( String ptype , int fieldIndex , String ... fieldValues ) { return removeFilteredPolicy ( "p" , ptype , fieldIndex , fieldValues ) ; }
removeFilteredNamedPolicy removes an authorization rule from the current named policy field filters can be specified .
19,823
public boolean removeFilteredNamedGroupingPolicy ( String ptype , int fieldIndex , String ... fieldValues ) { boolean ruleRemoved = removeFilteredPolicy ( "g" , ptype , fieldIndex , fieldValues ) ; if ( autoBuildRoleLinks ) { buildRoleLinks ( ) ; } return ruleRemoved ; }
removeFilteredNamedGroupingPolicy removes a role inheritance rule from the current named policy field filters can be specified .
19,824
public void build ( final BuildNodeCallback callback ) { Preconditions . checkNotNull ( callback ) ; if ( leftChild == null ) { callback . onLastNode ( this ) ; return ; } LocalDate curDate = start ; NodeInterval curChild = leftChild ; while ( curChild != null ) { if ( curChild . getStart ( ) . compareTo ( curDate ) > 0 ) { callback . onMissingInterval ( this , curDate , curChild . getStart ( ) ) ; } curChild . build ( callback ) ; curDate = curChild . getEnd ( ) ; curChild = curChild . getRightSibling ( ) ; } if ( curDate . compareTo ( end ) < 0 ) { callback . onMissingInterval ( this , curDate , end ) ; } return ; }
Build the tree by calling the callback on the last node in the tree or remaining part with no children .
19,825
public boolean addNode ( final NodeInterval newNode , final AddNodeCallback callback ) { Preconditions . checkNotNull ( newNode ) ; Preconditions . checkNotNull ( callback ) ; if ( ! isRoot ( ) && newNode . getStart ( ) . compareTo ( start ) == 0 && newNode . getEnd ( ) . compareTo ( end ) == 0 ) { return callback . onExistingNode ( this ) ; } computeRootInterval ( newNode ) ; newNode . parent = this ; if ( leftChild == null ) { if ( callback . shouldInsertNode ( this ) ) { leftChild = newNode ; return true ; } else { return false ; } } NodeInterval prevChild = null ; NodeInterval curChild = leftChild ; while ( curChild != null ) { if ( curChild . isItemContained ( newNode ) ) { return curChild . addNode ( newNode , callback ) ; } if ( curChild . isItemOverlap ( newNode ) ) { if ( rebalance ( newNode ) ) { return callback . shouldInsertNode ( this ) ; } } if ( newNode . getStart ( ) . compareTo ( curChild . getStart ( ) ) < 0 ) { Preconditions . checkState ( newNode . getEnd ( ) . compareTo ( end ) <= 0 ) ; if ( callback . shouldInsertNode ( this ) ) { newNode . rightSibling = curChild ; if ( prevChild == null ) { leftChild = newNode ; } else { prevChild . rightSibling = newNode ; } return true ; } else { return false ; } } prevChild = curChild ; curChild = curChild . rightSibling ; } if ( callback . shouldInsertNode ( this ) ) { prevChild . rightSibling = newNode ; return true ; } else { return false ; } }
Add a new node in the tree .
19,826
public static Map < String , Object > toMap ( final Iterable < PluginProperty > ... propertiesLists ) { final Map < String , Object > mergedProperties = new HashMap < String , Object > ( ) ; for ( final Iterable < PluginProperty > propertiesList : propertiesLists ) { if ( propertiesList != null ) { for ( final PluginProperty pluginProperty : propertiesList ) { if ( pluginProperty != null && pluginProperty . getKey ( ) != null ) { mergedProperties . put ( pluginProperty . getKey ( ) , pluginProperty . getValue ( ) ) ; } } } } return mergedProperties ; }
Last one has precedence
19,827
private void errorDuringTransaction ( final Throwable t , final Method method , final String extraErrorMessage ) throws Throwable { final StringBuilder errorMessageBuilder = new StringBuilder ( "Error during transaction for sql entity {} and method {}" ) ; if ( t instanceof SQLException ) { final SQLException sqlException = ( SQLException ) t ; errorMessageBuilder . append ( " [SQL DefaultState: " ) . append ( sqlException . getSQLState ( ) ) . append ( ", Vendor Error Code: " ) . append ( sqlException . getErrorCode ( ) ) . append ( "]" ) ; } if ( extraErrorMessage != null ) { errorMessageBuilder . append ( "\n" ) . append ( extraErrorMessage ) ; } logger . warn ( errorMessageBuilder . toString ( ) , sqlDaoClass , method . getName ( ) ) ; if ( ! ( t instanceof RuntimeException ) ) { throw new RuntimeException ( t ) ; } else { throw t ; } }
Nice method name to ease debugging while looking at log files
19,828
public static List < BlockingState > sortedCopy ( final Iterable < BlockingState > blockingStates ) { final List < BlockingState > blockingStatesSomewhatSorted = Ordering . < BlockingState > natural ( ) . immutableSortedCopy ( blockingStates ) ; final List < BlockingState > result = new LinkedList < BlockingState > ( ) ; final Iterator < BlockingState > iterator = blockingStatesSomewhatSorted . iterator ( ) ; BlockingState prev = null ; while ( iterator . hasNext ( ) ) { final BlockingState current = iterator . next ( ) ; if ( iterator . hasNext ( ) ) { final BlockingState next = iterator . next ( ) ; if ( prev != null && current . getEffectiveDate ( ) . equals ( next . getEffectiveDate ( ) ) && current . getBlockedId ( ) . equals ( next . getBlockedId ( ) ) && ! current . getService ( ) . equals ( next . getService ( ) ) ) { BlockingState prevCandidate = insertTiedBlockingStatesInTheRightOrder ( result , current , next , prev . isBlockBilling ( ) , current . isBlockBilling ( ) , next . isBlockBilling ( ) ) ; if ( prevCandidate == null ) { prevCandidate = insertTiedBlockingStatesInTheRightOrder ( result , current , next , prev . isBlockEntitlement ( ) , current . isBlockEntitlement ( ) , next . isBlockEntitlement ( ) ) ; if ( prevCandidate == null ) { prevCandidate = insertTiedBlockingStatesInTheRightOrder ( result , current , next , prev . isBlockChange ( ) , current . isBlockChange ( ) , next . isBlockChange ( ) ) ; if ( prevCandidate == null ) { result . add ( current ) ; result . add ( next ) ; prev = next ; } else { prev = prevCandidate ; } } else { prev = prevCandidate ; } } else { prev = prevCandidate ; } } else { result . add ( current ) ; result . add ( next ) ; prev = next ; } } else { result . add ( current ) ; } } return result ; }
Ordering is critical here especially for Junction
19,829
protected List < BlockingState > addBlockingStatesNotOnDisk ( final UUID blockableId , final BlockingStateType blockingStateType , final Collection < BlockingState > blockingStatesOnDiskCopy , final Iterable < SubscriptionBase > baseSubscriptionsToConsider , final Iterable < EventsStream > eventsStreams ) { final DateTime now = clock . getUTCNow ( ) ; for ( final SubscriptionBase baseSubscription : baseSubscriptionsToConsider ) { final EventsStream eventsStream = Iterables . < EventsStream > find ( eventsStreams , new Predicate < EventsStream > ( ) { public boolean apply ( final EventsStream input ) { return input . getSubscriptionBase ( ) . getId ( ) . equals ( baseSubscription . getId ( ) ) ; } } ) ; final Collection < BlockingState > blockingStatesNotOnDisk = eventsStream . computeAddonsBlockingStatesForFutureSubscriptionBaseEvents ( ) ; for ( final BlockingState blockingState : blockingStatesNotOnDisk ) { BlockingState cancellationBlockingStateOnDisk = null ; boolean overrideCancellationBlockingStateOnDisk = false ; if ( isEntitlementCancellationBlockingState ( blockingState ) ) { cancellationBlockingStateOnDisk = findEntitlementCancellationBlockingState ( blockingState . getBlockedId ( ) , blockingStatesOnDiskCopy ) ; overrideCancellationBlockingStateOnDisk = cancellationBlockingStateOnDisk != null && blockingState . getEffectiveDate ( ) . isBefore ( cancellationBlockingStateOnDisk . getEffectiveDate ( ) ) ; } if ( ( blockingStateType == null || ( BlockingStateType . SUBSCRIPTION . equals ( blockingStateType ) && blockingState . getBlockedId ( ) . equals ( blockableId ) ) ) && ( cancellationBlockingStateOnDisk == null || overrideCancellationBlockingStateOnDisk ) ) { final BlockingStateModelDao blockingStateModelDao = new BlockingStateModelDao ( blockingState , now , now ) ; blockingStatesOnDiskCopy . add ( BlockingStateModelDao . toBlockingState ( blockingStateModelDao ) ) ; if ( overrideCancellationBlockingStateOnDisk ) { blockingStatesOnDiskCopy . remove ( cancellationBlockingStateOnDisk ) ; } } } } return sortedCopy ( blockingStatesOnDiskCopy ) ; }
Special signature for OptimizedProxyBlockingStateDao
19,830
void initializeIfNeeded ( final UUID objectId ) { if ( auditLogsCache . get ( objectId ) == null ) { auditLogsCache . put ( objectId , new LinkedList < AuditLog > ( ) ) ; } }
Used by DefaultAccountAuditLogs
19,831
public int compareTo ( final DisabledDuration o ) { int result = start . compareTo ( o . getStart ( ) ) ; if ( result == 0 ) { if ( end == null && o . getEnd ( ) == null ) { result = 0 ; } else if ( end != null && o . getEnd ( ) != null ) { result = end . compareTo ( o . getEnd ( ) ) ; } else if ( o . getEnd ( ) == null ) { return - 1 ; } else { return 1 ; } } return result ; }
Order by start date first and then end date
19,832
protected final void bindShiroInterceptorWithHierarchy ( final AnnotationMethodInterceptor methodInterceptor ) { bindInterceptor ( Matchers . any ( ) , new AbstractMatcher < Method > ( ) { public boolean matches ( final Method method ) { final Class < ? extends Annotation > annotation = methodInterceptor . getHandler ( ) . getAnnotationClass ( ) ; return resolver . getAnnotationFromMethod ( method , annotation ) != null ; } } , new AopAllianceMethodInterceptorAdapter ( methodInterceptor ) ) ; }
Similar to bindShiroInterceptor but will look for annotations in the class hierarchy
19,833
public void addExistingItem ( final ItemsNodeInterval newNode ) { Preconditions . checkState ( newNode . getItems ( ) . size ( ) == 1 , "Invalid node=%s" , newNode ) ; final Item item = newNode . getItems ( ) . get ( 0 ) ; addNode ( newNode , new AddNodeCallback ( ) { public boolean onExistingNode ( final NodeInterval existingNode ) { final ItemsInterval existingOrNewNodeItems = ( ( ItemsNodeInterval ) existingNode ) . getItemsInterval ( ) ; existingOrNewNodeItems . add ( item ) ; return false ; } public boolean shouldInsertNode ( final NodeInterval insertionNode ) { return true ; } } ) ; }
Add existing item into the tree
19,834
public Item addAdjustment ( final InvoiceItem item , final UUID targetInvoiceId ) { final UUID targetId = item . getLinkedItemId ( ) ; final NodeInterval node = findNode ( new SearchCallback ( ) { public boolean isMatch ( final NodeInterval curNode ) { return ( ( ItemsNodeInterval ) curNode ) . getItemsInterval ( ) . findItem ( targetId ) != null ; } } ) ; Preconditions . checkNotNull ( node , "Unable to find item interval for id='%s', tree=%s" , targetId , this ) ; final ItemsInterval targetItemsInterval = ( ( ItemsNodeInterval ) node ) . getItemsInterval ( ) ; final Item targetItem = targetItemsInterval . findItem ( targetId ) ; Preconditions . checkNotNull ( targetItem , "Unable to find item with id='%s', itemsInterval=%s" , targetId , targetItemsInterval ) ; final BigDecimal adjustmentAmount = item . getAmount ( ) . negate ( ) ; if ( targetItem . getAmount ( ) . compareTo ( adjustmentAmount ) == 0 ) { addExistingItem ( new ItemsNodeInterval ( this , new Item ( item , targetItem . getStartDate ( ) , targetItem . getEndDate ( ) , targetInvoiceId , ItemAction . CANCEL ) ) ) ; return targetItem ; } else { targetItem . incrementAdjustedAmount ( adjustmentAmount ) ; return null ; } }
Add the adjustment amount on the item specified by the targetId .
19,835
private StaticCatalog getStaticCatalog ( final PlanSpecifier spec , final DateTime requestedDate , final DateTime subscriptionChangePlanDate ) throws CatalogApiException { final CatalogPlanEntry entry = findCatalogPlanEntry ( new PlanRequestWrapper ( spec ) , requestedDate , subscriptionChangePlanDate ) ; return entry . getStaticCatalog ( ) ; }
Note that the PlanSpecifier billing period must refer here to the recurring phase one when a plan name isn t specified
19,836
public InvoiceItemModelDao computeCBAComplexity ( final InvoiceModelDao invoice , final BigDecimal accountCBAOrNull , final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory , final InternalCallContext context ) throws EntityPersistenceException , InvoiceApiException { final BigDecimal balance = getInvoiceBalance ( invoice ) ; if ( balance . compareTo ( BigDecimal . ZERO ) < 0 ) { return buildCBAItem ( invoice , balance , context ) ; } else if ( balance . compareTo ( BigDecimal . ZERO ) > 0 && invoice . getStatus ( ) == InvoiceStatus . COMMITTED && ! invoice . isWrittenOff ( ) ) { BigDecimal accountCBA = accountCBAOrNull ; if ( accountCBAOrNull == null ) { accountCBA = getAccountCBAFromTransaction ( entitySqlDaoWrapperFactory , context ) ; } if ( accountCBA . compareTo ( BigDecimal . ZERO ) <= 0 ) { return null ; } final BigDecimal positiveCreditAmount = accountCBA . compareTo ( balance ) > 0 ? balance : accountCBA ; return buildCBAItem ( invoice , positiveCreditAmount , context ) ; } else { return null ; } }
We expect a clean up to date invoice with all the items except the cba that we will compute in that method
19,837
private void useExistingCBAFromTransaction ( final BigDecimal accountCBA , final List < Tag > invoicesTags , final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory , final InternalCallContext context ) throws InvoiceApiException , EntityPersistenceException { if ( accountCBA . compareTo ( BigDecimal . ZERO ) <= 0 ) { return ; } final List < InvoiceModelDao > allInvoices = invoiceDaoHelper . getAllInvoicesByAccountFromTransaction ( false , invoicesTags , entitySqlDaoWrapperFactory , context ) ; final List < InvoiceModelDao > unpaidInvoices = invoiceDaoHelper . getUnpaidInvoicesByAccountFromTransaction ( allInvoices , null ) ; final List < InvoiceModelDao > orderedUnpaidInvoices = Ordering . from ( new Comparator < InvoiceModelDao > ( ) { public int compare ( final InvoiceModelDao i1 , final InvoiceModelDao i2 ) { return i1 . getInvoiceDate ( ) . compareTo ( i2 . getInvoiceDate ( ) ) ; } } ) . immutableSortedCopy ( unpaidInvoices ) ; BigDecimal remainingAccountCBA = accountCBA ; for ( final InvoiceModelDao unpaidInvoice : orderedUnpaidInvoices ) { remainingAccountCBA = computeCBAComplexityAndCreateCBAItem ( remainingAccountCBA , unpaidInvoice , entitySqlDaoWrapperFactory , context ) ; if ( remainingAccountCBA . compareTo ( BigDecimal . ZERO ) <= 0 ) { break ; } } }
Distribute account CBA across all COMMITTED unpaid invoices
19,838
private BigDecimal computeCBAComplexityAndCreateCBAItem ( final BigDecimal accountCBA , final InvoiceModelDao invoice , final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory , final InternalCallContext context ) throws EntityPersistenceException , InvoiceApiException { final InvoiceItemModelDao cbaItem = computeCBAComplexity ( invoice , accountCBA , entitySqlDaoWrapperFactory , context ) ; if ( cbaItem != null ) { createCBAItem ( invoice , cbaItem , entitySqlDaoWrapperFactory , context ) ; return accountCBA . add ( cbaItem . getAmount ( ) ) ; } else { return accountCBA ; } }
Return the updated account CBA
19,839
public void loadSchemaInformation ( final String schemaName ) { columnInfoMap . clear ( ) ; final List < DefaultColumnInfo > columnInfoList = dao . getColumnInfoList ( schemaName ) ; for ( final DefaultColumnInfo columnInfo : columnInfoList ) { final String tableName = columnInfo . getTableName ( ) ; if ( ! columnInfoMap . containsKey ( tableName ) ) { columnInfoMap . put ( tableName , new HashMap < String , DefaultColumnInfo > ( ) ) ; } columnInfoMap . get ( tableName ) . put ( columnInfo . getColumnName ( ) , columnInfo ) ; } }
replaces existing schema information with the information for the specified schema
19,840
private static LinkedList < Field > initializeNonRequiredFields ( final Class < ? > aClass ) { final LinkedList < Field > result = new LinkedList ( ) ; final Field [ ] fields = aClass . getDeclaredFields ( ) ; for ( final Field f : fields ) { if ( f . getType ( ) . isArray ( ) ) { final XmlElementWrapper xmlElementWrapper = f . getAnnotation ( XmlElementWrapper . class ) ; if ( xmlElementWrapper != null ) { if ( ! xmlElementWrapper . required ( ) ) { result . add ( f ) ; } } else { final XmlElement xmlElement = f . getAnnotation ( XmlElement . class ) ; if ( xmlElement != null && ! xmlElement . required ( ) ) { result . add ( f ) ; } } } else if ( ! f . getType ( ) . isPrimitive ( ) ) { if ( f . getType ( ) . isEnum ( ) ) { if ( FixedType . class . equals ( f . getType ( ) ) ) { result . add ( f ) ; } else if ( BlockType . class . equals ( f . getType ( ) ) ) { result . add ( f ) ; } else if ( TierBlockPolicy . class . equals ( f . getType ( ) ) ) { result . add ( f ) ; } } else if ( Integer . class . equals ( f . getType ( ) ) ) { result . add ( f ) ; } else if ( Double . class . equals ( f . getType ( ) ) ) { result . add ( f ) ; } } } return result ; }
For each type of catalog object we keep the Field associated to non required attribute fields
19,841
private DefaultSubscriptionBase getDefaultSubscriptionBase ( final Entity subscriptionBase , final Catalog catalog , final InternalTenantContext context ) throws CatalogApiException { if ( subscriptionBase instanceof DefaultSubscriptionBase ) { return ( DefaultSubscriptionBase ) subscriptionBase ; } else { return ( DefaultSubscriptionBase ) dao . getSubscriptionFromId ( subscriptionBase . getId ( ) , catalog , context ) ; } }
For forward - compatibility
19,842
private String getFormattedAmountByLocaleAndInvoiceCurrency ( final BigDecimal amount ) { final String invoiceCurrencyCode = invoice . getCurrency ( ) . toString ( ) ; final CurrencyUnit currencyUnit = CurrencyUnit . of ( invoiceCurrencyCode ) ; final DecimalFormat numberFormatter = ( DecimalFormat ) DecimalFormat . getCurrencyInstance ( locale ) ; final DecimalFormatSymbols dfs = numberFormatter . getDecimalFormatSymbols ( ) ; dfs . setInternationalCurrencySymbol ( currencyUnit . getCurrencyCode ( ) ) ; try { Currency currency = Currency . fromCode ( invoiceCurrencyCode ) ; dfs . setCurrencySymbol ( currency . getSymbol ( ) ) ; } catch ( final IllegalArgumentException e ) { dfs . setCurrencySymbol ( currencyUnit . getSymbol ( locale ) ) ; } numberFormatter . setDecimalFormatSymbols ( dfs ) ; numberFormatter . setMinimumFractionDigits ( currencyUnit . getDefaultFractionDigits ( ) ) ; numberFormatter . setMaximumFractionDigits ( currencyUnit . getDefaultFractionDigits ( ) ) ; return numberFormatter . format ( amount . doubleValue ( ) ) ; }
Returns the formatted amount with the correct currency symbol that is get from the invoice currency .
19,843
public void addItem ( final InvoiceItem invoiceItem ) { Preconditions . checkState ( ! isBuilt , "Tree already built, unable to add new invoiceItem=%s" , invoiceItem ) ; switch ( invoiceItem . getInvoiceItemType ( ) ) { case RECURRING : if ( invoiceItem . getAmount ( ) . compareTo ( BigDecimal . ZERO ) == 0 ) { existingIgnoredItems . add ( invoiceItem ) ; } else { root . addExistingItem ( new ItemsNodeInterval ( root , new Item ( invoiceItem , targetInvoiceId , ItemAction . ADD ) ) ) ; } break ; case REPAIR_ADJ : root . addExistingItem ( new ItemsNodeInterval ( root , new Item ( invoiceItem , targetInvoiceId , ItemAction . CANCEL ) ) ) ; break ; case FIXED : existingIgnoredItems . add ( invoiceItem ) ; break ; case ITEM_ADJ : pendingItemAdj . add ( invoiceItem ) ; break ; default : break ; } }
Add an existing item in the tree . A new node is inserted or an existing one updated if one for the same period already exists .
19,844
public void build ( ) { Preconditions . checkState ( ! isBuilt ) ; for ( final InvoiceItem item : pendingItemAdj ) { final InvoiceItem ignoredLinkedItem = Iterables . tryFind ( existingIgnoredItems , new Predicate < InvoiceItem > ( ) { public boolean apply ( final InvoiceItem input ) { return input . getId ( ) . equals ( item . getLinkedItemId ( ) ) ; } } ) . orNull ( ) ; if ( ignoredLinkedItem == null ) { final Item fullyAdjustedItem = root . addAdjustment ( item , targetInvoiceId ) ; if ( fullyAdjustedItem != null ) { existingFullyAdjustedItems . add ( fullyAdjustedItem ) ; } } } pendingItemAdj . clear ( ) ; root . buildForExistingItems ( items , targetInvoiceId ) ; isBuilt = true ; }
Build the tree and process adjustments
19,845
public void mergeProposedItem ( final InvoiceItem invoiceItem ) { Preconditions . checkState ( ! isBuilt , "Tree already built, unable to add new invoiceItem=%s" , invoiceItem ) ; final InvoiceItem existingItem = Iterables . tryFind ( existingIgnoredItems , new Predicate < InvoiceItem > ( ) { public boolean apply ( final InvoiceItem input ) { return input . matches ( invoiceItem ) ; } } ) . orNull ( ) ; if ( existingItem != null ) { return ; } switch ( invoiceItem . getInvoiceItemType ( ) ) { case RECURRING : final boolean merged = root . addProposedItem ( new ItemsNodeInterval ( root , new Item ( invoiceItem , targetInvoiceId , ItemAction . ADD ) ) ) ; if ( ! merged ) { items . add ( new Item ( invoiceItem , targetInvoiceId , ItemAction . ADD ) ) ; } break ; case FIXED : remainingIgnoredItems . add ( invoiceItem ) ; break ; default : Preconditions . checkState ( false , "Unexpected proposed item " + invoiceItem ) ; } }
Merge a new proposed item in the tree .
19,846
public void buildForMerge ( ) { Preconditions . checkState ( ! isBuilt , "Tree already built" ) ; root . mergeExistingAndProposed ( items , targetInvoiceId ) ; isBuilt = true ; isMerged = true ; }
Build tree post merge
19,847
public EventsStream buildForEntitlement ( final Collection < BlockingState > blockingStatesForAccount , final ImmutableAccountData account , final SubscriptionBaseBundle bundle , final SubscriptionBase baseSubscription , final Collection < SubscriptionBase > allSubscriptionsForBundle , final int accountBCD , final Catalog catalog , final InternalTenantContext internalTenantContext ) throws EntitlementApiException { final Map < UUID , Integer > bcdCache = new HashMap < UUID , Integer > ( ) ; return buildForEntitlement ( blockingStatesForAccount , account , bundle , baseSubscription , baseSubscription , allSubscriptionsForBundle , accountBCD , bcdCache , catalog , internalTenantContext ) ; }
Special signature for OptimizedProxyBlockingStateDao to save some DAO calls
19,848
public static UUID getOrCreateUserToken ( ) { UUID userToken ; if ( Request . getPerThreadRequestData ( ) . getRequestId ( ) != null ) { try { userToken = UUID . fromString ( Request . getPerThreadRequestData ( ) . getRequestId ( ) ) ; } catch ( final IllegalArgumentException ignored ) { userToken = UUIDs . randomUUID ( ) ; } } else { userToken = UUIDs . randomUUID ( ) ; } return userToken ; }
Use REQUEST_ID_HEADER if this is provided and looks like a UUID if not allocate a random one .
19,849
protected List < DisabledDuration > createBlockingDurations ( final Iterable < BlockingState > inputBundleEvents ) { final List < DisabledDuration > result = new ArrayList < DisabledDuration > ( ) ; final Set < String > services = ImmutableSet . copyOf ( Iterables . transform ( inputBundleEvents , new Function < BlockingState , String > ( ) { public String apply ( final BlockingState input ) { return input . getService ( ) ; } } ) ) ; final Map < String , BlockingStateService > svcBlockedMap = new HashMap < String , BlockingStateService > ( ) ; for ( String svc : services ) { svcBlockedMap . put ( svc , new BlockingStateService ( ) ) ; } for ( final BlockingState e : inputBundleEvents ) { svcBlockedMap . get ( e . getService ( ) ) . addBlockingState ( e ) ; } final Iterable < DisabledDuration > unorderedDisabledDuration = Iterables . concat ( Iterables . transform ( svcBlockedMap . values ( ) , new Function < BlockingStateService , List < DisabledDuration > > ( ) { public List < DisabledDuration > apply ( final BlockingStateService input ) { return input . build ( ) ; } } ) ) ; final List < DisabledDuration > sortedDisabledDuration = Ordering . natural ( ) . sortedCopy ( unorderedDisabledDuration ) ; DisabledDuration prevDuration = null ; for ( DisabledDuration d : sortedDisabledDuration ) { if ( prevDuration == null ) { prevDuration = d ; } else { if ( prevDuration . isDisjoint ( d ) ) { result . add ( prevDuration ) ; prevDuration = d ; } else { prevDuration = DisabledDuration . mergeDuration ( prevDuration , d ) ; } } } if ( prevDuration != null ) { result . add ( prevDuration ) ; } return result ; }
In ascending order
19,850
public void build ( ) { Preconditions . checkState ( ! isBuilt ) ; if ( pendingItemAdj . size ( ) > 0 ) { for ( InvoiceItem item : pendingItemAdj ) { addExistingItem ( item , true ) ; } pendingItemAdj . clear ( ) ; } for ( SubscriptionItemTree tree : subscriptionItemTree . values ( ) ) { tree . build ( ) ; } isBuilt = true ; }
build the subscription trees after they have been populated with existing items on disk
19,851
public void mergeWithProposedItems ( final List < InvoiceItem > proposedItems ) { build ( ) ; for ( SubscriptionItemTree tree : subscriptionItemTree . values ( ) ) { tree . flatten ( true ) ; } for ( InvoiceItem item : proposedItems ) { final UUID subscriptionId = getSubscriptionId ( item , null ) ; SubscriptionItemTree tree = subscriptionItemTree . get ( subscriptionId ) ; if ( tree == null ) { tree = new SubscriptionItemTree ( subscriptionId , targetInvoiceId ) ; subscriptionItemTree . put ( subscriptionId , tree ) ; } tree . mergeProposedItem ( item ) ; } for ( SubscriptionItemTree tree : subscriptionItemTree . values ( ) ) { tree . buildForMerge ( ) ; } }
Rebuild the new tree by merging current on - disk existing view with new proposed list .
19,852
public InternalTenantContext createInternalTenantContext ( final UUID objectId , final ObjectType objectType , final TenantContext context ) { final Long tenantRecordId = getTenantRecordIdSafe ( context ) ; final Long accountRecordId = getAccountRecordIdSafe ( objectId , objectType , context ) ; return createInternalTenantContext ( tenantRecordId , accountRecordId ) ; }
Crate an internal tenant callcontext from a tenant callcontext and retrieving the account_record_id from another table
19,853
public InternalTenantContext createInternalTenantContext ( final Long tenantRecordId , final Long accountRecordId ) { populateMDCContext ( null , accountRecordId , tenantRecordId ) ; if ( accountRecordId == null ) { return new InternalTenantContext ( tenantRecordId ) ; } else { final ImmutableAccountData immutableAccountData = getImmutableAccountData ( accountRecordId , tenantRecordId ) ; final DateTimeZone fixedOffsetTimeZone = immutableAccountData . getFixedOffsetTimeZone ( ) ; final DateTime referenceTime = immutableAccountData . getReferenceTime ( ) ; return new InternalTenantContext ( tenantRecordId , accountRecordId , fixedOffsetTimeZone , referenceTime ) ; } }
Create an internal tenant callcontext
19,854
public InternalCallContext createInternalCallContext ( final UUID objectId , final ObjectType objectType , final CallContext context ) { final Long tenantRecordId = getTenantRecordIdSafe ( context ) ; final Long accountRecordId = getAccountRecordIdSafe ( objectId , objectType , context ) ; return createInternalCallContext ( tenantRecordId , accountRecordId , context . getUserName ( ) , context . getCallOrigin ( ) , context . getUserType ( ) , context . getUserToken ( ) , context . getReasonCode ( ) , context . getComments ( ) , context . getCreatedDate ( ) , context . getUpdatedDate ( ) ) ; }
Create an internal call callcontext from a call callcontext and retrieving the account_record_id from another table
19,855
public InternalCallContext createInternalCallContext ( final UUID objectId , final ObjectType objectType , final String userName , final CallOrigin callOrigin , final UserType userType , final UUID userToken , final Long tenantRecordId ) { final Long accountRecordId = getAccountRecordIdSafe ( objectId , objectType , tenantRecordId ) ; return createInternalCallContext ( tenantRecordId , accountRecordId , userName , callOrigin , userType , userToken , null , null , null , null ) ; }
Used by the payment retry service
19,856
public UUID getAccountId ( final UUID objectId , final ObjectType objectType , final TenantContext context ) { final Long accountRecordId = getAccountRecordIdSafe ( objectId , objectType , context ) ; if ( accountRecordId != null ) { return nonEntityDao . retrieveIdFromObject ( accountRecordId , ObjectType . ACCOUNT , objectIdCacheController ) ; } else { return null ; } }
Safe method to retrieve the account id from any object
19,857
private LinkedList < SubscriptionEvent > computeSubscriptionBaseEvents ( final Iterable < Entitlement > entitlements , final InternalTenantContext internalTenantContext ) { final LinkedList < SubscriptionEvent > result = new LinkedList < SubscriptionEvent > ( ) ; for ( final Entitlement cur : entitlements ) { Preconditions . checkState ( cur instanceof DefaultEntitlement , "Entitlement %s is not a DefaultEntitlement" , cur ) ; final SubscriptionBase base = ( ( DefaultEntitlement ) cur ) . getSubscriptionBase ( ) ; final List < SubscriptionBaseTransition > baseTransitions = base . getAllTransitions ( ) ; for ( final SubscriptionBaseTransition tr : baseTransitions ) { final List < SubscriptionEventType > eventTypes = toEventTypes ( tr . getTransitionType ( ) ) ; for ( final SubscriptionEventType eventType : eventTypes ) { final SubscriptionEvent event = toSubscriptionEvent ( tr , eventType , internalTenantContext ) ; insertSubscriptionEvent ( event , result ) ; } } } return result ; }
Compute the initial stream of events based on the subscription base events
19,858
private void removeOverlappingSubscriptionEvents ( final LinkedList < SubscriptionEvent > events ) { final Iterator < SubscriptionEvent > iterator = events . iterator ( ) ; final Map < String , DefaultSubscriptionEvent > prevPerService = new HashMap < String , DefaultSubscriptionEvent > ( ) ; while ( iterator . hasNext ( ) ) { final DefaultSubscriptionEvent current = ( DefaultSubscriptionEvent ) iterator . next ( ) ; final DefaultSubscriptionEvent prev = prevPerService . get ( current . getServiceName ( ) ) ; if ( prev != null ) { if ( current . overlaps ( prev ) ) { iterator . remove ( ) ; } else { prevPerService . put ( current . getServiceName ( ) , current ) ; } } else { prevPerService . put ( current . getServiceName ( ) , current ) ; } } }
Make sure the argument supports the remove operation - hence expect a LinkedList not a List
19,859
Invoice earliest ( final SortedSet < Invoice > unpaidInvoices ) { try { return unpaidInvoices . first ( ) ; } catch ( NoSuchElementException e ) { return null ; } }
Package scope for testing
19,860
private Object sanitize ( final Object o ) { if ( ! ( o instanceof String ) ) { return o ; } else { return ( ( String ) o ) . replace ( "\n" , "\\N{LINE FEED}" ) . replace ( "|" , "\\N{VERTICAL LINE}" ) ; } }
Sanitize special characters which could impact the import process
19,861
private CacheLoaderArgument initializeCacheLoaderArgument ( final boolean filterTemplateCatalog ) { final LoaderCallback loaderCallback = new LoaderCallback ( ) { public Catalog loadCatalog ( final List < String > catalogXMLs , final Long tenantRecordId ) throws CatalogApiException { return loader . load ( catalogXMLs , filterTemplateCatalog , tenantRecordId ) ; } } ; final Object [ ] args = new Object [ 1 ] ; args [ 0 ] = loaderCallback ; final ObjectType irrelevant = null ; final InternalTenantContext notUsed = null ; return new CacheLoaderArgument ( irrelevant , args , notUsed ) ; }
This is a contract between the TenantCatalogCacheLoader and the DefaultCatalogCache
19,862
private void build ( ) { for ( final UUID subscriptionId : perSubscriptionFutureNotificationDates . keySet ( ) ) { final SubscriptionFutureNotificationDates tmp = perSubscriptionFutureNotificationDates . get ( subscriptionId ) ; if ( tmp . getRecurringBillingMode ( ) == BillingMode . IN_ADVANCE && ! hasItemsForSubscription ( subscriptionId , InvoiceItemType . RECURRING ) ) { tmp . resetNextRecurringDate ( ) ; } } if ( invoice != null && invoice . getInvoiceItems ( ) . isEmpty ( ) ) { invoice = null ; } }
Remove all the IN_ADVANCE items for which we have no invoice items
19,863
private static BigDecimal computeInvoiceAmountAdjustedForAccountCredit ( final Currency currency , final Iterable < InvoiceItem > invoiceItems ) { BigDecimal amountAdjusted = BigDecimal . ZERO ; if ( invoiceItems == null || ! invoiceItems . iterator ( ) . hasNext ( ) ) { return KillBillMoney . of ( amountAdjusted , currency ) ; } for ( final InvoiceItem invoiceItem : invoiceItems ) { final Iterable < InvoiceItem > otherInvoiceItems = Iterables . filter ( invoiceItems , new Predicate < InvoiceItem > ( ) { public boolean apply ( final InvoiceItem input ) { return ! input . getId ( ) . equals ( invoiceItem . getId ( ) ) ; } } ) ; if ( InvoiceItemType . CREDIT_ADJ . equals ( invoiceItem . getInvoiceItemType ( ) ) && ( Iterables . size ( otherInvoiceItems ) == 1 && InvoiceItemType . CBA_ADJ . equals ( otherInvoiceItems . iterator ( ) . next ( ) . getInvoiceItemType ( ) ) && otherInvoiceItems . iterator ( ) . next ( ) . getInvoiceId ( ) . equals ( invoiceItem . getInvoiceId ( ) ) && otherInvoiceItems . iterator ( ) . next ( ) . getAmount ( ) . compareTo ( invoiceItem . getAmount ( ) . negate ( ) ) == 0 ) ) { amountAdjusted = amountAdjusted . add ( invoiceItem . getAmount ( ) ) ; } } return KillBillMoney . of ( amountAdjusted , currency ) ; }
Snowflake for the CREDIT_ADJ on its own invoice
19,864
public TimedPhase [ ] getCurrentAndNextTimedPhaseOnCreate ( final DateTime alignStartDate , final DateTime bundleStartDate , final Plan plan , final PhaseType initialPhase , final String priceList , final DateTime effectiveDate , final Catalog catalog , final InternalTenantContext context ) throws CatalogApiException , SubscriptionBaseApiException { final List < TimedPhase > timedPhases = getTimedPhaseOnCreate ( alignStartDate , bundleStartDate , plan , initialPhase , catalog , effectiveDate , context ) ; final TimedPhase [ ] result = new TimedPhase [ 2 ] ; result [ 0 ] = getTimedPhase ( timedPhases , effectiveDate , WhichPhase . CURRENT ) ; result [ 1 ] = getTimedPhase ( timedPhases , effectiveDate , WhichPhase . NEXT ) ; return result ; }
Returns the current and next phase for the subscription in creation
19,865
public TimedPhase getCurrentTimedPhaseOnChange ( final DefaultSubscriptionBase subscription , final Plan plan , final DateTime effectiveDate , final PhaseType newPlanInitialPhaseType , final Catalog catalog , final InternalTenantContext context ) throws CatalogApiException , SubscriptionBaseApiException { return getTimedPhaseOnChange ( subscription , plan , effectiveDate , newPlanInitialPhaseType , WhichPhase . CURRENT , catalog , context ) ; }
Returns current Phase for that Plan change
19,866
public TimedPhase getNextTimedPhase ( final DefaultSubscriptionBase subscription , final DateTime effectiveDate , final Catalog catalog , final InternalTenantContext context ) { try { final SubscriptionBaseTransition pendingOrLastPlanTransition ; if ( subscription . getState ( ) == EntitlementState . PENDING ) { pendingOrLastPlanTransition = subscription . getPendingTransition ( ) ; } else { pendingOrLastPlanTransition = subscription . getLastTransitionForCurrentPlan ( ) ; } switch ( pendingOrLastPlanTransition . getTransitionType ( ) ) { case CREATE : case TRANSFER : final List < TimedPhase > timedPhases = getTimedPhaseOnCreate ( subscription . getAlignStartDate ( ) , subscription . getBundleStartDate ( ) , pendingOrLastPlanTransition . getNextPlan ( ) , pendingOrLastPlanTransition . getNextPhase ( ) . getPhaseType ( ) , catalog , subscription . getAlignStartDate ( ) , context ) ; return getTimedPhase ( timedPhases , effectiveDate , WhichPhase . NEXT ) ; case CHANGE : return getTimedPhaseOnChange ( subscription . getAlignStartDate ( ) , subscription . getBundleStartDate ( ) , pendingOrLastPlanTransition . getPreviousPhase ( ) , pendingOrLastPlanTransition . getPreviousPlan ( ) , pendingOrLastPlanTransition . getNextPlan ( ) , effectiveDate , subscription . getAlignStartDate ( ) , pendingOrLastPlanTransition . getEffectiveTransitionTime ( ) , subscription . getAllTransitions ( ) . get ( 0 ) . getNextPhase ( ) . getPhaseType ( ) , null , WhichPhase . NEXT , catalog , context ) ; default : throw new SubscriptionBaseError ( String . format ( "Unexpected initial transition %s for current plan %s on subscription %s" , pendingOrLastPlanTransition . getTransitionType ( ) , subscription . getCurrentPlan ( ) , subscription . getId ( ) ) ) ; } } catch ( Exception e ) { throw new SubscriptionBaseError ( String . format ( "Could not compute next phase change for subscription %s" , subscription . getId ( ) ) , e ) ; } }
Returns next Phase for that SubscriptionBase at a point in time
19,867
private TimedPhase getTimedPhase ( final List < TimedPhase > timedPhases , final DateTime effectiveDate , final WhichPhase which ) { TimedPhase cur = null ; TimedPhase next = null ; for ( final TimedPhase phase : timedPhases ) { if ( phase . getStartPhase ( ) . isAfter ( effectiveDate ) ) { next = phase ; break ; } cur = phase ; } switch ( which ) { case CURRENT : return cur ; case NEXT : return next ; default : throw new SubscriptionBaseError ( String . format ( "Unexpected %s TimedPhase" , which ) ) ; } }
STEPH check for non evergreen Plans and what happens
19,868
private org . ehcache . CacheManager getEhcacheManager ( ) { try { final Field f = eh107CacheManager . getClass ( ) . getDeclaredField ( "ehCacheManager" ) ; f . setAccessible ( true ) ; return ( org . ehcache . CacheManager ) f . get ( eh107CacheManager ) ; } catch ( final IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( final NoSuchFieldException e ) { throw new RuntimeException ( e ) ; } }
Shiro isn t JCache compatible
19,869
public void buildForMissingInterval ( final LocalDate startDate , final LocalDate endDate , final UUID targetInvoiceId , final Collection < Item > output , final boolean addRepair ) { final Item item = createNewItem ( startDate , endDate , targetInvoiceId , addRepair ) ; if ( item != null ) { output . add ( item ) ; } }
Called for missing service periods
19,870
public void buildFromItems ( final Collection < Item > output , final boolean mergeMode ) { buildForMissingInterval ( null , null , null , output , mergeMode ) ; }
Called on the last node
19,871
private static BigDecimal calculateProrationBetweenDates ( final LocalDate startDate , final LocalDate endDate , final LocalDate previousBillingCycleDate , final LocalDate nextBillingCycleDate ) { final int daysBetween = Days . daysBetween ( previousBillingCycleDate , nextBillingCycleDate ) . getDays ( ) ; return calculateProrationBetweenDates ( startDate , endDate , daysBetween ) ; }
Called internally to calculate proration or when we recalculate approximate repair amount
19,872
private TransactionStatus computeNewTransactionStatusFromPaymentTransactionInfoPlugin ( final PaymentTransactionInfoPlugin input , final TransactionStatus currentTransactionStatus ) { final TransactionStatus newTransactionStatus = PaymentTransactionInfoPluginConverter . toTransactionStatus ( input ) ; return ( newTransactionStatus != TransactionStatus . UNKNOWN ) ? newTransactionStatus : currentTransactionStatus ; }
Keep the existing currentTransactionStatus if we can t obtain a better answer from the plugin ; if not return the newTransactionStatus
19,873
private int insertFromBlockingEvent ( final Collection < UUID > allEntitlementUUIDs , final BlockingState currentBlockingState , final List < SubscriptionEvent > inputExistingEvents , final SupportForOlderVersionThan_0_17_X backwardCompatibleContext , final InternalTenantContext internalTenantContext , final Collection < SubscriptionEvent > outputNewEvents ) { final Map < UUID , TargetState > targetStates = new HashMap < UUID , TargetState > ( ) ; for ( final UUID cur : allEntitlementUUIDs ) { targetStates . put ( cur , new TargetState ( ) ) ; } int index = - 1 ; final Iterator < SubscriptionEvent > it = inputExistingEvents . iterator ( ) ; DefaultSubscriptionEvent curInsertion = null ; while ( it . hasNext ( ) ) { final DefaultSubscriptionEvent cur = ( DefaultSubscriptionEvent ) it . next ( ) ; final int compEffectiveDate = currentBlockingState . getEffectiveDate ( ) . compareTo ( cur . getEffectiveDateTime ( ) ) ; final boolean shouldContinue ; switch ( compEffectiveDate ) { case - 1 : shouldContinue = false ; break ; case 0 : shouldContinue = compareBlockingStateWithNextSubscriptionEvent ( currentBlockingState , cur ) > 0 ; break ; case 1 : shouldContinue = true ; break ; default : throw new IllegalStateException ( "Cannot reach statement" ) ; } if ( ! shouldContinue ) { break ; } index ++ ; final TargetState curTargetState = targetStates . get ( cur . getEntitlementId ( ) ) ; switch ( cur . getSubscriptionEventType ( ) ) { case START_ENTITLEMENT : curTargetState . setEntitlementStarted ( ) ; break ; case STOP_ENTITLEMENT : curTargetState . setEntitlementStopped ( ) ; break ; case START_BILLING : if ( backwardCompatibleContext . isOlderEntitlement ( cur . getEntitlementId ( ) ) ) { curTargetState . setEntitlementStarted ( ) ; } curTargetState . setBillingStarted ( ) ; break ; case PAUSE_BILLING : case PAUSE_ENTITLEMENT : case RESUME_ENTITLEMENT : case RESUME_BILLING : case SERVICE_STATE_CHANGE : curTargetState . addEntitlementEvent ( cur ) ; break ; case STOP_BILLING : curTargetState . setBillingStopped ( ) ; break ; } curInsertion = cur ; } final List < UUID > targetEntitlementIds = currentBlockingState . getType ( ) == BlockingStateType . SUBSCRIPTION ? ImmutableList . < UUID > of ( currentBlockingState . getBlockedId ( ) ) : ImmutableList . < UUID > copyOf ( allEntitlementUUIDs ) ; for ( final UUID targetEntitlementId : targetEntitlementIds ) { final SubscriptionEvent [ ] prevNext = findPrevNext ( inputExistingEvents , targetEntitlementId , curInsertion ) ; final TargetState curTargetState = targetStates . get ( targetEntitlementId ) ; final List < SubscriptionEventType > eventTypes = curTargetState . addStateAndReturnEventTypes ( currentBlockingState ) ; for ( final SubscriptionEventType t : eventTypes ) { outputNewEvents . add ( toSubscriptionEvent ( prevNext [ 0 ] , prevNext [ 1 ] , targetEntitlementId , currentBlockingState , t , internalTenantContext ) ) ; } } return index ; }
Returns the index and the newEvents generated from the incoming blocking state event . Those new events will all be created for the same effectiveDate and should be ordered .
19,874
private SubscriptionEvent [ ] findPrevNext ( final List < SubscriptionEvent > events , final UUID targetEntitlementId , final SubscriptionEvent insertionEvent ) { final SubscriptionEvent [ ] result = new DefaultSubscriptionEvent [ 2 ] ; if ( insertionEvent == null ) { result [ 0 ] = null ; result [ 1 ] = ! events . isEmpty ( ) ? events . get ( 0 ) : null ; return result ; } final Iterator < SubscriptionEvent > it = events . iterator ( ) ; DefaultSubscriptionEvent prev = null ; DefaultSubscriptionEvent next = null ; boolean foundCur = false ; while ( it . hasNext ( ) ) { final DefaultSubscriptionEvent tmp = ( DefaultSubscriptionEvent ) it . next ( ) ; if ( tmp . getEntitlementId ( ) . equals ( targetEntitlementId ) ) { if ( ! foundCur ) { prev = tmp ; } else { next = tmp ; break ; } } if ( tmp . getId ( ) . equals ( insertionEvent . getId ( ) ) && tmp . getSubscriptionEventType ( ) . equals ( insertionEvent . getSubscriptionEventType ( ) ) ) { foundCur = true ; } } result [ 0 ] = prev ; result [ 1 ] = next ; return result ; }
Extract prev and next events in the stream events for that particular target subscription from the insertionEvent
19,875
public < NewSqlDao extends EntitySqlDao < NewEntityModelDao , NewEntity > , NewEntityModelDao extends EntityModelDao < NewEntity > , NewEntity extends Entity > NewSqlDao become ( final Class < NewSqlDao > newSqlDaoClass ) { final NewSqlDao newSqlDao = SqlObjectBuilder . attach ( handle , newSqlDaoClass ) ; return create ( newSqlDaoClass , newSqlDao ) ; }
Get an instance of a specified EntitySqlDao class sharing the same database session as the initial sql dao class with which this wrapper factory was created .
19,876
public void prepare ( ) { for ( JavaClass jc : heap . getAllClasses ( ) ) { for ( TypeFilterStep it : interestingTypes ) { if ( it . evaluate ( jc ) ) { rootClasses . add ( jc . getName ( ) ) ; } } for ( TypeFilterStep bt : blacklistedTypes ) { if ( bt . evaluate ( jc ) ) { blacklist . add ( jc . getName ( ) ) ; } } for ( PathStep [ ] bp : blacklistedMethods ) { TypeFilterStep ts = ( TypeFilterStep ) bp [ 0 ] ; String fn = ( ( FieldStep ) bp [ 1 ] ) . getFieldName ( ) ; if ( ts . evaluate ( jc ) ) { for ( Field f : jc . getFields ( ) ) { if ( fn == null || fn . equals ( f . getName ( ) ) ) { blacklist . add ( jc . getName ( ) + "#" + f . getName ( ) ) ; } } } } } }
Process entry point and blacklist configuration
19,877
private void init ( int initCapacity ) { assert ( initCapacity & - initCapacity ) == initCapacity ; assert initCapacity >= MINIMUM_CAPACITY ; assert initCapacity <= MAXIMUM_CAPACITY ; threshold = ( initCapacity * 3 ) / 4 ; table = new long [ 2 * initCapacity ] ; }
Initializes object to be an empty map with the specified initial capacity which is assumed to be a power of two between MINIMUM_CAPACITY and MAXIMUM_CAPACITY inclusive .
19,878
private void resize ( int newCapacity ) { int newLength = newCapacity * 2 ; long [ ] oldTable = table ; int oldLength = oldTable . length ; if ( oldLength == 2 * MAXIMUM_CAPACITY ) { if ( threshold == MAXIMUM_CAPACITY - 1 ) throw new IllegalStateException ( "Capacity exhausted." ) ; threshold = MAXIMUM_CAPACITY - 1 ; return ; } if ( oldLength >= newLength ) return ; long [ ] newTable = new long [ newLength ] ; threshold = ( newCapacity * 3 ) / 4 ; for ( int j = 0 ; j < oldLength ; j += 2 ) { long key = oldTable [ j ] ; if ( key != 0 ) { long value = oldTable [ j + 1 ] ; int i = hash ( key , newLength ) ; while ( newTable [ i ] != 0 ) i = nextKeyIndex ( i , newLength ) ; newTable [ i ] = key ; newTable [ i + 1 ] = value ; } } table = newTable ; }
Resize the table to hold given capacity .
19,879
public static byte [ ] readMagic ( InputStream is ) throws IOException { byte [ ] buf = new byte [ 32 ] ; int n = 0 ; while ( true ) { int c = is . read ( ) ; if ( c < 0 ) { throw new EOFException ( "Cannot read magic" ) ; } if ( n >= buf . length ) { throw new IOException ( "Cannot read magic" ) ; } if ( c == ' ' ) { buf [ n ] = ( byte ) c ; ++ n ; break ; } else if ( MAGIC_APHLABET . indexOf ( c ) >= 0 ) { buf [ n ] = ( byte ) c ; } else { throw new IOException ( "Invalid magic" ) ; } ++ n ; } return Arrays . copyOf ( buf , n ) ; }
reads chars until space
19,880
private void breakCage ( String ... args ) { if ( "false" . equalsIgnoreCase ( System . getProperty ( "sjk.breakCage" , "true" ) ) ) { return ; } RuntimeMXBean rtBean = ManagementFactory . getRuntimeMXBean ( ) ; String spec = rtBean . getSpecVersion ( ) ; if ( spec . startsWith ( "1." ) ) { if ( verbose ) { System . out . println ( "Java version " + spec + " skipping cage break" ) ; } return ; } else { if ( getModulesUnlockCommand ( ) . length > 0 ) { StringBuilder sb = new StringBuilder ( ) ; for ( String a : rtBean . getInputArguments ( ) ) { if ( sb . length ( ) > 0 ) { sb . append ( " " ) ; } sb . append ( a ) ; } if ( isUnlocked ( sb . toString ( ) ) ) { if ( verbose ) { System . out . println ( "All required modules are unlocked, skipping cage break" ) ; } return ; } else { List < String > command = new ArrayList < String > ( ) ; File jhome = new File ( System . getProperty ( "java.home" ) ) ; File jbin = new File ( jhome , "bin/java" ) ; command . add ( jbin . getPath ( ) ) ; for ( String m : getModulesUnlockCommand ( ) ) { command . add ( "--add-opens" ) ; command . add ( m ) ; } command . add ( "-Dsjk.breakCage=false" ) ; command . add ( "-cp" ) ; command . add ( rtBean . getClassPath ( ) ) ; command . addAll ( rtBean . getInputArguments ( ) ) ; command . add ( this . getClass ( ) . getName ( ) ) ; command . addAll ( Arrays . asList ( args ) ) ; System . err . println ( "Restarting java with unlocked package access" ) ; if ( verbose ) { System . err . println ( "Exec command: " + formatCmd ( command ) ) ; } ProcessSpawner . start ( command ) ; } } } }
special hack to workaround Java module system
19,881
public final int writeFieldName ( String name ) { if ( _type == TYPE_OBJECT ) { if ( _currentName != null ) { return STATUS_EXPECT_VALUE ; } _currentName = name ; return ( _index < 0 ) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA ; } return STATUS_EXPECT_VALUE ; }
Method that writer is to call before it writes a field name .
19,882
private void _writeLongString ( String text ) throws IOException , JsonGenerationException { _flushBuffer ( ) ; final int textLen = text . length ( ) ; int offset = 0 ; do { int max = _outputEnd ; int segmentLen = ( ( offset + max ) > textLen ) ? ( textLen - offset ) : max ; text . getChars ( offset , offset + segmentLen , _outputBuffer , 0 ) ; if ( _maximumNonEscapedChar != 0 ) { _writeSegmentASCII ( segmentLen , _maximumNonEscapedChar ) ; } else { _writeSegment ( segmentLen ) ; } offset += segmentLen ; } while ( offset < textLen ) ; }
Method called to write long strings strings whose length exceeds output buffer length .
19,883
private final void _writeString ( char [ ] text , int offset , int len ) throws IOException , JsonGenerationException { if ( _maximumNonEscapedChar != 0 ) { _writeStringASCII ( text , offset , len , _maximumNonEscapedChar ) ; return ; } len += offset ; final int [ ] escCodes = _outputEscapes ; final int escLen = escCodes . length ; while ( offset < len ) { int start = offset ; while ( true ) { char c = text [ offset ] ; if ( c < escLen && escCodes [ c ] != 0 ) { break ; } if ( ++ offset >= len ) { break ; } } int newAmount = offset - start ; if ( newAmount < SHORT_WRITE ) { if ( ( _outputTail + newAmount ) > _outputEnd ) { _flushBuffer ( ) ; } if ( newAmount > 0 ) { System . arraycopy ( text , start , _outputBuffer , _outputTail , newAmount ) ; _outputTail += newAmount ; } } else { _flushBuffer ( ) ; _writer . write ( text , start , newAmount ) ; } if ( offset >= len ) { break ; } char c = text [ offset ++ ] ; _appendCharacterEscape ( c , escCodes [ c ] ) ; } }
This method called when the string content is already in a char buffer and need not be copied for processing .
19,884
protected void _writeSimpleObject ( Object value ) throws IOException , JsonGenerationException { if ( value == null ) { writeNull ( ) ; return ; } if ( value instanceof String ) { writeString ( ( String ) value ) ; return ; } if ( value instanceof Number ) { Number n = ( Number ) value ; if ( n instanceof Integer ) { writeNumber ( n . intValue ( ) ) ; return ; } else if ( n instanceof Long ) { writeNumber ( n . longValue ( ) ) ; return ; } else if ( n instanceof Double ) { writeNumber ( n . doubleValue ( ) ) ; return ; } else if ( n instanceof Float ) { writeNumber ( n . floatValue ( ) ) ; return ; } else if ( n instanceof Short ) { writeNumber ( n . shortValue ( ) ) ; return ; } else if ( n instanceof Byte ) { writeNumber ( n . byteValue ( ) ) ; return ; } else if ( n instanceof BigInteger ) { writeNumber ( ( BigInteger ) n ) ; return ; } else if ( n instanceof BigDecimal ) { writeNumber ( ( BigDecimal ) n ) ; return ; } else if ( n instanceof AtomicInteger ) { writeNumber ( ( ( AtomicInteger ) n ) . get ( ) ) ; return ; } else if ( n instanceof AtomicLong ) { writeNumber ( ( ( AtomicLong ) n ) . get ( ) ) ; return ; } } else if ( value instanceof Boolean ) { writeBoolean ( ( ( Boolean ) value ) . booleanValue ( ) ) ; return ; } else if ( value instanceof AtomicBoolean ) { writeBoolean ( ( ( AtomicBoolean ) value ) . get ( ) ) ; return ; } throw new IllegalStateException ( "No ObjectCodec defined for the generator, can only serialize simple wrapper types (type passed " + value . getClass ( ) . getName ( ) + ")" ) ; }
Helper method to try to call appropriate write method for given untyped Object . At this point no structural conversions should be done only simple basic types are to be coerced as necessary .
19,885
public String getMessage ( ) { String msg = super . getMessage ( ) ; if ( msg == null ) { msg = "N/A" ; } JsonLocation loc = getLocation ( ) ; if ( loc != null ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( msg ) ; sb . append ( '\n' ) ; sb . append ( " at " ) ; sb . append ( loc . toString ( ) ) ; return sb . toString ( ) ; } return msg ; }
Default method overridden so that we can add location information
19,886
private List < CompletableFuture < Channel > > getChannelPool ( Address address ) { List < CompletableFuture < Channel > > channelPool = channels . get ( address ) ; if ( channelPool != null ) { return channelPool ; } return channels . computeIfAbsent ( address , e -> { List < CompletableFuture < Channel > > defaultList = new ArrayList < > ( size ) ; for ( int i = 0 ; i < size ; i ++ ) { defaultList . add ( null ) ; } return Lists . newCopyOnWriteArrayList ( defaultList ) ; } ) ; }
Returns the channel pool for the given address .
19,887
CompletableFuture < Channel > getChannel ( Address address , String messageType ) { List < CompletableFuture < Channel > > channelPool = getChannelPool ( address ) ; int offset = getChannelOffset ( messageType ) ; CompletableFuture < Channel > channelFuture = channelPool . get ( offset ) ; if ( channelFuture == null || channelFuture . isCompletedExceptionally ( ) ) { synchronized ( channelPool ) { channelFuture = channelPool . get ( offset ) ; if ( channelFuture == null || channelFuture . isCompletedExceptionally ( ) ) { LOGGER . debug ( "Connecting to {}" , address ) ; channelFuture = factory . apply ( address ) ; channelFuture . whenComplete ( ( channel , error ) -> { if ( error == null ) { LOGGER . debug ( "Connected to {}" , channel . remoteAddress ( ) ) ; } else { LOGGER . debug ( "Failed to connect to {}" , address , error ) ; } } ) ; channelPool . set ( offset , channelFuture ) ; } } } final CompletableFuture < Channel > future = new CompletableFuture < > ( ) ; final CompletableFuture < Channel > finalFuture = channelFuture ; finalFuture . whenComplete ( ( channel , error ) -> { if ( error == null ) { if ( ! channel . isActive ( ) ) { CompletableFuture < Channel > currentFuture ; synchronized ( channelPool ) { currentFuture = channelPool . get ( offset ) ; if ( currentFuture == finalFuture ) { channelPool . set ( offset , null ) ; } else if ( currentFuture == null ) { currentFuture = factory . apply ( address ) ; currentFuture . whenComplete ( ( c , e ) -> { if ( e == null ) { LOGGER . debug ( "Connected to {}" , channel . remoteAddress ( ) ) ; } else { LOGGER . debug ( "Failed to connect to {}" , channel . remoteAddress ( ) , e ) ; } } ) ; channelPool . set ( offset , currentFuture ) ; } } if ( currentFuture == finalFuture ) { getChannel ( address , messageType ) . whenComplete ( ( recursiveResult , recursiveError ) -> { if ( recursiveError == null ) { future . complete ( recursiveResult ) ; } else { future . completeExceptionally ( recursiveError ) ; } } ) ; } else { currentFuture . whenComplete ( ( recursiveResult , recursiveError ) -> { if ( recursiveError == null ) { future . complete ( recursiveResult ) ; } else { future . completeExceptionally ( recursiveError ) ; } } ) ; } } else { future . complete ( channel ) ; } } else { future . completeExceptionally ( error ) ; } } ) ; return future ; }
Gets or creates a pooled channel to the given address for the given message type .
19,888
public < V > Match < V > map ( Function < T , V > mapper ) { if ( matchAny ) { return any ( ) ; } else if ( value == null ) { return negation ? ifNotNull ( ) : ifNull ( ) ; } else { return negation ? ifNotValue ( mapper . apply ( value ) ) : ifValue ( mapper . apply ( value ) ) ; } }
Maps this instance to a Match of another type .
19,889
public boolean matches ( T other ) { if ( matchAny ) { return true ; } else if ( other == null ) { return negation ? value != null : value == null ; } else { if ( value instanceof byte [ ] ) { boolean equal = Arrays . equals ( ( byte [ ] ) value , ( byte [ ] ) other ) ; return negation ? ! equal : equal ; } return negation ? ! Objects . equals ( value , other ) : Objects . equals ( value , other ) ; } }
Checks if this instance matches specified value .
19,890
private void completeFutures ( ) { long commitIndex = queues . values ( ) . stream ( ) . map ( queue -> queue . ackedIndex ) . reduce ( Math :: min ) . orElse ( 0L ) ; for ( long i = context . getCommitIndex ( ) + 1 ; i <= commitIndex ; i ++ ) { CompletableFuture < Void > future = futures . remove ( i ) ; if ( future != null ) { future . complete ( null ) ; } } context . setCommitIndex ( commitIndex ) ; }
Completes futures .
19,891
void map ( ByteBuffer buffer ) { if ( ! ( reader instanceof MappedJournalSegmentReader ) ) { JournalReader < E > reader = this . reader ; this . reader = new MappedJournalSegmentReader < > ( buffer , segment , maxEntrySize , index , namespace ) ; this . reader . reset ( reader . getNextIndex ( ) ) ; reader . close ( ) ; } }
Converts the reader to a mapped reader using the given buffer .
19,892
void unmap ( ) { if ( reader instanceof MappedJournalSegmentReader ) { JournalReader < E > reader = this . reader ; this . reader = new FileChannelJournalSegmentReader < > ( channel , segment , maxEntrySize , index , namespace ) ; this . reader . reset ( reader . getNextIndex ( ) ) ; reader . close ( ) ; } }
Converts the reader to an unmapped reader .
19,893
private void compactBySize ( ) { if ( maxLogSize > 0 && journal . size ( ) > maxLogSize ) { JournalSegment < LogEntry > compactSegment = null ; Long compactIndex = null ; for ( JournalSegment < LogEntry > segment : journal . segments ( ) ) { Collection < JournalSegment < LogEntry > > remainingSegments = journal . segments ( segment . lastIndex ( ) + 1 ) ; long remainingSize = remainingSegments . stream ( ) . mapToLong ( JournalSegment :: size ) . sum ( ) ; if ( remainingSize > maxLogSize ) { log . debug ( "Found outsize journal segment {}" , segment . file ( ) . file ( ) ) ; compactSegment = segment ; } else if ( compactSegment != null ) { compactIndex = segment . index ( ) ; break ; } } if ( compactIndex != null ) { log . info ( "Compacting journal by size up to {}" , compactIndex ) ; journal . compact ( compactIndex ) ; } } }
Compacts the log by size .
19,894
private void compactByAge ( ) { if ( maxLogAge != null ) { long currentTime = System . currentTimeMillis ( ) ; JournalSegment < LogEntry > compactSegment = null ; Long compactIndex = null ; for ( JournalSegment < LogEntry > segment : journal . segments ( ) ) { if ( currentTime - segment . descriptor ( ) . updated ( ) > maxLogAge . toMillis ( ) ) { log . debug ( "Found expired journal segment {}" , segment . file ( ) . file ( ) ) ; compactSegment = segment ; } else if ( compactSegment != null ) { compactIndex = segment . index ( ) ; break ; } } if ( compactIndex != null ) { log . info ( "Compacting journal by age up to {}" , compactIndex ) ; journal . compact ( compactIndex ) ; } } }
Compacts the log by age .
19,895
public void delete ( ) { try { Files . walkFileTree ( partition . dataDirectory ( ) . toPath ( ) , new SimpleFileVisitor < Path > ( ) { public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { Files . delete ( file ) ; return FileVisitResult . CONTINUE ; } public FileVisitResult postVisitDirectory ( Path dir , IOException exc ) throws IOException { Files . delete ( dir ) ; return FileVisitResult . CONTINUE ; } } ) ; } catch ( IOException e ) { log . error ( "Failed to delete partition: {}" , e ) ; } }
Deletes the server .
19,896
private void openProxy ( CompletableFuture < SessionClient > future ) { log . debug ( "Opening proxy session" ) ; proxyFactory . get ( ) . thenCompose ( proxy -> proxy . connect ( ) ) . whenComplete ( ( proxy , error ) -> { if ( error == null ) { synchronized ( this ) { this . log = ContextualLoggerFactory . getLogger ( getClass ( ) , LoggerContext . builder ( SessionClient . class ) . addValue ( proxy . sessionId ( ) ) . add ( "type" , proxy . type ( ) ) . add ( "name" , proxy . name ( ) ) . build ( ) ) ; this . session = proxy ; proxy . addStateChangeListener ( this :: onStateChange ) ; eventListeners . entries ( ) . forEach ( entry -> proxy . addEventListener ( entry . getKey ( ) , entry . getValue ( ) ) ) ; onStateChange ( PrimitiveState . CONNECTED ) ; } future . complete ( this ) ; } else { recoverTask = context . schedule ( Duration . ofSeconds ( 1 ) , ( ) -> openProxy ( future ) ) ; } } ) ; }
Opens a new client completing the provided future only once the client has been opened .
19,897
public static ThreadFactory namedThreads ( String pattern , Logger log ) { return new ThreadFactoryBuilder ( ) . setNameFormat ( pattern ) . setThreadFactory ( new AtomixThreadFactory ( ) ) . setUncaughtExceptionHandler ( ( t , e ) -> log . error ( "Uncaught exception on " + t . getName ( ) , e ) ) . build ( ) ; }
Returns a thread factory that produces threads named according to the supplied name pattern .
19,898
private void handleClusterMembershipEvent ( ClusterMembershipEvent event ) { if ( event . type ( ) == ClusterMembershipEvent . Type . MEMBER_ADDED || event . type ( ) == ClusterMembershipEvent . Type . MEMBER_REMOVED ) { recomputeTerm ( groupMembershipService . getMembership ( partitionId . group ( ) ) ) ; } }
Handles a cluster membership event .
19,899
private long incrementTerm ( ) { counters . compute ( clusterMembershipService . getLocalMember ( ) . id ( ) , ( id , value ) -> value != null ? value + 1 : 1 ) ; broadcastCounters ( ) ; return currentTerm ( ) ; }
Increments and returns the current term .