idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
23,800
private static boolean functionsAreAllowed ( boolean isAddAllFunction , boolean isPutAllFunction , Class < ? > classD , Class < ? > classS ) { if ( isAddAllFunction ) return collectionIsAssignableFrom ( classD ) && collectionIsAssignableFrom ( classS ) ; if ( isPutAllFunction ) return mapIsAssignableFrom ( classD ) && mapIsAssignableFrom ( classS ) ; return isAssignableFrom ( classD , classS ) ; }
Returns true if the function to check is allowed .
23,801
public static String getGenericString ( Field field ) { String fieldDescription = field . toGenericString ( ) ; List < String > splitResult = new ArrayList < String > ( ) ; char [ ] charResult = fieldDescription . toCharArray ( ) ; boolean isFinished = false ; int separatorIndex = fieldDescription . indexOf ( " " ) ; int previousIndex = 0 ; while ( ! isFinished ) { int position = separatorIndex - 1 ; char specialChar = charResult [ position ] ; boolean isSpecialChar = true ; if ( specialChar != ',' && specialChar != '?' ) { if ( specialChar == 's' ) { String specialString = null ; try { specialString = fieldDescription . substring ( position - "extends" . length ( ) , position + 1 ) ; if ( isNull ( specialString ) || ! " extends" . equals ( specialString ) ) isSpecialChar = false ; } catch ( IndexOutOfBoundsException e ) { isSpecialChar = false ; } } else isSpecialChar = false ; } if ( ! isSpecialChar ) { splitResult . add ( fieldDescription . substring ( previousIndex , separatorIndex ) ) ; previousIndex = separatorIndex + 1 ; } separatorIndex = fieldDescription . indexOf ( " " , separatorIndex + 1 ) ; if ( separatorIndex == - 1 ) isFinished = true ; } for ( String description : splitResult ) if ( ! isAccessModifier ( description ) ) return description ; return null ; }
Splits the fieldDescription to obtain his class type generics inclusive .
23,802
public static boolean areEqual ( Field destination , Field source ) { return getGenericString ( destination ) . equals ( getGenericString ( source ) ) ; }
Returns true if destination and source have the same structure .
23,803
public static String mapperClassName ( Class < ? > destination , Class < ? > source , String resource ) { String className = destination . getName ( ) . replaceAll ( "\\." , "" ) + source . getName ( ) . replaceAll ( "\\." , "" ) ; if ( isEmpty ( resource ) ) return className ; if ( ! isPath ( resource ) ) return write ( className , String . valueOf ( resource . hashCode ( ) ) ) ; String [ ] dep = resource . split ( "\\\\" ) ; if ( dep . length <= 1 ) dep = resource . split ( "/" ) ; String xml = dep [ dep . length - 1 ] ; return write ( className , xml . replaceAll ( "\\." , "" ) . replaceAll ( " " , "" ) ) ; }
Returns the name of mapper that identifies the destination and source classes .
23,804
public static boolean areMappedObjects ( Class < ? > dClass , Class < ? > sClass , XML xml ) { return isMapped ( dClass , xml ) || isMapped ( sClass , xml ) ; }
returns true if almost one class is configured false otherwise .
23,805
private static boolean isMapped ( Class < ? > aClass , XML xml ) { return xml . isInheritedMapped ( aClass ) || Annotation . isInheritedMapped ( aClass ) ; }
Returns true if the class is configured in annotation or xml false otherwise .
23,806
public static List < Class < ? > > getAllsuperClasses ( Class < ? > aClass ) { List < Class < ? > > result = new ArrayList < Class < ? > > ( ) ; result . add ( aClass ) ; Class < ? > superclass = aClass . getSuperclass ( ) ; while ( ! isNull ( superclass ) && superclass != Object . class ) { result . add ( superclass ) ; superclass = superclass . getSuperclass ( ) ; } return result ; }
Returns a list with the class passed in input plus his superclasses .
23,807
public InfoOperation getInfoOperation ( final Field destination , final Field source ) { Class < ? > dClass = destination . getType ( ) ; Class < ? > sClass = source . getType ( ) ; Class < ? > dItem = null ; Class < ? > sItem = null ; InfoOperation operation = new InfoOperation ( ) . setConversionType ( UNDEFINED ) ; if ( dClass . isArray ( ) && collectionIsAssignableFrom ( sClass ) ) { dItem = dClass . getComponentType ( ) ; sItem = getCollectionItemClass ( source ) ; operation . setInstructionType ( ARRAY_LIST ) ; if ( areMappedObjects ( dItem , sItem , xml ) ) return operation . setInstructionType ( ARRAY_LIST_WITH_MAPPED_ITEMS ) . setConfigChosen ( configChosen ( dItem , sItem , xml ) ) ; } if ( collectionIsAssignableFrom ( dClass ) && sClass . isArray ( ) ) { dItem = getCollectionItemClass ( destination ) ; sItem = sClass . getComponentType ( ) ; operation . setInstructionType ( LIST_ARRAY ) ; if ( areMappedObjects ( dItem , sItem , xml ) ) return operation . setInstructionType ( LIST_ARRAY_WITH_MAPPED_ITEMS ) . setConfigChosen ( configChosen ( dItem , sItem , xml ) ) ; } if ( isAssignableFrom ( dItem , sItem ) ) return operation . setConversionType ( ABSENT ) ; if ( areBasic ( dItem , sItem ) ) return operation . setConversionType ( getConversionType ( dItem , sItem ) ) ; return operation ; }
This method calculates and returns information relating the operation to be performed .
23,808
private MapperConstructor getMapper ( String dName ) { return new MapperConstructor ( destinationType ( ) , sourceType ( ) , dName , dName , getSName ( ) , configChosen , xml , methodsToGenerate ) ; }
Returns a new instance of MapperConstructor
23,809
public Map < String , String > getMappings ( ) { HashMap < String , String > mappings = new HashMap < String , String > ( ) ; HashMap < String , Boolean > destInstance = new HashMap < String , Boolean > ( ) ; String s = "V" ; destInstance . put ( "null" , true ) ; destInstance . put ( "v" , false ) ; HashMap < String , NullPointerControl > nullPointer = new HashMap < String , NullPointerControl > ( ) ; nullPointer . put ( "Not" , NOT_ANY ) ; nullPointer . put ( "All" , ALL ) ; nullPointer . put ( "Des" , DESTINATION ) ; nullPointer . put ( "Sou" , SOURCE ) ; HashMap < String , MappingType > mapping = new HashMap < String , MappingType > ( ) ; mapping . put ( "All" , ALL_FIELDS ) ; mapping . put ( "Valued" , ONLY_VALUED_FIELDS ) ; mapping . put ( "Null" , ONLY_NULL_FIELDS ) ; java . lang . reflect . Method [ ] methods = IMapper . class . getDeclaredMethods ( ) ; for ( Entry < String , Boolean > d : destInstance . entrySet ( ) ) for ( Entry < String , NullPointerControl > npc : nullPointer . entrySet ( ) ) for ( Entry < String , MappingType > mtd : mapping . entrySet ( ) ) for ( Entry < String , MappingType > mts : mapping . entrySet ( ) ) { String methodName = d . getKey ( ) + s + npc . getKey ( ) + mtd . getKey ( ) + mts . getKey ( ) ; for ( java . lang . reflect . Method method : methods ) if ( method . getName ( ) . equals ( methodName ) ) mappings . put ( methodName , wrappedMapping ( d . getValue ( ) , npc . getValue ( ) , mtd . getValue ( ) , mts . getValue ( ) ) ) ; } mappings . put ( "get" , "return null;" + newLine ) ; return mappings ; }
Returns a Map where the keys are the mappings names and relative values are the mappings .
23,810
private String wrappedMapping ( boolean makeDest , NullPointerControl npc , MappingType mtd , MappingType mts ) { String sClass = source . getName ( ) ; String dClass = destination . getName ( ) ; String str = ( makeDest ? " " + sClass + " " + stringOfGetSource + " = (" + sClass + ") $1;" : " " + dClass + " " + stringOfGetDestination + " = (" + dClass + ") $1;" + newLine + " " + sClass + " " + stringOfGetSource + " = (" + sClass + ") $2;" ) + newLine ; switch ( npc ) { case SOURCE : str += "if(" + stringOfGetSource + "!=null){" + newLine ; break ; case DESTINATION : str += "if(" + stringOfGetDestination + "!=null){" + newLine ; break ; case ALL : str += "if(" + stringOfGetSource + "!=null && " + stringOfGetDestination + "!=null){" + newLine ; break ; default : break ; } str += mapping ( makeDest , mtd , mts ) + newLine + " return " + stringOfSetDestination + ";" + newLine ; return ( npc != NOT_ANY ) ? str += "}" + newLine + " return null;" + newLine : str ; }
This method adds the Null Pointer Control to mapping created by the mapping method . wrapMapping is used to wrap the mapping returned by mapping method .
23,811
public StringBuilder mapping ( boolean makeDest , MappingType mtd , MappingType mts ) { StringBuilder sb = new StringBuilder ( ) ; if ( isNullSetting ( makeDest , mtd , mts , sb ) ) return sb ; if ( makeDest ) sb . append ( newInstance ( destination , stringOfSetDestination ) ) ; for ( ASimpleOperation simpleOperation : simpleOperations ) sb . append ( setOperation ( simpleOperation , mtd , mts ) . write ( ) ) ; for ( AComplexOperation complexOperation : complexOperations ) sb . append ( setOperation ( complexOperation , mtd , mts ) . write ( makeDest ) ) ; return sb ; }
This method writes the mapping based on the value of the three MappingType taken in input .
23,812
private < T extends AGeneralOperation > T setOperation ( T operation , MappingType mtd , MappingType mts ) { operation . setMtd ( mtd ) . setMts ( mts ) . initialDSetPath ( stringOfSetDestination ) . initialDGetPath ( stringOfGetDestination ) . initialSGetPath ( stringOfGetSource ) ; return operation ; }
Setting common to all operations .
23,813
private boolean isNullSetting ( boolean makeDest , MappingType mtd , MappingType mts , StringBuilder result ) { if ( makeDest && ( mtd == ALL_FIELDS || mtd == ONLY_VALUED_FIELDS ) && mts == ONLY_NULL_FIELDS ) { result . append ( " " + stringOfSetDestination + "(null);" + newLine ) ; return true ; } return false ; }
if it is a null setting returns the null mapping
23,814
private final StringBuilder genericFlow ( boolean newInstance ) { if ( newInstance || getMtd ( ) == ONLY_NULL_FIELDS ) return sourceControl ( fieldToCreate ( ) ) ; if ( getMtd ( ) == ALL_FIELDS && ! destinationType ( ) . isPrimitive ( ) ) return write ( " if(" , getDestination ( ) , "!=null){" , newLine , sourceControl ( existingField ( ) ) , " }else{" , newLine , sourceControl ( fieldToCreate ( ) ) , " }" , newLine ) ; return sourceControl ( existingField ( ) ) ; }
This method specifies the general flow of the complex mapping .
23,815
private StringBuilder sourceControl ( StringBuilder mapping ) { if ( getMts ( ) == ALL_FIELDS && ! sourceType ( ) . isPrimitive ( ) ) { StringBuilder write = write ( " if(" , getSource ( ) , "!=null){" , newLine , sharedCode ( mapping ) , newLine , " }" ) ; if ( ! destinationType ( ) . isPrimitive ( ) && ! avoidSet ) write . append ( write ( "else{" , newLine , setDestination ( "null" ) , newLine , " }" , newLine ) ) ; else write . append ( newLine ) ; return write ; } else return write ( sharedCode ( mapping ) , newLine ) ; }
This method is used when the MappingType of Source is setting to ALL .
23,816
public static Redirect moved ( String url , Object ... args ) { touchPayload ( ) . message ( url , args ) ; return _INSTANCE ; }
This method is deprecated
23,817
public Binder < T > attribute ( String key , Object value ) { if ( null == value ) { attributes . remove ( value ) ; } else { attributes . put ( key , value ) ; } return this ; }
Set attribute of this binder .
23,818
public Binder < T > attributes ( Map < String , Object > attributes ) { this . attributes . putAll ( attributes ) ; return this ; }
Set attributes to this binder
23,819
static boolean isPortAvailable ( int port ) { ServerSocket ss = null ; try { ss = new ServerSocket ( port ) ; ss . setReuseAddress ( true ) ; return true ; } catch ( IOException ioe ) { return false ; } finally { closeQuietly ( ss ) ; } }
Find out if the provided port is available .
23,820
public RenderBinary name ( String attachmentName ) { this . name = attachmentName ; this . disposition = Disposition . of ( S . notBlank ( attachmentName ) ) ; return this ; }
Set the attachment name .
23,821
private static void addNonHeapMetrics ( Collection < Metric < ? > > result ) { MemoryUsage memoryUsage = ManagementFactory . getMemoryMXBean ( ) . getNonHeapMemoryUsage ( ) ; result . add ( newMemoryMetric ( "nonheap.committed" , memoryUsage . getCommitted ( ) ) ) ; result . add ( newMemoryMetric ( "nonheap.init" , memoryUsage . getInit ( ) ) ) ; result . add ( newMemoryMetric ( "nonheap.used" , memoryUsage . getUsed ( ) ) ) ; result . add ( newMemoryMetric ( "nonheap" , memoryUsage . getMax ( ) ) ) ; }
Add JVM non - heap metrics .
23,822
protected void addBasicMetrics ( Collection < Metric < ? > > result ) { Runtime runtime = Runtime . getRuntime ( ) ; result . add ( newMemoryMetric ( "mem" , runtime . totalMemory ( ) + getTotalNonHeapMemoryIfPossible ( ) ) ) ; result . add ( newMemoryMetric ( "mem.free" , runtime . freeMemory ( ) ) ) ; result . add ( new Metric < > ( "processors" , runtime . availableProcessors ( ) ) ) ; result . add ( new Metric < > ( "instance.uptime" , System . currentTimeMillis ( ) - this . timestamp ) ) ; }
Add basic system metrics .
23,823
protected void addClassLoadingMetrics ( Collection < Metric < ? > > result ) { ClassLoadingMXBean classLoadingMxBean = ManagementFactory . getClassLoadingMXBean ( ) ; result . add ( new Metric < > ( "classes" , ( long ) classLoadingMxBean . getLoadedClassCount ( ) ) ) ; result . add ( new Metric < > ( "classes.loaded" , classLoadingMxBean . getTotalLoadedClassCount ( ) ) ) ; result . add ( new Metric < > ( "classes.unloaded" , classLoadingMxBean . getUnloadedClassCount ( ) ) ) ; }
Add class loading metrics .
23,824
protected void addGarbageCollectionMetrics ( Collection < Metric < ? > > result ) { List < GarbageCollectorMXBean > garbageCollectorMxBeans = ManagementFactory . getGarbageCollectorMXBeans ( ) ; for ( GarbageCollectorMXBean garbageCollectorMXBean : garbageCollectorMxBeans ) { String name = beautifyGcName ( garbageCollectorMXBean . getName ( ) ) ; result . add ( new Metric < > ( "gc." + name + ".count" , garbageCollectorMXBean . getCollectionCount ( ) ) ) ; result . add ( new Metric < > ( "gc." + name + ".time" , garbageCollectorMXBean . getCollectionTime ( ) ) ) ; } }
Add garbage collection metrics .
23,825
protected void addHeapMetrics ( Collection < Metric < ? > > result ) { MemoryUsage memoryUsage = ManagementFactory . getMemoryMXBean ( ) . getHeapMemoryUsage ( ) ; result . add ( newMemoryMetric ( "heap.committed" , memoryUsage . getCommitted ( ) ) ) ; result . add ( newMemoryMetric ( "heap.init" , memoryUsage . getInit ( ) ) ) ; result . add ( newMemoryMetric ( "heap.used" , memoryUsage . getUsed ( ) ) ) ; result . add ( newMemoryMetric ( "heap" , memoryUsage . getMax ( ) ) ) ; }
Add JVM heap metrics .
23,826
protected void addThreadMetrics ( Collection < Metric < ? > > result ) { ThreadMXBean threadMxBean = ManagementFactory . getThreadMXBean ( ) ; result . add ( new Metric < > ( "threads.peak" , ( long ) threadMxBean . getPeakThreadCount ( ) ) ) ; result . add ( new Metric < > ( "threads.daemon" , ( long ) threadMxBean . getDaemonThreadCount ( ) ) ) ; result . add ( new Metric < > ( "threads.totalStarted" , threadMxBean . getTotalStartedThreadCount ( ) ) ) ; result . add ( new Metric < > ( "threads" , ( long ) threadMxBean . getThreadCount ( ) ) ) ; }
Add thread metrics .
23,827
private void addManagementMetrics ( Collection < Metric < ? > > result ) { try { result . add ( new Metric < > ( "uptime" , ManagementFactory . getRuntimeMXBean ( ) . getUptime ( ) ) ) ; result . add ( new Metric < > ( "systemload.average" , ManagementFactory . getOperatingSystemMXBean ( ) . getSystemLoadAverage ( ) ) ) ; this . addHeapMetrics ( result ) ; addNonHeapMetrics ( result ) ; this . addThreadMetrics ( result ) ; this . addClassLoadingMetrics ( result ) ; this . addGarbageCollectionMetrics ( result ) ; } catch ( NoClassDefFoundError ex ) { } }
Add metrics from ManagementFactory if possible . Note that ManagementFactory is not available on Google App Engine .
23,828
public void invoke ( StartupLifecycle lifecycle ) { this . initializeAsciiLogo ( ) ; this . printLogo ( ) ; lifecycle . willInitialize ( ) ; this . logInitializationStart ( ) ; lifecycle . willCreateSpringContext ( ) ; this . initializeApplicationContext ( ) ; lifecycle . didCreateSpringContext ( this . context ) ; this . initializeVersionProvider ( ) ; this . initializeSystemInfo ( ) ; this . initializeProfile ( ) ; this . initializeExternalProperties ( ) ; this . initializePropertyPlaceholderConfigurer ( ) ; this . initializeSpark ( ) ; lifecycle . willCreateDefaultSparkRoutes ( this . context ) ; this . initializeJsonTransformer ( ) ; this . initializeDefaultResources ( ) ; this . initializeActuators ( ) ; lifecycle . willScanForComponents ( this . context ) ; this . initializeSpringComponentScan ( ) ; lifecycle . willRefreshSpringContext ( this . context ) ; this . refreshApplicationContext ( ) ; this . completeSystemInfoInitialization ( ) ; lifecycle . didInitializeSpring ( this . context ) ; this . enableApplicationReloading ( ) ; Optional < CharSequence > statusMessages = lifecycle . didInitialize ( ) ; this . logInitializationFinished ( statusMessages ) ; }
Start the Indoqa - Boot application and hook into the startup lifecycle .
23,829
public static void save ( ) { H . Response resp = H . Response . current ( ) ; H . Session session = H . Session . current ( ) ; serialize ( session ) ; H . Flash flash = H . Flash . current ( ) ; serialize ( flash ) ; }
Persist session and flash to cookie write all cookies to http response
23,830
private Connection connect ( ) throws SQLException { if ( DefaultContentLoader . localDataSource == null ) { LOG . error ( "Data Source is null" ) ; return null ; } final Connection conn = DataSourceUtils . getConnection ( DefaultContentLoader . localDataSource ) ; if ( conn == null ) { LOG . error ( "Connection is null" ) ; } return conn ; }
Establish a connection to underlying db .
23,831
protected RequestData initializeRequestData ( final MessageContext messageContext ) { RequestData requestData = new RequestData ( ) ; requestData . setMsgContext ( messageContext ) ; String contextUsername = ( String ) messageContext . getProperty ( SECUREMENT_USER_PROPERTY_NAME ) ; if ( StringUtils . hasLength ( contextUsername ) ) { requestData . setUsername ( contextUsername ) ; } else { requestData . setUsername ( securementUsername ) ; } requestData . setAppendSignatureAfterTimestamp ( true ) ; requestData . setTimeStampTTL ( securementTimeToLive ) ; requestData . setWssConfig ( wssConfig ) ; return requestData ; }
Creates and initializes a request data for the given message context .
23,832
protected void checkResults ( final List < WSSecurityEngineResult > results , final List < Integer > validationActions ) throws Wss4jSecurityValidationException { if ( ! handler . checkReceiverResultsAnyOrder ( results , validationActions ) ) { throw new Wss4jSecurityValidationException ( "Security processing failed (actions mismatch)" ) ; } }
Checks whether the received headers match the configured validation actions . Subclasses could override this method for custom verification behavior .
23,833
@ SuppressWarnings ( "unchecked" ) private void updateContextWithResults ( final MessageContext messageContext , final WSHandlerResult result ) { List < WSHandlerResult > handlerResults ; if ( ( handlerResults = ( List < WSHandlerResult > ) messageContext . getProperty ( WSHandlerConstants . RECV_RESULTS ) ) == null ) { handlerResults = new ArrayList < WSHandlerResult > ( ) ; messageContext . setProperty ( WSHandlerConstants . RECV_RESULTS , handlerResults ) ; } handlerResults . add ( 0 , result ) ; messageContext . setProperty ( WSHandlerConstants . RECV_RESULTS , handlerResults ) ; }
Puts the results of WS - Security headers processing in the message context . Some actions like Signature Confirmation require this .
23,834
protected void verifyCertificateTrust ( WSHandlerResult result ) throws WSSecurityException { List < WSSecurityEngineResult > signResults = result . getActionResults ( ) . getOrDefault ( WSConstants . SIGN , emptyList ( ) ) ; if ( signResults . isEmpty ( ) ) { throw new Wss4jSecurityValidationException ( "No action results for 'Perform Signature' found" ) ; } else if ( signResults . size ( ) > 1 ) { throw new Wss4jSecurityValidationException ( "Multiple action results for 'Perform Signature' found. Expected only 1." ) ; } WSSecurityEngineResult signResult = signResults . get ( 0 ) ; if ( signResult != null ) { X509Certificate returnCert = ( X509Certificate ) signResult . get ( WSSecurityEngineResult . TAG_X509_CERTIFICATE ) ; Credential credential = new Credential ( ) ; credential . setCertificates ( new X509Certificate [ ] { returnCert } ) ; RequestData requestData = new RequestData ( ) ; requestData . setSigVerCrypto ( validationSignatureCrypto ) ; requestData . setEnableRevocation ( enableRevocation ) ; requestData . setSubjectCertConstraints ( OrgnummerExtractor . PATTERNS ) ; SignatureTrustValidator validator = new SignatureTrustValidator ( ) ; validator . validate ( credential , requestData ) ; } }
Verifies the trust of a certificate .
23,835
protected void verifyTimestamp ( WSHandlerResult result ) throws WSSecurityException { List < WSSecurityEngineResult > insertTimestampResults = result . getActionResults ( ) . getOrDefault ( WSConstants . TS , emptyList ( ) ) ; if ( insertTimestampResults . isEmpty ( ) ) { throw new Wss4jSecurityValidationException ( "No action results for 'Insert timestamp' found" ) ; } else if ( insertTimestampResults . size ( ) > 1 ) { throw new Wss4jSecurityValidationException ( "Multiple action results for 'Insert timestamp' found. Expected only 1." ) ; } WSSecurityEngineResult actionResult = insertTimestampResults . get ( 0 ) ; if ( actionResult != null ) { Timestamp timestamp = ( Timestamp ) actionResult . get ( WSSecurityEngineResult . TAG_TIMESTAMP ) ; if ( timestamp != null && timestampStrict ) { Credential credential = new Credential ( ) ; credential . setTimestamp ( timestamp ) ; RequestData requestData = new RequestData ( ) ; requestData . setWssConfig ( WSSConfig . getNewInstance ( ) ) ; requestData . setTimeStampTTL ( validationTimeToLive ) ; requestData . setTimeStampStrict ( timestampStrict ) ; TimestampValidator validator = new TimestampValidator ( ) ; validator . validate ( credential , requestData ) ; } } }
Verifies the timestamp .
23,836
public static void addMissingColumns ( SQLiteDatabase database , Class contractClass ) { Contract contract = new Contract ( contractClass ) ; Cursor cursor = database . rawQuery ( "PRAGMA table_info(" + contract . getTable ( ) + ")" , null ) ; for ( ContractField field : contract . getFields ( ) ) { if ( ! fieldExistAsColumn ( field . name , cursor ) ) { database . execSQL ( "ALTER TABLE " + contract . getTable ( ) + " ADD COLUMN " + field . name + " " + field . type + ";" ) ; } } }
Adds missing table columns for the given contract class .
23,837
public TableBuilder addConstraint ( String columnName , String constraintType , String constraintConflictClause ) { constraints . add ( new Constraint ( columnName , constraintType , constraintConflictClause ) ) ; return this ; }
Adds the specified constraint to the created table .
23,838
public static Predicate < ColumnModel > allOf ( final Predicate < ColumnModel > ... conditions ) { return ( cM ) -> Arrays . stream ( conditions ) . allMatch ( c -> c . test ( cM ) ) ; }
A condition that returns true if all of the provided conditions return true . Equivalent to logical AND operator .
23,839
public static Predicate < ColumnModel > anyOf ( final Predicate < ColumnModel > ... conditions ) { return ( cM ) -> Arrays . stream ( conditions ) . anyMatch ( c -> c . test ( cM ) ) ; }
A condition that returns true if any of the provided conditions return true . Equivalent to logical OR operator .
23,840
public static Predicate < ColumnModel > oneOf ( final Predicate < ColumnModel > ... conditions ) { return ( cM ) -> Arrays . stream ( conditions ) . map ( c -> c . test ( cM ) ) . filter ( b -> b ) . count ( ) == 1 ; }
A condition that returns true if exactly one of the provided conditions return true . Equivalent to logical XOR operator .
23,841
public < T extends RedGEntity > T getDummy ( final AbstractRedG redG , final Class < T > dummyClass ) { if ( this . dummyCache . containsKey ( dummyClass ) ) { return dummyClass . cast ( this . dummyCache . get ( dummyClass ) ) ; } final T obj = createNewDummy ( redG , dummyClass ) ; this . dummyCache . put ( dummyClass , obj ) ; return obj ; }
Returns a dummy entity for the requested type . All this method guarantees is that the returned entity is a valid entity with all non null foreign key relations filled in it does not guarantee useful or even semantically correct data . The dummy objects get taken either from the list of objects to insert from the redG object or are created on the fly . The results are cached and the same entity will be returned for consecutive calls for an entity of the same type .
23,842
private boolean hasTemplate ( String href ) { if ( href == null ) { return false ; } return URI_TEMPLATE_PATTERN . matcher ( href ) . find ( ) ; }
Determine whether the argument href contains at least one URI template as defined in RFC 6570 .
23,843
private static void processJoinTables ( final List < TableModel > result , final Map < String , Map < Table , List < String > > > joinTableMetadata ) { joinTableMetadata . entrySet ( ) . forEach ( entry -> { LOG . debug ( "Processing join tables for {}. Found {} join tables to process" , entry . getKey ( ) , entry . getValue ( ) . size ( ) ) ; final TableModel model = getModelBySQLName ( result , entry . getKey ( ) ) ; if ( model == null ) { LOG . error ( "Could not find table {} in the already generated models! This should not happen!" , entry . getKey ( ) ) ; throw new NullPointerException ( "Table model not found" ) ; } entry . getValue ( ) . entrySet ( ) . forEach ( tableListEntry -> { LOG . debug ( "Processing join table {}" , tableListEntry . getKey ( ) . getFullName ( ) ) ; final TableModel joinTable = getModelBySQLName ( result , tableListEntry . getKey ( ) . getFullName ( ) ) ; if ( joinTable == null ) { LOG . error ( "Could not find join table {} in the already generated models! This should not happen!" , entry . getKey ( ) ) ; throw new NullPointerException ( "Table model not found" ) ; } JoinTableSimplifierModel jtsModel = new JoinTableSimplifierModel ( ) ; jtsModel . setName ( joinTable . getName ( ) ) ; for ( ForeignKeyModel fKModel : joinTable . getForeignKeys ( ) ) { if ( fKModel . getJavaTypeName ( ) . equals ( model . getClassName ( ) ) ) { jtsModel . getConstructorParams ( ) . add ( "this" ) ; } else { jtsModel . getConstructorParams ( ) . add ( fKModel . getName ( ) ) ; jtsModel . getMethodParams ( ) . put ( fKModel . getJavaTypeName ( ) , fKModel . getName ( ) ) ; } } model . getJoinTableSimplifierData ( ) . put ( joinTable . getClassName ( ) , jtsModel ) ; } ) ; } ) ; }
Processes the information about the join tables that were collected during table model extraction .
23,844
private static Map < String , Map < Table , List < String > > > mergeJoinTableMetadata ( Map < String , Map < Table , List < String > > > data , Map < String , Map < Table , List < String > > > extension ) { for ( String key : extension . keySet ( ) ) { Map < Table , List < String > > dataForTable = data . get ( key ) ; if ( dataForTable == null ) { data . put ( key , extension . get ( key ) ) ; continue ; } for ( Table t : extension . get ( key ) . keySet ( ) ) { dataForTable . put ( t , extension . get ( key ) . get ( t ) ) ; } data . put ( key , dataForTable ) ; } return data ; }
Performs a deep - merge on the two provided maps integrating everything from the second map into the first and returning the first map .
23,845
private String validatePath ( String path , int line ) throws ParseException { if ( ! path . startsWith ( "/" ) ) { throw new ParseException ( "Path must start with '/'" , line ) ; } boolean openedKey = false ; for ( int i = 0 ; i < path . length ( ) ; i ++ ) { boolean validChar = isValidCharForPath ( path . charAt ( i ) , openedKey ) ; if ( ! validChar ) { throw new ParseException ( path , i ) ; } if ( path . charAt ( i ) == '{' ) { openedKey = true ; } if ( path . charAt ( i ) == '}' ) { openedKey = false ; } } return path ; }
Helper method . It validates if the path is valid .
23,846
private boolean isValidCharForPath ( char c , boolean openedKey ) { char [ ] invalidChars = { '?' , '#' , ' ' } ; for ( char invalidChar : invalidChars ) { if ( c == invalidChar ) { return false ; } } if ( openedKey ) { char [ ] moreInvalidChars = { '/' , '{' } ; for ( char invalidChar : moreInvalidChars ) { if ( c == invalidChar ) { return false ; } } } return true ; }
Helper method . Tells if a char is valid in a the path of a route line .
23,847
public static void notEmpty ( String value , String message ) throws IllegalArgumentException { if ( value == null || "" . equals ( value . trim ( ) ) ) { throw new IllegalArgumentException ( "A precondition failed: " + message ) ; } }
Checks that a string is not null or empty .
23,848
protected void initPathVariables ( String routePath ) { pathVariables . clear ( ) ; List < String > variables = getVariables ( routePath ) ; String regexPath = routePath . replaceAll ( Path . VAR_REGEXP , Path . VAR_REPLACE ) ; Matcher matcher = Pattern . compile ( "(?i)" + regexPath ) . matcher ( getPath ( ) ) ; matcher . matches ( ) ; for ( int i = 1 ; i <= variables . size ( ) ; i ++ ) { String value = matcher . group ( i ) ; pathVariables . put ( variables . get ( i - 1 ) , value ) ; } }
Helper method . Initializes the pathVariables property of this class .
23,849
private List < String > getVariables ( String routePath ) { List < String > variables = new ArrayList < String > ( ) ; Matcher matcher = Pattern . compile ( Path . VAR_REGEXP ) . matcher ( routePath ) ; while ( matcher . find ( ) ) { variables . add ( matcher . group ( 1 ) ) ; } return variables ; }
Helper method . Retrieves all the variables defined in the path .
23,850
public ConfigurationBuilder withRemoteSocket ( String host , int port ) { configuration . connector = new NioSocketConnector ( ) ; configuration . address = new InetSocketAddress ( host , port ) ; return this ; }
Use a TCP connection for remotely connecting to the IT - 100 .
23,851
public ConfigurationBuilder withSerialPort ( String serialPort , int baudRate ) { configuration . connector = new SerialConnector ( ) ; configuration . address = new SerialAddress ( serialPort , baudRate , DataBits . DATABITS_8 , StopBits . BITS_1 , Parity . NONE , FlowControl . NONE ) ; return this ; }
Use a local serial port for communicating with the IT - 100 .
23,852
public Configuration build ( ) { if ( configuration . connector == null || configuration . address == null ) { throw new IllegalArgumentException ( "You must call either withRemoteSocket or withSerialPort." ) ; } return configuration ; }
Create an immutable Configuration instance .
23,853
public static Catalog crawlDatabase ( final Connection connection , final InclusionRule schemaRule , final InclusionRule tableRule ) throws SchemaCrawlerException { final SchemaCrawlerOptions options = SchemaCrawlerOptionsBuilder . builder ( ) . withSchemaInfoLevel ( SchemaInfoLevelBuilder . standard ( ) . setRetrieveIndexes ( false ) ) . routineTypes ( Arrays . asList ( RoutineType . procedure , RoutineType . unknown ) ) . includeSchemas ( schemaRule == null ? new IncludeAll ( ) : schemaRule ) . includeTables ( tableRule == null ? new IncludeAll ( ) : tableRule ) . toOptions ( ) ; try { return SchemaCrawlerUtility . getCatalog ( connection , options ) ; } catch ( SchemaCrawlerException e ) { LOG . error ( "Schema crawling failed with exception" , e ) ; throw e ; } }
Starts the schema crawler and lets it crawl the given JDBC connection .
23,854
public String generateMainClass ( final Collection < TableModel > tables , final boolean enableVisualizationSupport ) { Objects . requireNonNull ( tables ) ; final String targetPackage = ( ( TableModel ) tables . toArray ( ) [ 0 ] ) . getPackageName ( ) ; final ST template = this . stGroup . getInstanceOf ( "mainClass" ) ; LOG . debug ( "Filling main class template containing helpers for {} classes..." , tables . size ( ) ) ; template . add ( "package" , targetPackage ) ; template . add ( "prefix" , "" ) ; template . add ( "enableVisualizationSupport" , enableVisualizationSupport ) ; LOG . debug ( "Package is {} | Prefix is {}" , targetPackage , "" ) ; template . add ( "tables" , tables ) ; return template . render ( ) ; }
Generates the main class used for creating the extractor objects and later generating the insert statements . For each passed table a appropriate creation method will be generated that will return the new object and internally add it to the list of objects that will be used to generate the insert strings
23,855
public RedGBuilder < T > withDefaultValueStrategy ( final DefaultValueStrategy strategy ) { if ( instance == null ) { throw new IllegalStateException ( "Using the builder after build() was called is not allowed!" ) ; } instance . setDefaultValueStrategy ( strategy ) ; return this ; }
Sets the default value strategy
23,856
public RedGBuilder < T > withPreparedStatementParameterSetter ( final PreparedStatementParameterSetter setter ) { if ( instance == null ) { throw new IllegalStateException ( "Using the builder after build() was called is not allowed!" ) ; } instance . setPreparedStatementParameterSetter ( setter ) ; return this ; }
Sets the PreparedStatement parameter setter
23,857
public RedGBuilder < T > withSqlValuesFormatter ( final SQLValuesFormatter formatter ) { if ( instance == null ) { throw new IllegalStateException ( "Using the builder after build() was called is not allowed!" ) ; } instance . setSqlValuesFormatter ( formatter ) ; return this ; }
Sets the SQL values formatter
23,858
public RedGBuilder < T > withDummyFactory ( final DummyFactory dummyFactory ) { if ( instance == null ) { throw new IllegalStateException ( "Using the builder after build() was called is not allowed!" ) ; } instance . setDummyFactory ( dummyFactory ) ; return this ; }
Sets the dummy factory
23,859
private boolean isOneOf ( char ch , final char [ ] charray ) { boolean result = false ; for ( int i = 0 ; i < charray . length ; i ++ ) { if ( ch == charray [ i ] ) { result = true ; break ; } } return result ; }
Tests if the given character is present in the array of characters .
23,860
public static String get ( ) { String env = System . getProperty ( "JOGGER_ENV" ) ; if ( env == null ) { env = System . getenv ( "JOGGER_ENV" ) ; } if ( env == null ) { return "dev" ; } return env ; }
Retrieves the environment in which Jogger is working .
23,861
public List < String > generateSQLStatements ( ) { return getEntitiesSortedForInsert ( ) . stream ( ) . map ( RedGEntity :: getSQLString ) . collect ( Collectors . toList ( ) ) ; }
Returns a list of insert statements one for each added entity in the respective order they were added .
23,862
public String getMethodNameForReference ( final ForeignKey foreignKey ) { final Column c = foreignKey . getColumnReferences ( ) . get ( 0 ) . getForeignKeyColumn ( ) ; if ( foreignKey . getColumnReferences ( ) . size ( ) == 1 ) { return getMethodNameForColumn ( c ) + getClassNameForTable ( c . getReferencedColumn ( ) . getParent ( ) ) ; } final StringBuilder nameBuilder = new StringBuilder ( ) ; final List < String > words = new ArrayList < > ( Arrays . asList ( foreignKey . getName ( ) . toLowerCase ( ) . replaceAll ( "(^[0-9]+|[^a-z0-9_-])" , "" ) . split ( "_" ) ) ) ; words . removeAll ( Arrays . asList ( "fk" , "" , null ) ) ; final List < String > tableWords = new ArrayList < > ( Arrays . asList ( c . getParent ( ) . getName ( ) . toLowerCase ( ) . replaceAll ( "(^[0-9]+|[^a-z0-9_-])" , "" ) . split ( "_" ) ) ) ; words . removeAll ( tableWords ) ; nameBuilder . append ( words . get ( 0 ) ) ; for ( int i = 1 ; i < words . size ( ) ; i ++ ) { String word = words . get ( i ) ; nameBuilder . append ( word . substring ( 0 , 1 ) . toUpperCase ( ) ) ; nameBuilder . append ( word . substring ( 1 ) ) ; } return nameBuilder . toString ( ) ; }
Generates an appropriate method name for a foreign key
23,863
public void handle ( Request request , Response response ) throws Exception { if ( Environment . isDevelopment ( ) ) { this . middlewares = this . middlewareFactory . create ( ) ; } try { handle ( request , response , new ArrayList < Middleware > ( Arrays . asList ( middlewares ) ) ) ; } catch ( Exception e ) { if ( exceptionHandler != null ) { exceptionHandler . handle ( e , request , response ) ; } else { throw e ; } } }
Handles an HTTP request by delgating the call to the middlewares .
23,864
private synchronized void performReliableSubscription ( ) { if ( subscriberTimer == null ) { LOGGER . info ( "Initializing reliable subscriber" ) ; subscriberTimer = createTimerInternal ( ) ; ExponentialBackOff backOff = new ExponentialBackOff . Builder ( ) . setMaxElapsedTimeMillis ( Integer . MAX_VALUE ) . setMaxIntervalMillis ( MAX_BACKOFF_MS ) . setMultiplier ( MULTIPLIER ) . setRandomizationFactor ( 0.5 ) . setInitialIntervalMillis ( SEED_BACKOFF_MS ) . build ( ) ; subscriberTimer . schedule ( new SubscriberTask ( backOff ) , SEED_BACKOFF_MS , TimeUnit . MILLISECONDS ) ; } }
Task that performs Subscription .
23,865
protected Mesos startInternal ( ) { String version = System . getenv ( "MESOS_API_VERSION" ) ; if ( version == null ) { version = "V0" ; } LOGGER . info ( "Using Mesos API version: {}" , version ) ; if ( version . equals ( "V0" ) ) { if ( credential == null ) { return new V0Mesos ( this , frameworkInfo , master ) ; } else { return new V0Mesos ( this , frameworkInfo , master , credential ) ; } } else if ( version . equals ( "V1" ) ) { if ( credential == null ) { return new V1Mesos ( this , master ) ; } else { return new V1Mesos ( this , master , credential ) ; } } else { throw new IllegalArgumentException ( "Unsupported API version: " + version ) ; } }
Broken out into a separate function to allow testing with custom Mesos implementations .
23,866
public TableModel extractTableModel ( final Table table ) { Objects . requireNonNull ( table ) ; final TableModel model = new TableModel ( ) ; model . setClassName ( this . classPrefix + this . nameProvider . getClassNameForTable ( table ) ) ; model . setName ( this . nameProvider . getClassNameForTable ( table ) ) ; model . setSqlFullName ( table . getFullName ( ) ) ; model . setSqlName ( table . getName ( ) ) ; model . setPackageName ( this . targetPackage ) ; model . setColumns ( table . getColumns ( ) . stream ( ) . map ( this . columnExtractor :: extractColumnModel ) . collect ( Collectors . toList ( ) ) ) ; Set < Set < String > > seenForeignKeyColumnNameTuples = new HashSet < > ( ) ; model . setForeignKeys ( table . getImportedForeignKeys ( ) . stream ( ) . filter ( foreignKeyColumnReferences -> { Set < String > foreignKeyColumnNames = foreignKeyColumnReferences . getColumnReferences ( ) . stream ( ) . map ( foreignKeyColumnReference -> foreignKeyColumnReference . getForeignKeyColumn ( ) . getFullName ( ) ) . collect ( Collectors . toSet ( ) ) ; return seenForeignKeyColumnNameTuples . add ( foreignKeyColumnNames ) ; } ) . map ( this . foreignKeyExtractor :: extractForeignKeyModel ) . collect ( Collectors . toList ( ) ) ) ; Set < Set < String > > seenForeignKeyColumnNameTuples2 = new HashSet < > ( ) ; model . setIncomingForeignKeys ( table . getExportedForeignKeys ( ) . stream ( ) . filter ( foreignKeyColumnReferences -> { Set < String > foreignKeyColumnNames = foreignKeyColumnReferences . getColumnReferences ( ) . stream ( ) . map ( foreignKeyColumnReference -> foreignKeyColumnReference . getForeignKeyColumn ( ) . getFullName ( ) ) . collect ( Collectors . toSet ( ) ) ; return seenForeignKeyColumnNameTuples2 . add ( foreignKeyColumnNames ) ; } ) . map ( this . foreignKeyExtractor :: extractIncomingForeignKeyModel ) . collect ( Collectors . toList ( ) ) ) ; model . setHasColumnsAndForeignKeys ( ! model . getNonForeignKeyColumns ( ) . isEmpty ( ) && ! model . getForeignKeys ( ) . isEmpty ( ) ) ; return model ; }
Extracts the table model from a single table . Every table this table references via foreign keys must be fully loaded otherwise an exception will be thrown .
23,867
private ServletRequest init ( ) throws MultipartException , IOException { if ( Multipart . isMultipartContent ( request ) ) { Multipart multipart = new Multipart ( ) ; multipart . parse ( request , new PartHandler ( ) { public void handleFormItem ( String name , String value ) { multipartParams . put ( name , value ) ; } public void handleFileItem ( String name , FileItem fileItem ) { files . add ( fileItem ) ; } } ) ; } return this ; }
Initializes the path variables and the multipart content .
23,868
private String fixRequestPath ( String path ) { return path . endsWith ( "/" ) ? path . substring ( 0 , path . length ( ) - 1 ) : path ; }
Helper method . The request path shouldn t have a trailing slash .
23,869
private List < Interceptor > getInterceptors ( String path ) { List < Interceptor > ret = new ArrayList < Interceptor > ( ) ; for ( InterceptorEntry entry : getInterceptors ( ) ) { if ( matches ( path , entry . getPaths ( ) ) ) { ret . add ( entry . getInterceptor ( ) ) ; } } return ret ; }
Returns a list of interceptors that match a path
23,870
private boolean matchesPath ( String routePath , String pathToMatch ) { routePath = routePath . replaceAll ( Path . VAR_REGEXP , Path . VAR_REPLACE ) ; return pathToMatch . matches ( "(?i)" + routePath ) ; }
Helper method . Tells if the the HTTP path matches the route path .
23,871
public static boolean isMultipartContent ( HttpServletRequest request ) { if ( ! "post" . equals ( request . getMethod ( ) . toLowerCase ( ) ) ) { return false ; } String contentType = request . getContentType ( ) ; if ( contentType == null ) { return false ; } if ( contentType . toLowerCase ( ) . startsWith ( MULTIPART ) ) { return true ; } return false ; }
Tells if a request is multipart or not .
23,872
protected Map < String , String > getHeadersMap ( String headerPart ) { final int len = headerPart . length ( ) ; final Map < String , String > headers = new HashMap < String , String > ( ) ; int start = 0 ; for ( ; ; ) { int end = parseEndOfLine ( headerPart , start ) ; if ( start == end ) { break ; } String header = headerPart . substring ( start , end ) ; start = end + 2 ; while ( start < len ) { int nonWs = start ; while ( nonWs < len ) { char c = headerPart . charAt ( nonWs ) ; if ( c != ' ' && c != '\t' ) { break ; } ++ nonWs ; } if ( nonWs == start ) { break ; } end = parseEndOfLine ( headerPart , nonWs ) ; header += " " + headerPart . substring ( nonWs , end ) ; start = end + 2 ; } final int colonOffset = header . indexOf ( ':' ) ; if ( colonOffset == - 1 ) { continue ; } String headerName = header . substring ( 0 , colonOffset ) . trim ( ) ; String headerValue = header . substring ( header . indexOf ( ':' ) + 1 ) . trim ( ) ; if ( headers . containsKey ( headerName ) ) { headers . put ( headerName , headers . get ( headerName ) + "," + headerValue ) ; } else { headers . put ( headerName , headerValue ) ; } } return headers ; }
Retreives a map with the headers of a part .
23,873
private String getFieldName ( String contentDisposition ) { String fieldName = null ; if ( contentDisposition != null && contentDisposition . toLowerCase ( ) . startsWith ( FORM_DATA ) ) { ParameterParser parser = new ParameterParser ( ) ; parser . setLowerCaseNames ( true ) ; Map < String , String > params = parser . parse ( contentDisposition , ';' ) ; fieldName = ( String ) params . get ( "name" ) ; if ( fieldName != null ) { fieldName = fieldName . trim ( ) ; } } return fieldName ; }
Retrieves the name of the field from the Content - Disposition header of the part .
23,874
protected byte [ ] getBoundary ( String contentType ) { ParameterParser parser = new ParameterParser ( ) ; parser . setLowerCaseNames ( true ) ; Map < String , String > params = parser . parse ( contentType , new char [ ] { ';' , ',' } ) ; String boundaryStr = ( String ) params . get ( "boundary" ) ; if ( boundaryStr == null ) { return null ; } byte [ ] boundary ; try { boundary = boundaryStr . getBytes ( "ISO-8859-1" ) ; } catch ( UnsupportedEncodingException e ) { boundary = boundaryStr . getBytes ( ) ; } return boundary ; }
Retrieves the boundary that is used to separate the request parts from the Content - Type header .
23,875
private String getFileName ( String contentDisposition ) { String fileName = null ; if ( contentDisposition != null ) { String cdl = contentDisposition . toLowerCase ( ) ; if ( cdl . startsWith ( FORM_DATA ) || cdl . startsWith ( ATTACHMENT ) ) { ParameterParser parser = new ParameterParser ( ) ; parser . setLowerCaseNames ( true ) ; Map < String , String > params = parser . parse ( contentDisposition , ';' ) ; if ( params . containsKey ( "filename" ) ) { fileName = ( String ) params . get ( "filename" ) ; if ( fileName != null ) { fileName = fileName . trim ( ) ; } else { fileName = "" ; } } } } return fileName ; }
Retrieves the file name of a file from the filename attribute of the Content - Disposition header of the part .
23,876
public void connect ( ) throws Exception { final IT100CodecFactory it100CodecFactory = new IT100CodecFactory ( ) ; final ProtocolCodecFilter protocolCodecFilter = new ProtocolCodecFilter ( it100CodecFactory ) ; final CommandLogFilter loggingFilter = new CommandLogFilter ( LOGGER , Level . DEBUG ) ; final PollKeepAliveFilter pollKeepAliveFilter = new PollKeepAliveFilter ( KeepAliveRequestTimeoutHandler . EXCEPTION ) ; connector = configuration . getConnector ( ) ; connector . setConnectTimeoutMillis ( configuration . getConnectTimeout ( ) ) ; connector . getSessionConfig ( ) . setUseReadOperation ( true ) ; connector . getFilterChain ( ) . addLast ( "codec" , protocolCodecFilter ) ; connector . getFilterChain ( ) . addLast ( "logger" , loggingFilter ) ; connector . getFilterChain ( ) . addLast ( "keepalive" , pollKeepAliveFilter ) ; if ( configuration . getStatusPollingInterval ( ) != - 1 ) { connector . getFilterChain ( ) . addLast ( "statusrequest" , new StatusRequestFilter ( configuration . getStatusPollingInterval ( ) ) ) ; } final DemuxingIoHandler demuxIoHandler = new DemuxingIoHandler ( ) ; final ReadCommandOnSubscribe readCommandObservable = new ReadCommandOnSubscribe ( ) ; demuxIoHandler . addReceivedMessageHandler ( ReadCommand . class , readCommandObservable ) ; demuxIoHandler . addExceptionHandler ( Exception . class , readCommandObservable ) ; if ( configuration . getEnvisalinkPassword ( ) != null ) { final EnvisalinkLoginHandler envisalinkLoginHandler = new EnvisalinkLoginHandler ( configuration . getEnvisalinkPassword ( ) ) ; demuxIoHandler . addReceivedMessageHandler ( EnvisalinkLoginInteractionCommand . class , envisalinkLoginHandler ) ; } demuxIoHandler . addSentMessageHandler ( Object . class , MessageHandler . NOOP ) ; connector . setHandler ( demuxIoHandler ) ; final ConnectFuture future = connector . connect ( configuration . getAddress ( ) ) ; future . awaitUninterruptibly ( ) ; session = future . getSession ( ) ; final ConnectableObservable < ReadCommand > connectableReadObservable = Observable . create ( readCommandObservable ) . publish ( ) ; connectableReadObservable . connect ( ) ; readObservable = connectableReadObservable . share ( ) . asObservable ( ) ; writeObservable = PublishSubject . create ( ) ; writeObservable . subscribe ( new Observer < WriteCommand > ( ) { public void onCompleted ( ) { } public void onError ( Throwable e ) { } public void onNext ( WriteCommand command ) { session . write ( command ) ; } } ) ; }
Begin communicating with the IT - 100 .
23,877
public void disconnect ( ) throws Exception { if ( session != null ) { session . getCloseFuture ( ) . awaitUninterruptibly ( ) ; } if ( connector != null ) { connector . dispose ( ) ; } }
Stop communicating with the IT - 100 and release the port .
23,878
public static int registerBitSize ( final long expectedUniqueElements ) { return Math . max ( HLL . MINIMUM_REGWIDTH_PARAM , ( int ) Math . ceil ( NumberUtil . log2 ( NumberUtil . log2 ( expectedUniqueElements ) ) ) ) ; }
Computes the bit - width of HLL registers necessary to estimate a set of the specified cardinality .
23,879
public static double alphaMSquared ( final int m ) { switch ( m ) { case 1 : case 2 : case 4 : case 8 : throw new IllegalArgumentException ( "'m' cannot be less than 16 (" + m + " < 16)." ) ; case 16 : return 0.673 * m * m ; case 32 : return 0.697 * m * m ; case 64 : return 0.709 * m * m ; default : return ( 0.7213 / ( 1.0 + 1.079 / m ) ) * m * m ; } }
Computes the alpha - m - squared constant used by the HyperLogLog algorithm .
23,880
public long cardinality ( ) { switch ( type ) { case EMPTY : return 0 ; case EXPLICIT : return explicitStorage . size ( ) ; case SPARSE : return ( long ) Math . ceil ( sparseProbabilisticAlgorithmCardinality ( ) ) ; case FULL : return ( long ) Math . ceil ( fullProbabilisticAlgorithmCardinality ( ) ) ; default : throw new RuntimeException ( "Unsupported HLL type " + type ) ; } }
Computes the cardinality of the HLL .
23,881
public void union ( final HLL other ) { final HLLType otherType = other . getType ( ) ; if ( type . equals ( otherType ) ) { homogeneousUnion ( other ) ; return ; } else { heterogenousUnion ( other ) ; return ; } }
Computes the union of HLLs and stores the result in this instance .
23,882
private void homogeneousUnion ( final HLL other ) { switch ( type ) { case EMPTY : return ; case EXPLICIT : for ( final long value : other . explicitStorage ) { addRaw ( value ) ; } return ; case SPARSE : for ( final int registerIndex : other . sparseProbabilisticStorage . keySet ( ) ) { final byte registerValue = other . sparseProbabilisticStorage . get ( registerIndex ) ; final byte currentRegisterValue = sparseProbabilisticStorage . get ( registerIndex ) ; if ( registerValue > currentRegisterValue ) { sparseProbabilisticStorage . put ( registerIndex , registerValue ) ; } } if ( sparseProbabilisticStorage . size ( ) > sparseThreshold ) { initializeStorage ( HLLType . FULL ) ; for ( final int registerIndex : sparseProbabilisticStorage . keySet ( ) ) { final byte registerValue = sparseProbabilisticStorage . get ( registerIndex ) ; probabilisticStorage . setMaxRegister ( registerIndex , registerValue ) ; } sparseProbabilisticStorage = null ; } return ; case FULL : for ( int i = 0 ; i < m ; i ++ ) { final long registerValue = other . probabilisticStorage . getRegister ( i ) ; probabilisticStorage . setMaxRegister ( i , registerValue ) ; } return ; default : throw new RuntimeException ( "Unsupported HLL type " + type ) ; } }
Computes the union of two HLLs of the same type and stores the result in this instance .
23,883
public byte [ ] toBytes ( final ISchemaVersion schemaVersion ) { final byte [ ] bytes ; switch ( type ) { case EMPTY : bytes = new byte [ schemaVersion . paddingBytes ( type ) ] ; break ; case EXPLICIT : { final IWordSerializer serializer = schemaVersion . getSerializer ( type , Long . SIZE , explicitStorage . size ( ) ) ; final long [ ] values = explicitStorage . toLongArray ( ) ; Arrays . sort ( values ) ; for ( final long value : values ) { serializer . writeWord ( value ) ; } bytes = serializer . getBytes ( ) ; break ; } case SPARSE : { final IWordSerializer serializer = schemaVersion . getSerializer ( type , shortWordLength , sparseProbabilisticStorage . size ( ) ) ; final int [ ] indices = sparseProbabilisticStorage . keySet ( ) . toIntArray ( ) ; Arrays . sort ( indices ) ; for ( final int registerIndex : indices ) { final long registerValue = sparseProbabilisticStorage . get ( registerIndex ) ; final long shortWord = ( ( registerIndex << regwidth ) | registerValue ) ; serializer . writeWord ( shortWord ) ; } bytes = serializer . getBytes ( ) ; break ; } case FULL : { final IWordSerializer serializer = schemaVersion . getSerializer ( type , regwidth , m ) ; probabilisticStorage . getRegisterContents ( serializer ) ; bytes = serializer . getBytes ( ) ; break ; } default : throw new RuntimeException ( "Unsupported HLL type " + type ) ; } final IHLLMetadata metadata = new HLLMetadata ( schemaVersion . schemaVersionNumber ( ) , type , log2m , regwidth , ( int ) NumberUtil . log2 ( explicitThreshold ) , explicitOff , explicitAuto , ! sparseOff ) ; schemaVersion . writeMetadata ( bytes , metadata ) ; return bytes ; }
Serializes the HLL to an array of bytes in correspondence with the format of the specified schema version .
23,884
public void getRegisterContents ( final IWordSerializer serializer ) { for ( final LongIterator iter = registerIterator ( ) ; iter . hasNext ( ) ; ) { serializer . writeWord ( iter . next ( ) ) ; } }
Serializes the registers of the vector using the specified serializer .
23,885
private static Date parseDate ( @ SuppressWarnings ( "SameParameterValue" ) String stringDate ) { try { return formatter . parse ( stringDate ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; return null ; } }
Helper method used to parse a date in string format . Meant to encapsulate the error handling .
23,886
protected MavenPomDescriptor createMavenPomDescriptor ( Model model , Scanner scanner ) { ScannerContext context = scanner . getContext ( ) ; MavenPomDescriptor pomDescriptor = context . peek ( MavenPomDescriptor . class ) ; if ( model instanceof EffectiveModel ) { context . getStore ( ) . addDescriptorType ( pomDescriptor , EffectiveDescriptor . class ) ; } pomDescriptor . setName ( model . getName ( ) ) ; pomDescriptor . setGroupId ( model . getGroupId ( ) ) ; pomDescriptor . setArtifactId ( model . getArtifactId ( ) ) ; pomDescriptor . setPackaging ( model . getPackaging ( ) ) ; pomDescriptor . setVersion ( model . getVersion ( ) ) ; pomDescriptor . setUrl ( model . getUrl ( ) ) ; Coordinates artifactCoordinates = new ModelCoordinates ( model ) ; MavenArtifactDescriptor artifact = getArtifactResolver ( context ) . resolve ( artifactCoordinates , context ) ; pomDescriptor . getDescribes ( ) . add ( artifact ) ; return pomDescriptor ; }
Create the descriptor and set base information .
23,887
private void addActivation ( MavenProfileDescriptor mavenProfileDescriptor , Activation activation , Store store ) { if ( null == activation ) { return ; } MavenProfileActivationDescriptor profileActivationDescriptor = store . create ( MavenProfileActivationDescriptor . class ) ; mavenProfileDescriptor . setActivation ( profileActivationDescriptor ) ; profileActivationDescriptor . setJdk ( activation . getJdk ( ) ) ; profileActivationDescriptor . setActiveByDefault ( activation . isActiveByDefault ( ) ) ; ActivationFile activationFile = activation . getFile ( ) ; if ( null != activationFile ) { MavenActivationFileDescriptor activationFileDescriptor = store . create ( MavenActivationFileDescriptor . class ) ; profileActivationDescriptor . setActivationFile ( activationFileDescriptor ) ; activationFileDescriptor . setExists ( activationFile . getExists ( ) ) ; activationFileDescriptor . setMissing ( activationFile . getMissing ( ) ) ; } ActivationOS os = activation . getOs ( ) ; if ( null != os ) { MavenActivationOSDescriptor osDescriptor = store . create ( MavenActivationOSDescriptor . class ) ; profileActivationDescriptor . setActivationOS ( osDescriptor ) ; osDescriptor . setArch ( os . getArch ( ) ) ; osDescriptor . setFamily ( os . getFamily ( ) ) ; osDescriptor . setName ( os . getName ( ) ) ; osDescriptor . setVersion ( os . getVersion ( ) ) ; } ActivationProperty property = activation . getProperty ( ) ; if ( null != property ) { PropertyDescriptor propertyDescriptor = store . create ( PropertyDescriptor . class ) ; profileActivationDescriptor . setProperty ( propertyDescriptor ) ; propertyDescriptor . setName ( property . getName ( ) ) ; propertyDescriptor . setValue ( property . getValue ( ) ) ; } }
Adds activation information for the given profile .
23,888
private void addConfiguration ( ConfigurableDescriptor configurableDescriptor , Xpp3Dom config , Store store ) { if ( null == config ) { return ; } MavenConfigurationDescriptor configDescriptor = store . create ( MavenConfigurationDescriptor . class ) ; configurableDescriptor . setConfiguration ( configDescriptor ) ; Xpp3Dom [ ] children = config . getChildren ( ) ; for ( Xpp3Dom child : children ) { configDescriptor . getValues ( ) . add ( getConfigChildNodes ( child , store ) ) ; } }
Adds configuration information .
23,889
private < P extends MavenDependentDescriptor , D extends AbstractDependencyDescriptor > List < MavenDependencyDescriptor > getDependencies ( P dependent , List < Dependency > dependencies , Class < D > dependsOnType , ScannerContext scannerContext ) { Store store = scannerContext . getStore ( ) ; List < MavenDependencyDescriptor > dependencyDescriptors = new ArrayList < > ( dependencies . size ( ) ) ; for ( Dependency dependency : dependencies ) { MavenArtifactDescriptor dependencyArtifactDescriptor = getMavenArtifactDescriptor ( dependency , scannerContext ) ; D dependsOnDescriptor = store . create ( dependent , dependsOnType , dependencyArtifactDescriptor ) ; dependsOnDescriptor . setOptional ( dependency . isOptional ( ) ) ; dependsOnDescriptor . setScope ( dependency . getScope ( ) ) ; MavenDependencyDescriptor dependencyDescriptor = store . create ( MavenDependencyDescriptor . class ) ; dependencyDescriptor . setToArtifact ( dependencyArtifactDescriptor ) ; dependencyDescriptor . setOptional ( dependency . isOptional ( ) ) ; dependencyDescriptor . setScope ( dependency . getScope ( ) ) ; for ( Exclusion exclusion : dependency . getExclusions ( ) ) { MavenExcludesDescriptor mavenExcludesDescriptor = store . create ( MavenExcludesDescriptor . class ) ; mavenExcludesDescriptor . setGroupId ( exclusion . getGroupId ( ) ) ; mavenExcludesDescriptor . setArtifactId ( exclusion . getArtifactId ( ) ) ; dependencyDescriptor . getExclusions ( ) . add ( mavenExcludesDescriptor ) ; } dependencyDescriptors . add ( dependencyDescriptor ) ; } return dependencyDescriptors ; }
Adds information about artifact dependencies .
23,890
private void addExecutionGoals ( MavenPluginExecutionDescriptor executionDescriptor , PluginExecution pluginExecution , Store store ) { List < String > goals = pluginExecution . getGoals ( ) ; for ( String goal : goals ) { MavenExecutionGoalDescriptor goalDescriptor = store . create ( MavenExecutionGoalDescriptor . class ) ; goalDescriptor . setName ( goal ) ; executionDescriptor . getGoals ( ) . add ( goalDescriptor ) ; } }
Adds information about execution goals .
23,891
private void addLicenses ( MavenPomDescriptor pomDescriptor , Model model , Store store ) { List < License > licenses = model . getLicenses ( ) ; for ( License license : licenses ) { MavenLicenseDescriptor licenseDescriptor = store . create ( MavenLicenseDescriptor . class ) ; licenseDescriptor . setUrl ( license . getUrl ( ) ) ; licenseDescriptor . setComments ( license . getComments ( ) ) ; licenseDescriptor . setName ( license . getName ( ) ) ; licenseDescriptor . setDistribution ( license . getDistribution ( ) ) ; pomDescriptor . getLicenses ( ) . add ( licenseDescriptor ) ; } }
Adds information about references licenses .
23,892
private void addDevelopers ( MavenPomDescriptor pomDescriptor , Model model , Store store ) { List < Developer > developers = model . getDevelopers ( ) ; for ( Developer developer : developers ) { MavenDeveloperDescriptor developerDescriptor = store . create ( MavenDeveloperDescriptor . class ) ; developerDescriptor . setId ( developer . getId ( ) ) ; addCommonParticipantAttributes ( developerDescriptor , developer , store ) ; pomDescriptor . getDevelopers ( ) . add ( developerDescriptor ) ; } }
Adds information about developers .
23,893
private List < MavenDependencyDescriptor > addManagedDependencies ( MavenDependentDescriptor pomDescriptor , DependencyManagement dependencyManagement , ScannerContext scannerContext , Class < ? extends AbstractDependencyDescriptor > relationClass ) { if ( dependencyManagement == null ) { return Collections . emptyList ( ) ; } List < Dependency > dependencies = dependencyManagement . getDependencies ( ) ; return getDependencies ( pomDescriptor , dependencies , relationClass , scannerContext ) ; }
Adds dependency management information .
23,894
private void addManagedPlugins ( BaseProfileDescriptor pomDescriptor , BuildBase build , ScannerContext scannerContext ) { if ( null == build ) { return ; } PluginManagement pluginManagement = build . getPluginManagement ( ) ; if ( null == pluginManagement ) { return ; } List < MavenPluginDescriptor > pluginDescriptors = createMavenPluginDescriptors ( pluginManagement . getPlugins ( ) , scannerContext ) ; pomDescriptor . getManagedPlugins ( ) . addAll ( pluginDescriptors ) ; }
Adds information about managed plugins .
23,895
private List < MavenPluginDescriptor > createMavenPluginDescriptors ( List < Plugin > plugins , ScannerContext context ) { Store store = context . getStore ( ) ; List < MavenPluginDescriptor > pluginDescriptors = new ArrayList < > ( ) ; for ( Plugin plugin : plugins ) { MavenPluginDescriptor mavenPluginDescriptor = store . create ( MavenPluginDescriptor . class ) ; MavenArtifactDescriptor artifactDescriptor = getArtifactResolver ( context ) . resolve ( new PluginCoordinates ( plugin ) , context ) ; mavenPluginDescriptor . setArtifact ( artifactDescriptor ) ; mavenPluginDescriptor . setInherited ( plugin . isInherited ( ) ) ; mavenPluginDescriptor . getDeclaresDependencies ( ) . addAll ( getDependencies ( mavenPluginDescriptor , plugin . getDependencies ( ) , PluginDependsOnDescriptor . class , context ) ) ; addPluginExecutions ( mavenPluginDescriptor , plugin , store ) ; addConfiguration ( mavenPluginDescriptor , ( Xpp3Dom ) plugin . getConfiguration ( ) , store ) ; pluginDescriptors . add ( mavenPluginDescriptor ) ; } return pluginDescriptors ; }
Create plugin descriptors for the given plugins .
23,896
private void addModules ( BaseProfileDescriptor pomDescriptor , List < String > modules , Store store ) { for ( String module : modules ) { MavenModuleDescriptor moduleDescriptor = store . create ( MavenModuleDescriptor . class ) ; moduleDescriptor . setName ( module ) ; pomDescriptor . getModules ( ) . add ( moduleDescriptor ) ; } }
Adds information about referenced modules .
23,897
private void addParent ( MavenPomDescriptor pomDescriptor , Model model , ScannerContext context ) { Parent parent = model . getParent ( ) ; if ( null != parent ) { ArtifactResolver resolver = getArtifactResolver ( context ) ; MavenArtifactDescriptor parentDescriptor = resolver . resolve ( new ParentCoordinates ( parent ) , context ) ; pomDescriptor . setParent ( parentDescriptor ) ; } }
Adds information about parent POM .
23,898
private void addPluginExecutions ( MavenPluginDescriptor mavenPluginDescriptor , Plugin plugin , Store store ) { List < PluginExecution > executions = plugin . getExecutions ( ) ; for ( PluginExecution pluginExecution : executions ) { MavenPluginExecutionDescriptor executionDescriptor = store . create ( MavenPluginExecutionDescriptor . class ) ; executionDescriptor . setId ( pluginExecution . getId ( ) ) ; executionDescriptor . setPhase ( pluginExecution . getPhase ( ) ) ; executionDescriptor . setInherited ( pluginExecution . isInherited ( ) ) ; mavenPluginDescriptor . getExecutions ( ) . add ( executionDescriptor ) ; addExecutionGoals ( executionDescriptor , pluginExecution , store ) ; addConfiguration ( executionDescriptor , ( Xpp3Dom ) pluginExecution . getConfiguration ( ) , store ) ; } }
Adds information about plugin executions .
23,899
private void addPlugins ( BaseProfileDescriptor pomDescriptor , BuildBase build , ScannerContext scannerContext ) { if ( null == build ) { return ; } List < Plugin > plugins = build . getPlugins ( ) ; List < MavenPluginDescriptor > pluginDescriptors = createMavenPluginDescriptors ( plugins , scannerContext ) ; pomDescriptor . getPlugins ( ) . addAll ( pluginDescriptors ) ; }
Adds information about plugins .