idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
40,700
|
public static String toReadableLabel ( String value ) { StringBuilder ret = new StringBuilder ( ) ; char lastChar = 'x' ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char currentChar = value . charAt ( i ) ; if ( ( i == 0 || lastChar == ' ' ) && ! ( isSeparator ( currentChar ) ) ) { currentChar = Character . toUpperCase ( currentChar ) ; } else if ( Character . isLowerCase ( lastChar ) && Character . isUpperCase ( currentChar ) ) { ret . append ( ' ' ) ; } else if ( isSeparator ( currentChar ) ) { currentChar = ' ' ; } if ( ! ( lastChar == ' ' && currentChar == ' ' ) ) { ret . append ( currentChar ) ; lastChar = currentChar ; } } if ( ret . toString ( ) . startsWith ( "Is " ) || ret . toString ( ) . startsWith ( "Has " ) ) { ret . append ( '?' ) ; } return ret . toString ( ) ; }
|
Convert strings such as bankAccountSummary to Bank Account Summary
|
40,701
|
public static boolean endsWithIgnoreCase ( String name , Iterable < String > patterns ) { String nameUpper = name . toUpperCase ( ) ; for ( String pattern : patterns ) { String patternUpper = pattern . toUpperCase ( ) ; if ( nameUpper . equals ( patternUpper ) || nameUpper . endsWith ( patternUpper ) ) { return true ; } } return false ; }
|
Does the given column name ends with one of pattern given in parameter . Not case sensitive
|
40,702
|
public static boolean startsWithIgnoreCase ( String name , Iterable < String > patterns ) { String nameUpper = name . toUpperCase ( ) ; for ( String pattern : patterns ) { String patternUpper = pattern . toUpperCase ( ) ; if ( nameUpper . equals ( patternUpper ) || nameUpper . startsWith ( patternUpper ) ) { return true ; } } return false ; }
|
Does the given column name starts with one of pattern given in parameter Not case sensitive
|
40,703
|
public static boolean contains ( String name , Iterable < String > patterns ) { String nameUpper = name . toUpperCase ( ) ; for ( String pattern : patterns ) { String patternUpper = pattern . toUpperCase ( ) ; if ( nameUpper . equals ( patternUpper ) || nameUpper . contains ( patternUpper ) ) { return true ; } } return false ; }
|
Does the given column name contains one of pattern given in parameter Not case sensitive
|
40,704
|
public static boolean equalsIgnoreCase ( String name , Iterable < String > patterns ) { for ( String pattern : patterns ) { if ( name . equalsIgnoreCase ( pattern ) ) { return true ; } } return false ; }
|
Does the given column name equals ignore case with one of pattern given in parameter
|
40,705
|
public static boolean isUniCase ( String value ) { if ( value . toLowerCase ( ) . equals ( value ) || value . toUpperCase ( ) . equals ( value ) ) { return true ; } return false ; }
|
Return true if the passed value is all lower or all upper case .
|
40,706
|
public String getName ( ) { if ( name == null ) { return null ; } if ( name . endsWith ( "_INDEX_2" ) ) { return removeEnd ( name , "_INDEX_2" ) ; } return name ; }
|
H2 does append _INDEX_2 to unique constraints names
|
40,707
|
public void require ( Namer packageNamer , Namer classNamer ) { requireFirstTime ( packageNamer . getPackageName ( ) + "." + classNamer . getType ( ) ) ; }
|
Import the passed classNamer s type present in the passed packageNamer s package name .
|
40,708
|
public boolean requireFirstTime ( Attribute attribute ) { if ( ! attribute . isJavaBaseClass ( ) ) { return ImportsContext . getCurrentImportsHolder ( ) . add ( attribute . getFullType ( ) ) ; } return false ; }
|
Import the passed attribute type .
|
40,709
|
public List < String > getAnnotations ( ) { if ( attribute . getColumnConfig ( ) . getCustomAnnotations ( ) == null ) { return newArrayList ( ) ; } AnnotationBuilder builder = new AnnotationBuilder ( ) ; for ( CustomAnnotation ca : attribute . getColumnConfig ( ) . getCustomAnnotations ( ) ) { addImport ( ca . extractAnnotationImport ( ) ) ; builder . add ( ca . getAnnotation ( ) ) ; } return builder . getAnnotations ( ) ; }
|
Return the custom annotations declared in the configuration .
|
40,710
|
public String getNotNullAnnotation ( ) { if ( ! relation . isManyToOne ( ) && ! relation . isOneToOne ( ) ) { return "" ; } if ( relation . isMandatory ( ) && ! relation . hasInverse ( ) ) { if ( relation . getFromEntity ( ) . getName ( ) . equals ( relation . getToEntity ( ) . getName ( ) ) ) { return "" ; } if ( relation . getFromAttribute ( ) . isInPk ( ) ) { return "" ; } ImportsContext . addImport ( "javax.validation.constraints.NotNull" ) ; return "@NotNull" ; } else { return "" ; } }
|
Applies only to ManyToOne or OneToOne . When x to one has an inverse relation we never mark it as
|
40,711
|
public void removeVar ( String entityType , String attributeVar ) { fullVars . remove ( clashKey ( entityType , attributeVar ) ) ; }
|
During construction we may free a var .
|
40,712
|
public Namer getManyToManyNamer ( Namer fromEntityNamer , ColumnConfig pointsOnToEntity , Namer toEntityNamer ) { Namer result = getManyToManyNamerFromConf ( pointsOnToEntity . getManyToManyConfig ( ) , toEntityNamer ) ; if ( result == null ) { result = getManyToManyNamerFallBack ( fromEntityNamer , pointsOnToEntity , toEntityNamer ) ; } return result ; }
|
Compute the appropriate namer for the Java field marked by
|
40,713
|
private byte [ ] getAsByteArray ( String template ) throws IOException { if ( isTemplateGivenAsAnAbsoluteFile ( template ) ) { throw new IllegalArgumentException ( "Template " + template + " should not be given as an absolute file" ) ; } if ( ! containsTemplate ( template ) ) { throw new IllegalArgumentException ( "Template " + template + " is not a template" ) ; } java . io . InputStream is = null ; try { is = new FileInputStream ( getAbsoluteTemplate ( template ) ) ; return toByteArray ( is ) ; } finally { closeQuietly ( is ) ; } }
|
Extract a template from the jar as a byte array
|
40,714
|
private String getSpecificJoinFetchAnnotation ( ) { List < Relation > manyToManyRelations = relation . getToEntity ( ) . getManyToMany ( ) . getList ( ) ; if ( manyToManyRelations . size ( ) <= 1 ) { return null ; } for ( Relation relation : manyToManyRelations ) { if ( relation . getFetchTypeGetter ( ) != null && relation . getFetchTypeGetter ( ) . getFetch ( ) != null && relation . getFetchTypeGetter ( ) . getFetch ( ) . isEager ( ) ) { addImport ( "org.hibernate.annotations.Fetch" ) ; addImport ( "org.hibernate.annotations.FetchMode" ) ; return "@Fetch(value = FetchMode.SUBSELECT)" ; } } return null ; }
|
When you have multiple eager bags you need to specify how you want to make them eager .
|
40,715
|
public void putEntity ( Entity entity ) { Assert . isTrue ( entity . hasTableName ( ) , "Expecting a table name for the entity: " + entity . getName ( ) ) ; Assert . isTrue ( ! hasEntityBySchemaAndTableName ( entity . getTable ( ) . getSchemaName ( ) , entity . getTable ( ) . getName ( ) ) , "Entity was already added!: " + entity . getTableName ( ) ) ; currentEntitiesByTableName . put ( entity . getTable ( ) . getName ( ) . toUpperCase ( ) , entity ) ; currentEntitiesBySchemaAndTableName . put ( entity . getTable ( ) . asKeyForMap ( ) , entity ) ; }
|
Store 1 entity per table name . In case of inheritance you must pass the root entity only .
|
40,716
|
public Entity getEntityBySchemaAndTableName ( String schemaName , String tableName ) { return currentEntitiesBySchemaAndTableName . get ( Table . keyForMap ( schemaName , tableName ) ) ; }
|
Return the entity corresponding to the passed table . In case of inheritance the root entity is returned .
|
40,717
|
private void checkForeignKeyMapping ( List < String > errors , Config config ) { for ( Entity entity : config . getProject ( ) . getEntities ( ) . getList ( ) ) { for ( Relation relation : entity . getRelations ( ) . getList ( ) ) { if ( relation . isInverse ( ) || relation . isIntermediate ( ) ) { continue ; } for ( AttributePair attributePair : relation . getAttributePairs ( ) ) { if ( attributePair . getFromAttribute ( ) . getMappedType ( ) != attributePair . getToAttribute ( ) . getMappedType ( ) ) { String errorMsg = "Inconsistent types: Column " + attributePair . getFromAttribute ( ) . getFullColumnName ( ) + "[" + attributePair . getFromAttribute ( ) . getJdbcType ( ) + "] references column " + attributePair . getToAttribute ( ) . getFullColumnName ( ) + "[" + attributePair . getToAttribute ( ) . getJdbcType ( ) + "]. " + "You should really fix your SQL schema." ; if ( attributePair . getFromAttribute ( ) . isInCpk ( ) ) { log . warn ( errorMsg + ". To avoid this error you can force the mapped type using configuration." ) ; } else { log . warn ( errorMsg ) ; } } } } } }
|
Check that foreign keys have the same mapped type as the target .
|
40,718
|
private void checkVersionOnJoinedInheritance ( List < String > errors , Config config ) { for ( Entity entity : config . getProject ( ) . getRootEntities ( ) . getList ( ) ) { if ( entity . hasInheritance ( ) && entity . getInheritance ( ) . is ( JOINED ) ) { for ( Entity child : entity . getAllChildrenRecursive ( ) ) { for ( Attribute attribute : child . getAttributes ( ) . getList ( ) ) { if ( attribute . isVersion ( ) ) { errors . add ( attribute . getFullColumnName ( ) + " is a version column, you should not have @Version in a child joined entity." + " Use ignore=true in columnConfig or remove it from your table." ) ; } } } } } }
|
In case of JOINED inheritance we may have added some columns that are in the table but that are not in the entityConfigs . We check here that we have not added a version column in a child .
|
40,719
|
public List < String > getAnnotations ( ) { AnnotationBuilder annotations = new AnnotationBuilder ( ) ; annotations . add ( getFieldAnnotation ( ) , getFieldBridgeAnnotation ( ) , getTikaBridgeAnnotation ( ) ) ; return annotations . getAnnotations ( ) ; }
|
Returns all the search annotations for the attribute . Imports are processed automatically .
|
40,720
|
public boolean generateIdentifiableMethods ( ) { Assert . isTrue ( isRoot ( ) , "generateIdentifiableMethods() can be invoked only on root entity. Please fix your template." ) ; if ( hasSimplePk ( ) || hasCompositePk ( ) ) { String identifiableProperty = config . getCelerio ( ) . getConfiguration ( ) . getConventions ( ) . getIdentifiableProperty ( ) ; return ! getPrimaryKey ( ) . getVar ( ) . equalsIgnoreCase ( identifiableProperty ) ; } return true ; }
|
Tells whether we should generate identifiable methods . We do not need to generate them in the case where the identifiable property matches exactly the entity s PK field .
|
40,721
|
public List < AttributeBundle > getAttributeBundles ( ) { if ( attributeBundles != null ) { return attributeBundles ; } Map < String , AttributeBundle > bundlesMap = newHashMap ( ) ; for ( Attribute attribute : getAttributes ( ) . getList ( ) ) { if ( attribute . columnNameHasLanguageSuffix ( ) ) { String base = attribute . getColumnNameWithoutLanguage ( ) ; AttributeBundle bundle = bundlesMap . get ( base ) ; if ( bundle == null ) { bundle = new AttributeBundle ( attribute ) ; bundlesMap . put ( base , bundle ) ; } else { bundle . addAttribute ( attribute ) ; } } } attributeBundles = newArrayList ( ) ; for ( AttributeBundle bundle : bundlesMap . values ( ) ) { if ( bundle . getAttributes ( ) . size ( ) > 1 ) { attributeBundles . add ( bundle ) ; log . info ( "Found columns satisfying localization pattern: " + bundle . toString ( ) ) ; } } return attributeBundles ; }
|
we should also check on types .
|
40,722
|
public boolean setupAccount ( Entity e ) { AccountAttributes accountAttributes = new AccountAttributes ( ) ; if ( e . hasCompositePk ( ) ) { return false ; } for ( Attribute a : e . getAttributes ( ) . getList ( ) ) { if ( a . isString ( ) && match ( a . getVar ( ) , usernameCandidates ) && a . isUnique ( ) ) { accountAttributes . setUsername ( a ) ; log . debug ( "'Username' candidate: " + a . getVar ( ) + " found on " + e . getName ( ) ) ; break ; } } if ( ! accountAttributes . isUsernameSet ( ) ) { return false ; } for ( Attribute a : e . getAttributes ( ) . getList ( ) ) { if ( a . isString ( ) && match ( a . getVar ( ) , passwordCandidates ) ) { accountAttributes . setPassword ( a ) ; log . debug ( "'Password' candidate: " + a . getVar ( ) + " found on " + e . getName ( ) ) ; break ; } } if ( ! accountAttributes . isPasswordSet ( ) ) { return false ; } e . setAccountAttributes ( accountAttributes ) ; for ( Attribute a : e . getAttributes ( ) . getList ( ) ) { if ( a . isString ( ) && match ( a . getVar ( ) , emailCandidates ) ) { accountAttributes . setEmail ( a ) ; log . debug ( "'Email' candidate: " + a . getVar ( ) + " found on " + e . getName ( ) ) ; break ; } } for ( Attribute a : e . getAttributes ( ) . getList ( ) ) { if ( a . isBoolean ( ) && match ( a . getVar ( ) , enabledCandidates ) ) { accountAttributes . setEnabled ( a ) ; log . debug ( "'Enabled' candidate: " + a . getVar ( ) + " found on " + e . getName ( ) ) ; break ; } } for ( Relation relation : e . getXToMany ( ) . getList ( ) ) { RoleAttributes roleAttributes = getRoleEntity ( relation . getToEntity ( ) ) ; if ( roleAttributes != null ) { relation . getToEntity ( ) . setRoleAttributes ( roleAttributes ) ; accountAttributes . setRoleRelation ( relation ) ; log . debug ( "'Role' relation detected: " + relation . toString ( ) ) ; break ; } } return true ; }
|
Is this entity the account entity?
|
40,723
|
public boolean isMultiSelectable ( ) { return ( ( ! isInPk ( ) && ! isInFk ( ) && ! isVersion ( ) ) || ( isSimplePk ( ) && jpa . isManuallyAssigned ( ) ) ) && ( isBoolean ( ) || isEnum ( ) || isString ( ) || isNumeric ( ) ) ; }
|
Can we apply a search with a PropertySelector on this attribute?
|
40,724
|
public void execute ( ) throws MojoExecutionException { try { if ( getBootstrapPacksInfo ( ) . isEmpty ( ) ) { getLog ( ) . error ( "Could not find any Celerio Template Pack having a META-INF/celerio.txt file on the classpath!" ) ; return ; } celerioWelcomeBanner ( ) ; JdbcConnectivity jdbcConnectivity = null ; if ( useCommandLineParameters ( ) ) { jdbcConnectivity = setUpParamValuesAndReturnJdbcConnectivity ( ) ; TemplatePackInfo tpi = getBootstrapPackInfoByName ( bootstrapPackName ) ; packCommand = tpi . getCommand ( ) ; packCommandHelp = tpi . getCommandHelp ( ) ; } else { if ( isInteractive ( ) ) { startInteractiveConfWizard ( ) ; } else { useDefaultConf ( ) ; } } runCelerioInBootstrapMode ( jdbcConnectivity ) ; copySqlConf ( ) ; copyCelerioXsd ( ) ; printInstructionsOnceBootstrapIsReady ( ) ; } catch ( Exception e ) { getLog ( ) . error ( e . getMessage ( ) ) ; throw new MojoExecutionException ( e . getLocalizedMessage ( ) , e ) ; } }
|
Mojo entry point .
|
40,725
|
private void startInteractiveConfWizard ( ) throws IOException { BufferedReader br = null ; try { br = new BufferedReader ( new InputStreamReader ( System . in ) ) ; System . out . println ( "" ) ; chooseBootstrapPack ( br ) ; chooseSampleSqlAndConf ( br ) ; enterAppName ( br ) ; enterPackageName ( br ) ; } finally { br . close ( ) ; } }
|
Ask the user all the info we need .
|
40,726
|
private void chooseBootstrapPack ( BufferedReader br ) throws IOException { while ( true ) { printInstruction ( "Choose the type of application you want to generate:" ) ; for ( int i = 0 ; i < getBootstrapPacksInfo ( ) . size ( ) ; i ++ ) { TemplatePackInfo templatePackInfo = getBootstrapPacksInfo ( ) . get ( i ) ; System . out . println ( " " + ( i + 1 ) + ") " + templatePackInfo . getName ( ) ) ; System . out . println ( " " + templatePackInfo . getProjectLink ( ) ) ; System . out . println ( " " + templatePackInfo . getDescription ( ) ) ; if ( templatePackInfo . getDescription2 ( ) != null ) { System . out . println ( " " + templatePackInfo . getDescription2 ( ) ) ; } System . out . println ( "" ) ; } String choice = br . readLine ( ) ; if ( isBlank ( choice ) ) { continue ; } else { try { TemplatePackInfo chosenTemplatePackInfo = getBootstrapPacksInfo ( ) . get ( Integer . parseInt ( choice ) - 1 ) ; bootstrapPackName = chosenTemplatePackInfo . getName ( ) ; System . out . println ( "OK, using: " + chosenTemplatePackInfo . getName ( ) ) ; packCommand = chosenTemplatePackInfo . getCommand ( ) ; packCommandHelp = chosenTemplatePackInfo . getCommandHelp ( ) ; } catch ( Exception e ) { System . out . println ( "" ) ; continue ; } } break ; } }
|
Interactively ask the user which pack should be used .
|
40,727
|
protected List < TemplatePackInfo > getBootstrapPacksInfo ( ) { if ( bootstrapPacksInfo == null ) { bootstrapPacksInfo = getCelerioApplicationContext ( ) . getBean ( ClasspathTemplatePackInfoLoader . class ) . resolveTopLevelPacks ( ) ; } return bootstrapPacksInfo ; }
|
Return the celerio template packs found on the classpath .
|
40,728
|
private void chooseSampleSqlAndConf ( BufferedReader br ) throws IOException { while ( true ) { printInstruction ( "Which sample SQL schema would you like to use?" ) ; for ( int i = 0 ; i < getSqlConfInfos ( ) . size ( ) ; i ++ ) { System . out . println ( " " + ( i + 1 ) + ") " + getSqlConfInfos ( ) . get ( i ) . getName ( ) ) ; System . out . println ( " " + getSqlConfInfos ( ) . get ( i ) . getDescription ( ) ) ; if ( getSqlConfInfos ( ) . get ( i ) . getDescription2 ( ) != null ) { System . out . println ( " " + getSqlConfInfos ( ) . get ( i ) . getDescription2 ( ) ) ; } System . out . println ( "" ) ; } String choice = br . readLine ( ) ; if ( isBlank ( choice ) ) { continue ; } else { try { sqlConfName = getSqlConfInfos ( ) . get ( Integer . parseInt ( choice ) - 1 ) . getName ( ) ; System . out . println ( "OK, using: " + sqlConfName ) ; } catch ( Exception e ) { System . out . println ( "" ) ; continue ; } } break ; } }
|
Interactively ask the user which sql conf should be used .
|
40,729
|
protected List < SqlConfInfo > getSqlConfInfos ( ) { List < SqlConfInfo > packInfos = newArrayList ( ) ; PathMatchingResourcePatternResolver o = new PathMatchingResourcePatternResolver ( ) ; try { Resource packInfosAsResource [ ] = o . getResources ( "classpath*:sqlconf/*/00-info.txt" ) ; for ( Resource r : packInfosAsResource ) { packInfos . add ( new SqlConfInfo ( r ) ) ; } Collections . sort ( packInfos ) ; return packInfos ; } catch ( IOException ioe ) { throw new RuntimeException ( "Error while searching for SQL CONF having a sqlconf/*/00-info.txt file!" , ioe ) ; } }
|
Scan the classpath for SQL configurations .
|
40,730
|
private void enterPackageName ( BufferedReader br ) throws IOException { String suggestedRootPackage = getDefaultRootPackage ( ) + "." + appName ; while ( true ) { printInstruction ( "Enter the Java root package of your application: [" + suggestedRootPackage + "]" ) ; String packageNameCandidate = br . readLine ( ) ; if ( isBlank ( packageNameCandidate ) ) { rootPackage = suggestedRootPackage ; break ; } else { if ( isPackageNameValid ( packageNameCandidate ) ) { rootPackage = packageNameCandidate ; break ; } else { System . out . println ( "Oops! invalid Java package name." ) ; System . out . println ( "" ) ; continue ; } } } }
|
Ask the user to enter the package name .
|
40,731
|
private void enterAppName ( BufferedReader br ) throws IOException { while ( true ) { printInstruction ( "Enter your application name: [" + getDefaultAppName ( ) + "]" ) ; String appNameCandidate = br . readLine ( ) ; if ( isBlank ( appNameCandidate ) ) { appName = getDefaultAppName ( ) ; break ; } else { if ( isPackageNameValid ( getDefaultRootPackage ( ) + "." + appNameCandidate ) ) { appName = appNameCandidate ; break ; } else { System . out . println ( "Oops! invalid application name. Keep it simple, no '-', etc..." ) ; System . out . println ( "" ) ; continue ; } } } }
|
Ask the user to enter the application name .
|
40,732
|
private void printInstruction ( String instruction ) { System . out . println ( StringUtils . repeat ( "-" , instruction . length ( ) ) ) ; System . out . println ( instruction ) ; System . out . println ( StringUtils . repeat ( "-" , instruction . length ( ) ) ) ; }
|
Print the passed instruction in the console .
|
40,733
|
private List < Path > checkDirectories ( List < Path > pathList ) { List < Path > result = new ArrayList < > ( ) ; for ( Path path : pathList ) { if ( ! Files . exists ( path ) ) { LOGGER . debug ( "'{}' does not exist" , path ) ; } else if ( ! Files . isDirectory ( path ) ) { LOGGER . warn ( "'{}' is not directory" , path ) ; } result . add ( path ) ; } return result ; }
|
Check that all elements in the list exist and are directories . Log warning for each element that is not directory .
|
40,734
|
public List < Import > getPublicImports ( ) { return getImports ( ) . stream ( ) . filter ( Import :: isPublic ) . collect ( Collectors . toList ( ) ) ; }
|
Returns all public imports in this proto file .
|
40,735
|
List < PartitionInstance > getAbsent ( ) { List < PartitionInstance > absentPartitions = new ArrayList < > ( ) ; for ( Map . Entry < Integer , List < PartitionInstance > > e : nodeIndexToHostedPartitions . entrySet ( ) ) { if ( e . getKey ( ) < 0 ) { absentPartitions . addAll ( e . getValue ( ) ) ; } } return absentPartitions ; }
|
Returns the partition instances whose node indexes are < 0 .
|
40,736
|
public boolean isMap ( ) { if ( type instanceof Message ) { Message message = ( Message ) type ; return message . isMapEntry ( ) ; } return false ; }
|
Returns true if this message is generated by parser as a holder for a map entries .
|
40,737
|
protected List < String > trim ( List < String > comments ) { List < String > trimComments = new ArrayList < > ( ) ; int n = 0 ; boolean tryRemoveWhitespace = true ; while ( tryRemoveWhitespace ) { boolean allLinesAreShorter = true ; for ( String comment : comments ) { if ( comment . length ( ) <= n ) { continue ; } if ( comment . charAt ( n ) != ' ' ) { tryRemoveWhitespace = false ; } allLinesAreShorter = false ; } if ( allLinesAreShorter ) { break ; } if ( tryRemoveWhitespace ) { n ++ ; } } for ( String comment : comments ) { if ( comment . length ( ) > n ) { String substring = comment . substring ( n ) ; trimComments . add ( substring ) ; } else { trimComments . add ( "" ) ; } } return trimComments ; }
|
Remove common leading whitespaces from all strings in the list . Returns new list instance .
|
40,738
|
public static Deque < String > createScopeLookupList ( UserTypeContainer container ) { String namespace = container . getNamespace ( ) ; Deque < String > scopeLookupList = new ArrayDeque < > ( ) ; int end = 0 ; while ( end >= 0 ) { end = namespace . indexOf ( '.' , end ) ; if ( end >= 0 ) { end ++ ; String scope = namespace . substring ( 0 , end ) ; scopeLookupList . addFirst ( scope ) ; } } return scopeLookupList ; }
|
Create a lookup list for reference resolution .
|
40,739
|
public boolean bufferAckEnabled ( ) { String bufSize = get ( Names . CONNECTION_BUFFER_SIZE ) ; return bufSize != null && Integer . parseInt ( bufSize ) > 0 ; }
|
Shorthand getter to check if buffer acknowledgements are enabled .
|
40,740
|
public int noopIntervalSeconds ( ) { try { return parsePositiveInteger ( get ( Names . SET_NOOP_INTERVAL ) ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( "Bad value for '" + Names . SET_NOOP_INTERVAL . value ( ) + "'; " + e . getMessage ( ) ) ; } }
|
Shorthand getter for the NOOP interval .
|
40,741
|
public Map < String , String > getControls ( Version serverVersion ) { final CompressionMode effectiveMode = compression ( serverVersion ) ; if ( compressionMode != effectiveMode ) { LOGGER . info ( "Couchbase Server version {} does not support {} compression mode; falling back to {}." , serverVersion , compressionMode , effectiveMode ) ; } else { LOGGER . debug ( "Compression mode: {}" , compressionMode ) ; } final Map < String , String > result = new HashMap < > ( values ) ; result . putAll ( effectiveMode . getDcpControls ( serverVersion ) ) ; return result ; }
|
Returns the control settings adjusted for the actual Couchbase Server version .
|
40,742
|
public static ResponseStatus valueOf ( int code ) { code = code & 0xFFFF ; if ( code < 256 ) { ResponseStatus status = values [ code ] ; if ( status != null ) { return status ; } } return new ResponseStatus ( code ) ; }
|
Returns the ResponseStatus with the given status code . For recognized codes this method is guaranteed to always return the same ResponseStatus instance so it s safe to use == for equality checks against the pre - defined constants .
|
40,743
|
private void handleAuthResponse ( final ChannelHandlerContext ctx , final ByteBuf msg ) throws Exception { if ( saslClient . isComplete ( ) ) { checkIsAuthed ( ctx , MessageUtil . getResponseStatus ( msg ) ) ; return ; } ByteBuf challengeBuf = SaslAuthResponse . challenge ( msg ) ; byte [ ] challenge = new byte [ challengeBuf . readableBytes ( ) ] ; challengeBuf . readBytes ( challenge ) ; byte [ ] evaluatedBytes = saslClient . evaluateChallenge ( challenge ) ; if ( evaluatedBytes != null ) { ByteBuf content ; if ( selectedMechanism . equals ( "CRAM-MD5" ) || selectedMechanism . equals ( "PLAIN" ) ) { String [ ] evaluated = new String ( evaluatedBytes ) . split ( " " ) ; content = Unpooled . copiedBuffer ( username + "\0" + evaluated [ 1 ] , CharsetUtil . UTF_8 ) ; } else { content = Unpooled . wrappedBuffer ( evaluatedBytes ) ; } ByteBuf request = ctx . alloc ( ) . buffer ( ) ; SaslStepRequest . init ( request ) ; SaslStepRequest . mechanism ( selectedMechanism , request ) ; SaslStepRequest . challengeResponse ( content , request ) ; ChannelFuture future = ctx . writeAndFlush ( request ) ; future . addListener ( new GenericFutureListener < Future < Void > > ( ) { public void operationComplete ( Future < Void > future ) throws Exception { if ( ! future . isSuccess ( ) ) { LOGGER . warn ( "Error during SASL Auth negotiation phase." , future ) ; originalPromise ( ) . setFailure ( future . cause ( ) ) ; } } } ) ; } else { throw new AuthenticationException ( "SASL Challenge evaluation returned null." ) ; } }
|
Runs the SASL challenge protocol and dispatches the next step if required .
|
40,744
|
private void checkIsAuthed ( final ChannelHandlerContext ctx , final ResponseStatus status ) { if ( status . isSuccess ( ) ) { LOGGER . debug ( "Successfully authenticated against node {}" , ctx . channel ( ) . remoteAddress ( ) ) ; ctx . pipeline ( ) . remove ( this ) ; originalPromise ( ) . setSuccess ( ) ; ctx . fireChannelActive ( ) ; } else if ( status == AUTH_ERROR ) { originalPromise ( ) . setFailure ( new AuthenticationException ( "SASL Authentication Failure" ) ) ; } else { originalPromise ( ) . setFailure ( new AuthenticationException ( "Unhandled SASL auth status: " + status ) ) ; } }
|
Check if the authentication process succeeded or failed based on the response status .
|
40,745
|
private void handleListMechsResponse ( final ChannelHandlerContext ctx , final ByteBuf msg ) throws Exception { String remote = ctx . channel ( ) . remoteAddress ( ) . toString ( ) ; String [ ] supportedMechanisms = SaslListMechsResponse . supportedMechs ( msg ) ; if ( supportedMechanisms . length == 0 ) { throw new AuthenticationException ( "Received empty SASL mechanisms list from server: " + remote ) ; } saslClient = Sasl . createSaslClient ( supportedMechanisms , null , "couchbase" , remote , null , this ) ; selectedMechanism = saslClient . getMechanismName ( ) ; byte [ ] bytePayload = saslClient . hasInitialResponse ( ) ? saslClient . evaluateChallenge ( new byte [ ] { } ) : null ; ByteBuf payload = bytePayload != null ? ctx . alloc ( ) . buffer ( ) . writeBytes ( bytePayload ) : Unpooled . EMPTY_BUFFER ; ByteBuf request = ctx . alloc ( ) . buffer ( ) ; SaslAuthRequest . init ( request ) ; SaslAuthRequest . mechanism ( selectedMechanism , request ) ; SaslAuthRequest . challengeResponse ( payload , request ) ; payload . release ( ) ; ChannelFuture future = ctx . writeAndFlush ( request ) ; future . addListener ( new GenericFutureListener < Future < Void > > ( ) { public void operationComplete ( Future < Void > future ) throws Exception { if ( ! future . isSuccess ( ) ) { LOGGER . warn ( "Error during SASL Auth negotiation phase." , future ) ; originalPromise ( ) . setFailure ( future . cause ( ) ) ; } } } ) ; }
|
Helper method to parse the list of supported SASL mechs and dispatch the initial auth request following .
|
40,746
|
public Single < ByteBuf > getSeqnos ( ) { return Single . create ( new Single . OnSubscribe < ByteBuf > ( ) { public void call ( final SingleSubscriber < ? super ByteBuf > subscriber ) { if ( state ( ) != LifecycleState . CONNECTED ) { subscriber . onError ( new NotConnectedException ( ) ) ; return ; } ByteBuf buffer = Unpooled . buffer ( ) ; DcpGetPartitionSeqnosRequest . init ( buffer ) ; DcpGetPartitionSeqnosRequest . vbucketState ( buffer , VbucketState . ACTIVE ) ; sendRequest ( buffer ) . addListener ( new DcpResponseListener ( ) { public void operationComplete ( Future < DcpResponse > future ) throws Exception { if ( future . isSuccess ( ) ) { ByteBuf buf = future . getNow ( ) . buffer ( ) ; try { subscriber . onSuccess ( MessageUtil . getContent ( buf ) . copy ( ) ) ; } finally { buf . release ( ) ; } } else { subscriber . onError ( future . cause ( ) ) ; } } } ) ; } } ) ; }
|
Returns all seqnos for all vbuckets on that channel .
|
40,747
|
public static RetryBuilder anyOf ( Class < ? extends Throwable > ... types ) { RetryBuilder retryBuilder = new RetryBuilder ( ) ; retryBuilder . maxAttempts = 1 ; retryBuilder . errorsStoppingRetry = Arrays . asList ( types ) ; retryBuilder . inverse = true ; return retryBuilder ; }
|
Only errors that are instanceOf the specified types will trigger a retry
|
40,748
|
public static RetryBuilder allBut ( Class < ? extends Throwable > ... types ) { RetryBuilder retryBuilder = new RetryBuilder ( ) ; retryBuilder . maxAttempts = 1 ; retryBuilder . errorsStoppingRetry = Arrays . asList ( types ) ; retryBuilder . inverse = false ; return retryBuilder ; }
|
Only errors that are NOT instanceOf the specified types will trigger a retry
|
40,749
|
public static RetryBuilder anyMatches ( Func1 < Throwable , Boolean > retryErrorPredicate ) { RetryBuilder retryBuilder = new RetryBuilder ( ) ; retryBuilder . maxAttempts = 1 ; retryBuilder . retryErrorPredicate = retryErrorPredicate ; return retryBuilder ; }
|
Any error that pass the predicate will trigger a retry
|
40,750
|
public Value get ( String name ) { if ( name . length ( ) > 1 ) { int dot ; if ( name . charAt ( 0 ) == LPAREN ) { int start = name . indexOf ( RPAREN ) ; dot = name . indexOf ( DOT , start ) ; } else { dot = name . indexOf ( DOT ) ; } if ( dot > 0 ) { String fieldName = name . substring ( 0 , dot ) ; String rest = name . substring ( dot + 1 ) ; Key key = createKey ( fieldName ) ; Value value = fields . get ( key ) ; if ( ! value . isMessageType ( ) ) { throw new ParserException ( "Invalid option name: %s" , name ) ; } DynamicMessage msg = value . getMessage ( ) ; return msg . get ( rest ) ; } else { Key key = createKey ( name ) ; return fields . get ( key ) ; } } else { Key key = Key . field ( name ) ; return fields . get ( key ) ; } }
|
Get option value by given option name .
|
40,751
|
public void set ( SourceCodeLocation sourceCodeLocation , String name , Value value ) { if ( name . length ( ) > 1 ) { int dot ; if ( name . charAt ( 0 ) == LPAREN ) { int start = name . indexOf ( RPAREN ) ; dot = name . indexOf ( DOT , start ) ; } else { dot = name . indexOf ( DOT ) ; } if ( dot > 0 ) { String fieldName = name . substring ( 0 , dot ) ; String rest = name . substring ( dot + 1 ) ; Key key = createKey ( fieldName ) ; DynamicMessage msg ; if ( fields . containsKey ( key ) ) { msg = getChildMessage ( value , key ) ; } else { msg = new DynamicMessage ( ) ; fields . put ( key , Value . createMessage ( sourceCodeLocation , msg ) ) ; } msg . set ( sourceCodeLocation , rest , value ) ; } else { Key key = createKey ( name ) ; set ( key , value ) ; } } else { Key key = Key . field ( name ) ; set ( key , value ) ; } }
|
Set field of an option to a given value .
|
40,752
|
public void normalizeName ( Key key , String fullyQualifiedName ) { Value value = fields . remove ( key ) ; if ( value == null ) { throw new IllegalStateException ( "Could not find option for key=" + key ) ; } Key newKey ; if ( fullyQualifiedName . startsWith ( "." ) ) { newKey = Key . extension ( fullyQualifiedName . substring ( 1 ) ) ; } else { newKey = Key . extension ( fullyQualifiedName ) ; } fields . put ( newKey , value ) ; }
|
Change option name to its fully qualified name .
|
40,753
|
public Map < String , Object > toMap ( ) { Map < String , Object > result = new HashMap < > ( ) ; for ( Entry < Key , Value > keyValueEntry : fields . entrySet ( ) ) { Key key = keyValueEntry . getKey ( ) ; Value value = keyValueEntry . getValue ( ) ; if ( ! key . isExtension ( ) ) { result . put ( key . getName ( ) , transformValueToObject ( value ) ) ; } else { result . put ( "(" + key . getName ( ) + ")" , transformValueToObject ( value ) ) ; } } return result ; }
|
Returns a map of option names as keys and option values as values ..
|
40,754
|
public void copyResource ( String name , String destinationFilename ) { ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( classLoader == null ) { String error = "Can not obtain classloader instance" ; throw new IllegalStateException ( error ) ; } try ( InputStream stream = classLoader . getResourceAsStream ( name ) ) { if ( stream == null ) { String error = "Could not copy file, source file not found: " + name ; throw new IllegalStateException ( error ) ; } Path path = Paths . get ( destinationFilename ) ; FileUtils . copyInputStreamToFile ( stream , path . toFile ( ) ) ; } catch ( IOException e ) { throw new GeneratorException ( "Could not copy %s" , e , name ) ; } }
|
Copy a classpath resource to the given location on a filesystem .
|
40,755
|
public final < T > void registerProperty ( Class < T > object , String property , Function < T , Object > function ) { PropertyProvider extender = extenderMap . computeIfAbsent ( object , aClass -> new PropertyProviderImpl ( ) ) ; extender . register ( property , function ) ; }
|
Register custom property for specified node type .
|
40,756
|
public static String getFieldType ( Field field ) { FieldType type = field . getType ( ) ; if ( type instanceof ScalarFieldType ) { ScalarFieldType scalarFieldType = ( ScalarFieldType ) type ; return ScalarFieldTypeUtil . getPrimitiveType ( scalarFieldType ) ; } if ( type instanceof UserType ) { UserType userType = ( UserType ) type ; return UserTypeUtil . getCanonicalName ( userType ) ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns a java field type for proto field .
|
40,757
|
public static String getFieldName ( Field field ) { String name = field . getName ( ) ; String formattedName = Formatter . toCamelCase ( name ) ; if ( isReservedKeyword ( formattedName ) ) { return formattedName + '_' ; } return formattedName ; }
|
Returns a java field name for proto field .
|
40,758
|
public static String getJsonFieldName ( Field field ) { String name = field . getName ( ) ; return Formatter . toCamelCase ( name ) ; }
|
Returns a json field name for proto field .
|
40,759
|
public static String getFieldGetterName ( Field field ) { String getterName = GETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) ; if ( "getClass" . equals ( getterName ) ) { return getterName + "_" ; } return getterName ; }
|
Returns a java field getter name for proto field .
|
40,760
|
public static String getEnumFieldValueGetterName ( Field field ) { return GETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) + VALUE ; }
|
Returns a java enum field value getter name for proto field .
|
40,761
|
public static String getEnumFieldValueSetterName ( Field field ) { return SETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) + VALUE ; }
|
Returns a java enum field value setter name for proto field .
|
40,762
|
public static String getDefaultValue ( Field field ) { FieldType type = field . getType ( ) ; if ( type instanceof ScalarFieldType ) { return ScalarFieldTypeUtil . getDefaultValue ( ( ScalarFieldType ) type ) ; } if ( type instanceof Message ) { Message m = ( Message ) type ; return UserTypeUtil . getCanonicalName ( m ) + ".getDefaultInstance()" ; } if ( type instanceof Enum ) { Enum anEnum = ( Enum ) type ; String defaultValue ; List < EnumConstant > constants = anEnum . getConstants ( ) ; if ( constants . isEmpty ( ) ) { defaultValue = "UNRECOGNIZED" ; } else { DynamicMessage options = field . getOptions ( ) ; defaultValue = options . containsKey ( DEFAULT ) ? options . get ( DEFAULT ) . getEnumName ( ) : constants . get ( 0 ) . getName ( ) ; } return UserTypeUtil . getCanonicalName ( anEnum ) + "." + defaultValue ; } throw new IllegalArgumentException ( String . valueOf ( type ) ) ; }
|
Returns a java field default value for proto field .
|
40,763
|
public static boolean isScalarNullableType ( Field field ) { FieldType type = field . getType ( ) ; return STRING . equals ( type ) || BYTES . equals ( type ) || type instanceof io . protostuff . compiler . model . Enum ; }
|
Check if field type used to store value in java is nullable type .
|
40,764
|
public static String getRepeatedFieldType ( Field field ) { FieldType type = field . getType ( ) ; if ( type instanceof ScalarFieldType ) { ScalarFieldType scalarFieldType = ( ScalarFieldType ) type ; return LIST + "<" + ScalarFieldTypeUtil . getWrapperType ( scalarFieldType ) + ">" ; } if ( type instanceof UserType ) { UserType userType = ( UserType ) type ; return LIST + "<" + UserTypeUtil . getCanonicalName ( userType ) + ">" ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns a java field type for proto repeated field .
|
40,765
|
public static String getRepeatedFieldGetterName ( Field field ) { if ( field . isRepeated ( ) ) { return GETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) + GETTER_REPEATED_SUFFIX ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns a java field getter name for proto repeated field .
|
40,766
|
public static String javaRepeatedEnumValueGetterByIndexName ( Field field ) { if ( field . isRepeated ( ) ) { return GETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) + VALUE ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns a field value getter by index name for proto repeated enum field .
|
40,767
|
public static String getRepeatedEnumConverterName ( Field field ) { if ( field . isRepeated ( ) ) { return "__" + Formatter . toCamelCase ( field . getName ( ) ) + "Converter" ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns a field converter class name for proto repeated enum field .
|
40,768
|
public static String getRepeatedFieldSetterName ( Field field ) { if ( field . isRepeated ( ) ) { return SETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns a field setter name for proto repeated field .
|
40,769
|
public static String getRepeatedEnumValueSetterName ( Field field ) { if ( field . isRepeated ( ) ) { return SETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) + VALUE ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns a field value setter name for proto repeated enum field .
|
40,770
|
public static String repeatedGetCountMethodName ( Field field ) { if ( field . isRepeated ( ) ) { return GETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) + "Count" ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns a element count getter name for proto repeated field .
|
40,771
|
public static String toStringPart ( Field field ) { String getterName ; if ( field . isMap ( ) ) { getterName = getMapGetterName ( field ) ; } else if ( field . isRepeated ( ) ) { getterName = getRepeatedFieldGetterName ( field ) ; } else { getterName = getFieldGetterName ( field ) ; } if ( field . getType ( ) . isEnum ( ) && ! field . isRepeated ( ) ) { return "\"" + getFieldName ( field ) + "=\" + " + getterName + "() + '(' + " + getEnumFieldValueGetterName ( field ) + "() + ')'" ; } return "\"" + getFieldName ( field ) + "=\" + " + getterName + "()" ; }
|
Generate part of toString method for a single field .
|
40,772
|
public static String getMapFieldType ( Field field ) { String k = getMapFieldKeyType ( field ) ; String v = getMapFieldValueType ( field ) ; return "java.util.Map<" + k + ", " + v + ">" ; }
|
Returns map field type name .
|
40,773
|
public static String getMapFieldKeyType ( Field field ) { FieldType type = field . getType ( ) ; if ( ! ( type instanceof Message ) ) { throw new IllegalArgumentException ( field . toString ( ) ) ; } Message entryType = ( Message ) type ; ScalarFieldType keyType = ( ScalarFieldType ) entryType . getField ( MAP_ENTRY_KEY ) . getType ( ) ; return ScalarFieldTypeUtil . getWrapperType ( keyType ) ; }
|
Returns map field key type name .
|
40,774
|
public static String getMapFieldValueType ( Field field ) { FieldType type = field . getType ( ) ; if ( ! ( type instanceof Message ) ) { throw new IllegalArgumentException ( field . toString ( ) ) ; } Message entryType = ( Message ) type ; Type valueType = entryType . getField ( MAP_ENTRY_VALUE ) . getType ( ) ; String v ; if ( valueType instanceof ScalarFieldType ) { ScalarFieldType scalarValueType = ( ScalarFieldType ) valueType ; v = ScalarFieldTypeUtil . getWrapperType ( scalarValueType ) ; } else { UserType userType = ( UserType ) valueType ; v = UserTypeUtil . getCanonicalName ( userType ) ; } return v ; }
|
Returns map field value type name .
|
40,775
|
public static String getMapGetterName ( Field field ) { if ( field . isMap ( ) ) { return GETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) + MAP_SUFFIX ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns map field getter name .
|
40,776
|
public static String getMapSetterName ( Field field ) { if ( field . isMap ( ) ) { return SETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) + MAP_SUFFIX ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns map field setter name .
|
40,777
|
public static String mapGetByKeyMethodName ( Field field ) { if ( field . isMap ( ) ) { return GETTER_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns map field getter for particular key method name .
|
40,778
|
public static String getMapFieldAdderName ( Field field ) { if ( field . isMap ( ) ) { return PUT_PREFIX + Formatter . toPascalCase ( field . getName ( ) ) ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns map field put method name .
|
40,779
|
public static String getMapFieldAddAllName ( Field field ) { if ( field . isMap ( ) ) { return "putAll" + Formatter . toPascalCase ( field . getName ( ) ) ; } throw new IllegalArgumentException ( field . toString ( ) ) ; }
|
Returns putAll method name for map field .
|
40,780
|
public static String javaOneofConstantName ( Field field ) { String name = field . getName ( ) ; String underscored = Formatter . toUnderscoreCase ( name ) ; return Formatter . toUpperCase ( underscored ) ; }
|
Returns an one - of enum constant name for oneof field .
|
40,781
|
public static boolean isNumericType ( Field field ) { FieldType type = field . getType ( ) ; boolean scalar = type instanceof ScalarFieldType ; return scalar && ! ( BOOL . equals ( type ) || STRING . equals ( type ) || BYTES . equals ( type ) ) ; }
|
Check if field type is numeric .
|
40,782
|
private Observable < PartitionAndSeqno > getSeqnos ( ) { return conductor . getSeqnos ( ) . flatMap ( new Func1 < ByteBuf , Observable < PartitionAndSeqno > > ( ) { public Observable < PartitionAndSeqno > call ( ByteBuf buf ) { int numPairs = buf . readableBytes ( ) / 10 ; List < PartitionAndSeqno > pairs = new ArrayList < > ( numPairs ) ; for ( int i = 0 ; i < numPairs ; i ++ ) { pairs . add ( new PartitionAndSeqno ( buf . getShort ( 10 * i ) , buf . getLong ( 10 * i + 2 ) ) ) ; } buf . release ( ) ; return Observable . from ( pairs ) ; } } ) ; }
|
Get the current sequence numbers from all partitions .
|
40,783
|
private void handleFailoverLogResponse ( final ByteBuf event ) { short partition = DcpFailoverLogResponse . vbucket ( event ) ; PartitionState ps = sessionState ( ) . get ( partition ) ; ps . setFailoverLog ( DcpFailoverLogResponse . entries ( event ) ) ; sessionState ( ) . set ( partition , ps ) ; }
|
Helper method to handle a failover log response .
|
40,784
|
private List < Short > selectInitializedPartitions ( int clusterPartitions , List < Short > partitions ) { List < Short > initializedPartitions = new ArrayList < > ( ) ; SessionState state = sessionState ( ) ; for ( short partition : partitions ) { PartitionState ps = state . get ( partition ) ; if ( ps != null ) { if ( MathUtils . lessThanUnsigned ( ps . getStartSeqno ( ) , ps . getEndSeqno ( ) ) ) { initializedPartitions . add ( partition ) ; } else { LOGGER . debug ( "Skipping partition {}, because startSeqno({}) >= endSeqno({})" , partition , ps . getStartSeqno ( ) , ps . getEndSeqno ( ) ) ; } } else { LOGGER . debug ( "Skipping partition {}, because its state is null" , partition ) ; } } if ( initializedPartitions . size ( ) > clusterPartitions ) { throw new IllegalStateException ( "Session State has " + initializedPartitions + " partitions while the cluster has " + clusterPartitions + "!" ) ; } return initializedPartitions ; }
|
Helper method to check on stream start that some kind of state is initialized to avoid a common error of starting without initializing .
|
40,785
|
private static List < Short > partitionsForVbids ( int numPartitions , Short ... vbids ) { if ( vbids . length > 0 ) { Arrays . sort ( vbids ) ; return Arrays . asList ( vbids ) ; } List < Short > partitions = new ArrayList < > ( vbids . length ) ; for ( short i = 0 ; i < numPartitions ; i ++ ) { partitions . add ( i ) ; } return partitions ; }
|
Helper method to turn the array of vbids into a list .
|
40,786
|
private Completable initFromBeginningToInfinity ( ) { return Completable . create ( new Completable . OnSubscribe ( ) { public void call ( CompletableSubscriber subscriber ) { LOGGER . info ( "Initializing state from beginning to no end." ) ; try { sessionState ( ) . setToBeginningWithNoEnd ( numPartitions ( ) ) ; subscriber . onCompleted ( ) ; } catch ( Exception ex ) { LOGGER . warn ( "Failed to initialize state from beginning to no end." , ex ) ; subscriber . onError ( ex ) ; } } } ) ; }
|
Initializes the session state from beginning to no end .
|
40,787
|
private Completable initFromNowToInfinity ( ) { return initWithCallback ( new Action1 < PartitionAndSeqno > ( ) { public void call ( PartitionAndSeqno partitionAndSeqno ) { short partition = partitionAndSeqno . partition ( ) ; long seqno = partitionAndSeqno . seqno ( ) ; PartitionState partitionState = sessionState ( ) . get ( partition ) ; partitionState . setStartSeqno ( seqno ) ; partitionState . setSnapshotStartSeqno ( seqno ) ; partitionState . setSnapshotEndSeqno ( seqno ) ; sessionState ( ) . set ( partition , partitionState ) ; } } ) ; }
|
Initializes the session state from now to no end .
|
40,788
|
private Completable initFromBeginningToNow ( ) { return initWithCallback ( new Action1 < PartitionAndSeqno > ( ) { public void call ( PartitionAndSeqno partitionAndSeqno ) { short partition = partitionAndSeqno . partition ( ) ; long seqno = partitionAndSeqno . seqno ( ) ; PartitionState partitionState = sessionState ( ) . get ( partition ) ; partitionState . setEndSeqno ( seqno ) ; sessionState ( ) . set ( partition , partitionState ) ; } } ) ; }
|
Initializes the session state from beginning to now .
|
40,789
|
public static InputStream readResource ( String name ) { String classpath = System . getProperty ( "java.class.path" ) ; LOGGER . trace ( "Reading {} from classpath={}" , name , classpath ) ; ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( classLoader == null ) { throw new IllegalStateException ( "Can not obtain classloader instance from current thread" ) ; } return classLoader . getResourceAsStream ( name ) ; }
|
Load resource from classpath .
|
40,790
|
public static DefaultConnectionNameGenerator forProduct ( String productName , String productVersion , String ... comments ) { return new DefaultConnectionNameGenerator ( new UserAgentBuilder ( ) . append ( productName , productVersion , comments ) ) ; }
|
Returns a new connection name generator that includes the given product information in the User Agent string .
|
40,791
|
public synchronized long update ( final PartitionInstance partitionInstance , final long vbuuid , final long seqno ) { return update ( partitionInstance . partition ( ) , partitionInstance . slot ( ) , vbuuid , seqno ) ; }
|
Updates the dataset with information about the given partition instance
|
40,792
|
public static < T extends ParseTreeListener > T create ( Class < T > type , T ... delegates ) { ImmutableList < T > listeners = ImmutableList . copyOf ( delegates ) ; return Reflection . newProxy ( type , new AbstractInvocationHandler ( ) { protected Object handleInvocation ( Object proxy , Method method , Object [ ] args ) throws Throwable { for ( T listener : listeners ) { method . invoke ( listener , args ) ; } return null ; } public String toString ( ) { return MoreObjects . toStringHelper ( "CompositeParseTreeListener" ) . add ( "listeners" , listeners ) . toString ( ) ; } } ) ; }
|
Create new composite listener for a collection of delegates .
|
40,793
|
public static String getPackage ( Proto proto ) { DynamicMessage . Value javaPackage = proto . getOptions ( ) . get ( OPTION_JAVA_PACKAGE ) ; if ( javaPackage != null ) { return javaPackage . getString ( ) ; } return proto . getPackage ( ) . getValue ( ) ; }
|
Returns java package name .
|
40,794
|
public static String getPackagePath ( Proto proto ) { String javaPackage = getPackage ( proto ) ; return javaPackage . replace ( '.' , '/' ) ; }
|
Returns a relative path where java class should be placed computed from java package .
|
40,795
|
public static String getName ( EnumConstant constant ) { String name = constant . getName ( ) ; String underscored = Formatter . toUnderscoreCase ( name ) ; return Formatter . toUpperCase ( underscored ) ; }
|
Returns constant name for java enum .
|
40,796
|
public static UsageIndex build ( Collection < Proto > protos ) { UsageIndex usageIndex = new UsageIndex ( ) ; for ( Proto proto : protos ) { ProtoWalker . newInstance ( proto . getContext ( ) ) . onMessage ( message -> { for ( Field field : message . getFields ( ) ) { usageIndex . register ( field . getType ( ) , message ) ; } } ) . onService ( service -> { for ( ServiceMethod serviceMethod : service . getMethods ( ) ) { usageIndex . register ( serviceMethod . getArgType ( ) , service ) ; usageIndex . register ( serviceMethod . getReturnType ( ) , service ) ; } } ) . walk ( ) ; } return usageIndex ; }
|
Build usage index for given collection of proto files .
|
40,797
|
public boolean disconnected ( ) { if ( ! configProvider . isState ( LifecycleState . DISCONNECTED ) ) { return false ; } for ( DcpChannel channel : channels ) { if ( ! channel . isState ( LifecycleState . DISCONNECTED ) ) { return false ; } } return true ; }
|
Returns true if all channels and the config provider are in a disconnected state .
|
40,798
|
@ SuppressWarnings ( "unchecked" ) public < T > T peek ( Class < T > declarationClass ) { Object declaration = declarationStack . peek ( ) ; if ( declaration == null ) { throw new IllegalStateException ( "Declaration stack is empty" ) ; } if ( declarationClass . isAssignableFrom ( declaration . getClass ( ) ) ) { return ( T ) declaration ; } return fail ( declaration , declarationClass ) ; }
|
Peek an element from a declaration stack . Used by parse listeners .
|
40,799
|
@ SuppressWarnings ( "unchecked" ) public < T > T pop ( Class < T > declarationClass ) { Object declaration = declarationStack . pop ( ) ; if ( declarationClass . isAssignableFrom ( declaration . getClass ( ) ) ) { return ( T ) declaration ; } return fail ( declaration , declarationClass ) ; }
|
Pop an element from from a declaration stack . Used by parse listeners .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.