idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
23,800
@ Deprecated 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 .
55
21
23,801
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 .
64
23
23,802
@ Override public < T extends RedGEntity > T getDummy ( final AbstractRedG redG , final Class < T > dummyClass ) { // check if a dummy for this type already exists in cache if ( this . dummyCache . containsKey ( dummyClass ) ) { return dummyClass . cast ( this . dummyCache . get ( dummyClass ) ) ; } final T obj = createNewDummy ( redG , dummyClass ) ; // if no one is found, create new 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 .
121
90
23,803
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 .
43
20
23,804
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 .
496
16
23,805
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 .
170
26
23,806
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 .
158
12
23,807
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 .
110
19
23,808
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 .
57
11
23,809
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 ( ) ; // start index at 1 as group(0) always stands for the entire expression 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 .
162
14
23,810
private List < String > getVariables ( String routePath ) { List < String > variables = new ArrayList < String > ( ) ; Matcher matcher = Pattern . compile ( Path . VAR_REGEXP ) . matcher ( routePath ) ; while ( matcher . find ( ) ) { // group(0) always stands for the entire expression and we only want what is inside the {} variables . add ( matcher . group ( 1 ) ) ; } return variables ; }
Helper method . Retrieves all the variables defined in the path .
102
14
23,811
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 .
45
13
23,812
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 .
79
13
23,813
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 .
48
6
23,814
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 .
192
16
23,815
public String generateMainClass ( final Collection < TableModel > tables , final boolean enableVisualizationSupport ) { Objects . requireNonNull ( tables ) ; //get package from the table models 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 ) ; // TODO: make prefix usable 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
196
54
23,816
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
66
6
23,817
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
74
9
23,818
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
70
7
23,819
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
65
5
23,820
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 .
63
14
23,821
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 .
67
13
23,822
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 .
51
19
23,823
@ Override public String getMethodNameForReference ( final ForeignKey foreignKey ) { final Column c = foreignKey . getColumnReferences ( ) . get ( 0 ) . getForeignKeyColumn ( ) ; // check if only one-column fk 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_-])" , "" ) // Delete every not-alphanumeric or _/- character and numbers at beginning . split ( "_" ) ) ) ; words . removeAll ( Arrays . asList ( "fk" , "" , null ) ) ; // removes FK_ prefix and empty entries final List < String > tableWords = new ArrayList <> ( Arrays . asList ( c . getParent ( ) . getName ( ) . toLowerCase ( ) . replaceAll ( "(^[0-9]+|[^a-z0-9_-])" , "" ) // Delete every not-alphanumeric or _/- character and numbers at beginning . 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
416
10
23,824
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 .
105
17
23,825
private synchronized void performReliableSubscription ( ) { // If timer is not running, initialize it. if ( subscriberTimer == null ) { LOGGER . info ( "Initializing reliable subscriber" ) ; subscriberTimer = createTimerInternal ( ) ; ExponentialBackOff backOff = new ExponentialBackOff . Builder ( ) . setMaxElapsedTimeMillis ( Integer . MAX_VALUE /* Try forever */ ) . 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 .
179
6
23,826
@ VisibleForTesting 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 .
200
16
23,827
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 ( ) //.filter(c -> !c.isPartOfForeignKey()) // no longer filter due to #12 . map ( this . columnExtractor :: extractColumnModel ) . collect ( Collectors . toList ( ) ) ) ; Set < Set < String > > seenForeignKeyColumnNameTuples = new HashSet <> ( ) ; // TODO unit test removing duplicates model . setForeignKeys ( table . getImportedForeignKeys ( ) . stream ( ) // only get data about "outgoing" foreign keys . 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 <> ( ) ; // TODO unit test removing duplicates 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 .
586
30
23,828
private ServletRequest init ( ) throws MultipartException , IOException { // retrieve multipart/form-data parameters if ( Multipart . isMultipartContent ( request ) ) { Multipart multipart = new Multipart ( ) ; multipart . parse ( request , new PartHandler ( ) { @ Override public void handleFormItem ( String name , String value ) { multipartParams . put ( name , value ) ; } @ Override public void handleFileItem ( String name , FileItem fileItem ) { files . add ( fileItem ) ; } } ) ; } return this ; }
Initializes the path variables and the multipart content .
131
11
23,829
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 .
39
13
23,830
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
82
10
23,831
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 .
59
15
23,832
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 .
98
11
23,833
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 != ' ' ) { break ; } ++ nonWs ; } if ( nonWs == start ) { break ; } // continuation line found end = parseEndOfLine ( headerPart , nonWs ) ; header += " " + headerPart . substring ( nonWs , end ) ; start = end + 2 ; } // parse header line final int colonOffset = header . indexOf ( ' ' ) ; if ( colonOffset == - 1 ) { // this header line is malformed, skip it. 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 .
350
12
23,834
private String getFieldName ( String contentDisposition ) { String fieldName = null ; if ( contentDisposition != null && contentDisposition . toLowerCase ( ) . startsWith ( FORM_DATA ) ) { ParameterParser parser = new ParameterParser ( ) ; parser . setLowerCaseNames ( true ) ; // parameter parser can handle null input 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 .
134
19
23,835
protected byte [ ] getBoundary ( String contentType ) { ParameterParser parser = new ParameterParser ( ) ; parser . setLowerCaseNames ( true ) ; // Parameter parser can handle null input 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 .
151
20
23,836
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 ) ; // parameter parser can handle null input Map < String , String > params = parser . parse ( contentDisposition , ' ' ) ; if ( params . containsKey ( "filename" ) ) { fileName = ( String ) params . get ( "filename" ) ; if ( fileName != null ) { fileName = fileName . trim ( ) ; } else { // even if there is no value, the parameter is present, // so we return an empty file name rather than no file // name. fileName = "" ; } } } } return fileName ; }
Retrieves the file name of a file from the filename attribute of the Content - Disposition header of the part .
206
24
23,837
public void connect ( ) throws Exception { // Start up our MINA stuff // Setup MINA codecs 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 ) ; // Connect to system serial port. connector = configuration . getConnector ( ) ; // Typical configuration connector . setConnectTimeoutMillis ( configuration . getConnectTimeout ( ) ) ; connector . getSessionConfig ( ) . setUseReadOperation ( true ) ; // Add IT100 codec to MINA filter chain to interpret messages. 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 ( ) ; // Setup a read message handler // OnSubscribe will allow us to create an Observable to received messages. final ReadCommandOnSubscribe readCommandObservable = new ReadCommandOnSubscribe ( ) ; demuxIoHandler . addReceivedMessageHandler ( ReadCommand . class , readCommandObservable ) ; demuxIoHandler . addExceptionHandler ( Exception . class , readCommandObservable ) ; // Handle Envisalink 505 request for password events if ( configuration . getEnvisalinkPassword ( ) != null ) { final EnvisalinkLoginHandler envisalinkLoginHandler = new EnvisalinkLoginHandler ( configuration . getEnvisalinkPassword ( ) ) ; demuxIoHandler . addReceivedMessageHandler ( EnvisalinkLoginInteractionCommand . class , envisalinkLoginHandler ) ; } // We don't need to subscribe to the messages we sent. demuxIoHandler . addSentMessageHandler ( Object . class , MessageHandler . NOOP ) ; connector . setHandler ( demuxIoHandler ) ; // Connect now final ConnectFuture future = connector . connect ( configuration . getAddress ( ) ) ; future . awaitUninterruptibly ( ) ; // Get a reference to the session session = future . getSession ( ) ; // Create and return our Observable for received IT-100 commands. final ConnectableObservable < ReadCommand > connectableReadObservable = Observable . create ( readCommandObservable ) . publish ( ) ; connectableReadObservable . connect ( ) ; readObservable = connectableReadObservable . share ( ) . asObservable ( ) ; // Create a write observer. writeObservable = PublishSubject . create ( ) ; writeObservable . subscribe ( new Observer < WriteCommand > ( ) { @ Override public void onCompleted ( ) { } @ Override public void onError ( Throwable e ) { } @ Override public void onNext ( WriteCommand command ) { session . write ( command ) ; } } ) ; }
Begin communicating with the IT - 100 .
758
8
23,838
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 .
47
12
23,839
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 .
67
21
23,840
public static double alphaMSquared ( final int m ) { switch ( m ) { case 1 /*2^0*/ : case 2 /*2^1*/ : case 4 /*2^2*/ : case 8 /*2^3*/ : throw new IllegalArgumentException ( "'m' cannot be less than 16 (" + m + " < 16)." ) ; case 16 /*2^4*/ : return 0.673 * m * m ; case 32 /*2^5*/ : return 0.697 * m * m ; case 64 /*2^6*/ : return 0.709 * m * m ; default /*>2^6*/ : return ( 0.7213 / ( 1.0 + 1.079 / m ) ) * m * m ; } }
Computes the alpha - m - squared constant used by the HyperLogLog algorithm .
161
17
23,841
public long cardinality ( ) { switch ( type ) { case EMPTY : return 0 /*by definition*/ ; 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 .
110
10
23,842
public void union ( final HLL other ) { // TODO: verify HLLs are compatible 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 .
68
16
23,843
private void homogeneousUnion ( final HLL other ) { switch ( type ) { case EMPTY : // union of empty and empty is empty return ; case EXPLICIT : for ( final long value : other . explicitStorage ) { addRaw ( value ) ; } // NOTE: #addRaw() will handle promotion, if necessary 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 ) ; } } // promotion, if necessary 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 .
338
21
23,844
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 ) ; // pack index and value into "short word" 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 .
436
21
23,845
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 .
51
13
23,846
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 .
59
20
23,847
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 .
281
8
23,848
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 .
459
8
23,849
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 .
128
4
23,850
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 ) ; // Deprecated graph structure D dependsOnDescriptor = store . create ( dependent , dependsOnType , dependencyArtifactDescriptor ) ; dependsOnDescriptor . setOptional ( dependency . isOptional ( ) ) ; dependsOnDescriptor . setScope ( dependency . getScope ( ) ) ; // New graph structure supporting exclusions 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 .
424
6
23,851
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 .
117
6
23,852
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 .
161
6
23,853
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 .
127
5
23,854
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 .
116
5
23,855
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 .
123
6
23,856
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 .
291
9
23,857
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 .
93
6
23,858
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 .
105
7
23,859
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 .
209
6
23,860
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 .
102
5
23,861
private void _addProfileDependencies ( MavenProfileDescriptor profileDescriptor , List < Dependency > dependencies , ScannerContext scannerContext ) { for ( Dependency dependency : dependencies ) { MavenArtifactDescriptor dependencyArtifactDescriptor = getMavenArtifactDescriptor ( dependency , scannerContext ) ; Store store = scannerContext . getStore ( ) ; ProfileDeclaresDependencyDescriptor profileDependsOnDescriptor = store . create ( profileDescriptor , ProfileDeclaresDependencyDescriptor . class , dependencyArtifactDescriptor ) ; profileDependsOnDescriptor . setOptional ( dependency . isOptional ( ) ) ; profileDependsOnDescriptor . setScope ( dependency . getScope ( ) ) ; } }
Adds information about profile dependencies .
169
6
23,862
private void addProfiles ( MavenPomDescriptor pomDescriptor , Model model , ScannerContext scannerContext ) { List < Profile > profiles = model . getProfiles ( ) ; Store store = scannerContext . getStore ( ) ; for ( Profile profile : profiles ) { MavenProfileDescriptor mavenProfileDescriptor = store . create ( MavenProfileDescriptor . class ) ; pomDescriptor . getProfiles ( ) . add ( mavenProfileDescriptor ) ; mavenProfileDescriptor . setId ( profile . getId ( ) ) ; addProperties ( mavenProfileDescriptor , profile . getProperties ( ) , store ) ; addModules ( mavenProfileDescriptor , profile . getModules ( ) , store ) ; addPlugins ( mavenProfileDescriptor , profile . getBuild ( ) , scannerContext ) ; addManagedPlugins ( mavenProfileDescriptor , profile . getBuild ( ) , scannerContext ) ; addDependencies ( mavenProfileDescriptor , ProfileDeclaresDependencyDescriptor . class , ProfileManagesDependencyDescriptor . class , profile , scannerContext ) ; addActivation ( mavenProfileDescriptor , profile . getActivation ( ) , store ) ; addRepository ( of ( mavenProfileDescriptor ) , profile . getRepositories ( ) , store ) ; } }
Adds information about defined profile .
310
6
23,863
private void addProperties ( BaseProfileDescriptor pomDescriptor , Properties properties , Store store ) { Set < Entry < Object , Object > > entrySet = properties . entrySet ( ) ; for ( Entry < Object , Object > entry : entrySet ) { PropertyDescriptor propertyDescriptor = store . create ( PropertyDescriptor . class ) ; propertyDescriptor . setName ( entry . getKey ( ) . toString ( ) ) ; propertyDescriptor . setValue ( entry . getValue ( ) . toString ( ) ) ; pomDescriptor . getProperties ( ) . add ( propertyDescriptor ) ; } }
Adds information about defined properties .
142
6
23,864
private MavenArtifactDescriptor getMavenArtifactDescriptor ( Dependency dependency , ScannerContext context ) { DependencyCoordinates coordinates = new DependencyCoordinates ( dependency ) ; return getArtifactResolver ( context ) . resolve ( coordinates , context ) ; }
Creates a MavenArtifactDescriptor and fills it with all information from given dependency .
62
20
23,865
private ValueDescriptor < ? > getConfigChildNodes ( Xpp3Dom node , Store store ) { Xpp3Dom [ ] children = node . getChildren ( ) ; if ( children . length == 0 ) { PropertyDescriptor propertyDescriptor = store . create ( PropertyDescriptor . class ) ; propertyDescriptor . setName ( node . getName ( ) ) ; propertyDescriptor . setValue ( node . getValue ( ) ) ; return propertyDescriptor ; } ArrayValueDescriptor childDescriptor = store . create ( ArrayValueDescriptor . class ) ; childDescriptor . setName ( node . getName ( ) ) ; for ( Xpp3Dom child : children ) { childDescriptor . getValue ( ) . add ( getConfigChildNodes ( child , store ) ) ; } return childDescriptor ; }
Returns information about child config entries .
190
7
23,866
public static MavenRepositoryDescriptor resolve ( Store store , String url ) { MavenRepositoryDescriptor repositoryDescriptor = store . find ( MavenRepositoryDescriptor . class , url ) ; if ( repositoryDescriptor == null ) { repositoryDescriptor = store . create ( MavenRepositoryDescriptor . class ) ; repositoryDescriptor . setUrl ( url ) ; } return repositoryDescriptor ; }
Finds or creates a repository descriptor for the given url .
96
12
23,867
private static void seedData ( PersistenceManager manager ) throws OnyxException { // Create test data Book harryPotter = new Book ( ) ; harryPotter . setTitle ( "Harry Potter, Deathly Hallows" ) ; harryPotter . setDescription ( "Story about a kid that has abnormal creepy powers that seeks revenge on a poor innocent guy named Voldomort." ) ; harryPotter . setGenre ( "CHILDREN" ) ; Book theGiver = new Book ( ) ; theGiver . setTitle ( "The Giver" ) ; theGiver . setDescription ( "Something about a whole community of color blind people." ) ; theGiver . setGenre ( "CHILDREN" ) ; Book twilight = new Book ( ) ; twilight . setTitle ( "Twilight" ) ; twilight . setGenre ( "CHILDREN" ) ; twilight . setDescription ( "Book that lead to awful teenie bopper vampire movie." ) ; Book longWayDown = new Book ( ) ; longWayDown . setTitle ( "Long Way Down" ) ; longWayDown . setGenre ( "TRAVEL" ) ; longWayDown . setDescription ( "Boring story about something I cant remember." ) ; // Save book data manager . saveEntity ( harryPotter ) ; manager . saveEntity ( theGiver ) ; manager . saveEntity ( twilight ) ; manager . saveEntity ( longWayDown ) ; }
Insert test data into a test database
316
7
23,868
private < T extends MavenArtifactDescriptor > T getMavenArtifactDescriptor ( Coordinates coordinates , ArtifactResolver artifactResolver , Class < T > type , Scanner scanner ) { MavenArtifactDescriptor mavenArtifactDescriptor = artifactResolver . resolve ( coordinates , scanner . getContext ( ) ) ; return scanner . getContext ( ) . getStore ( ) . addDescriptorType ( mavenArtifactDescriptor , type ) ; }
Returns a resolved maven artifact descriptor for the given coordinates .
106
12
23,869
protected < T extends MavenProjectDescriptor > T resolveProject ( MavenProject project , Class < T > expectedType , ScannerContext scannerContext ) { Store store = scannerContext . getStore ( ) ; String id = project . getGroupId ( ) + ":" + project . getArtifactId ( ) + ":" + project . getVersion ( ) ; MavenProjectDescriptor projectDescriptor = store . find ( MavenProjectDescriptor . class , id ) ; if ( projectDescriptor == null ) { projectDescriptor = store . create ( expectedType , id ) ; projectDescriptor . setName ( project . getName ( ) ) ; projectDescriptor . setGroupId ( project . getGroupId ( ) ) ; projectDescriptor . setArtifactId ( project . getArtifactId ( ) ) ; projectDescriptor . setVersion ( project . getVersion ( ) ) ; projectDescriptor . setPackaging ( project . getPackaging ( ) ) ; projectDescriptor . setFullQualifiedName ( id ) ; } else if ( ! expectedType . isAssignableFrom ( projectDescriptor . getClass ( ) ) ) { projectDescriptor = store . addDescriptorType ( projectDescriptor , expectedType ) ; } return expectedType . cast ( projectDescriptor ) ; }
Resolves a maven project .
294
7
23,870
private void addProjectDetails ( MavenProject project , MavenProjectDirectoryDescriptor projectDescriptor , Scanner scanner ) { ScannerContext scannerContext = scanner . getContext ( ) ; addParent ( project , projectDescriptor , scannerContext ) ; addModules ( project , projectDescriptor , scannerContext ) ; addModel ( project , projectDescriptor , scanner ) ; }
Add project specific information .
84
5
23,871
private void addModel ( MavenProject project , MavenProjectDirectoryDescriptor projectDescriptor , Scanner scanner ) { File pomXmlFile = project . getFile ( ) ; FileDescriptor mavenPomXmlDescriptor = scanner . scan ( pomXmlFile , pomXmlFile . getAbsolutePath ( ) , MavenScope . PROJECT ) ; projectDescriptor . setModel ( mavenPomXmlDescriptor ) ; // Effective model MavenPomDescriptor effectiveModelDescriptor = scanner . getContext ( ) . getStore ( ) . create ( MavenPomDescriptor . class ) ; Model model = new EffectiveModel ( project . getModel ( ) ) ; scanner . getContext ( ) . push ( MavenPomDescriptor . class , effectiveModelDescriptor ) ; scanner . scan ( model , pomXmlFile . getAbsolutePath ( ) , MavenScope . PROJECT ) ; scanner . getContext ( ) . pop ( MavenPomDescriptor . class ) ; projectDescriptor . setEffectiveModel ( effectiveModelDescriptor ) ; }
Scan the pom . xml file and add it as model .
251
13
23,872
private void addParent ( MavenProject project , MavenProjectDirectoryDescriptor projectDescriptor , ScannerContext scannerContext ) { MavenProject parent = project . getParent ( ) ; if ( parent != null ) { MavenProjectDescriptor parentDescriptor = resolveProject ( parent , MavenProjectDescriptor . class , scannerContext ) ; projectDescriptor . setParent ( parentDescriptor ) ; } }
Add the relation to the parent project .
93
8
23,873
private void addModules ( MavenProject project , MavenProjectDirectoryDescriptor projectDescriptor , ScannerContext scannerContext ) { File projectDirectory = project . getBasedir ( ) ; Set < File > modules = new HashSet <> ( ) ; for ( String moduleName : project . getModules ( ) ) { File module = new File ( projectDirectory , moduleName ) ; modules . add ( module ) ; } for ( MavenProject module : project . getCollectedProjects ( ) ) { if ( modules . contains ( module . getBasedir ( ) ) ) { MavenProjectDescriptor moduleDescriptor = resolveProject ( module , MavenProjectDescriptor . class , scannerContext ) ; projectDescriptor . getModules ( ) . add ( moduleDescriptor ) ; } } }
Add relations to the modules .
177
6
23,874
private void scanClassesDirectory ( MavenProjectDirectoryDescriptor projectDescriptor , MavenArtifactDescriptor artifactDescriptor , final String directoryName , Scanner scanner ) { File directory = new File ( directoryName ) ; if ( directory . exists ( ) ) { scanArtifact ( projectDescriptor , artifactDescriptor , directory , directoryName , scanner ) ; } }
Scan the given directory for classes and add them to an artifact .
84
13
23,875
private < F extends FileDescriptor > F scanFile ( MavenProjectDirectoryDescriptor projectDescriptor , File file , String path , Scope scope , Scanner scanner ) { scanner . getContext ( ) . push ( MavenProjectDirectoryDescriptor . class , projectDescriptor ) ; try { return scanner . scan ( file , path , scope ) ; } finally { scanner . getContext ( ) . pop ( MavenProjectDirectoryDescriptor . class ) ; } }
Scan a given file .
103
5
23,876
@ SuppressWarnings ( { "unchecked" , "SpellCheckingInspection" } ) List < Meeting > findBoringMeetings ( ) { Query query = new Query ( Meeting . class , new QueryCriteria ( "notes" , QueryCriteriaOperator . CONTAINS , "Boring" ) ) ; List < Meeting > boringMeetings = null ; try { boringMeetings = persistenceManager . executeQuery ( query ) ; } catch ( OnyxException e ) { // Log an error } return boringMeetings ; }
Method used to stream all meetings at work that are snoozers and are really hard to stay awake but you still have to pay attention because someone is going to call on you and ask you a dumb question .
115
42
23,877
@ Bean protected PersistenceManagerFactory persistenceManagerFactory ( ) throws InitializationException { CacheManagerFactory cacheManagerFactory = new CacheManagerFactory ( ) ; cacheManagerFactory . initialize ( ) ; return cacheManagerFactory ; }
Persistence Manager factory . This determines your database connection . This would have the same usage if you were connecting to an embedded or remote database . The only difference would be the factory type .
45
37
23,878
public static void main ( String [ ] args ) throws Exception { String pathToOnyxDB = System . getProperty ( "user.home" ) + File . separatorChar + ".onyxdb" + File . separatorChar + "sandbox" + File . separatorChar + "remote-db.oxd" ; DatabaseServer server1 = new DatabaseServer ( pathToOnyxDB ) ; server1 . setPort ( 8081 ) ; server1 . setCredentials ( "onyx-remote" , "SavingDataIsFun!" ) ; server1 . start ( ) ; System . out . println ( "Server Started" ) ; server1 . join ( ) ; //joins the database thread with the application thread }
Run Database Server
157
3
23,879
private static void seedData ( PersistenceManager manager ) throws OnyxException { // Create a call log for area code (555) CellPhone myPhoneNumber = new CellPhone ( ) ; myPhoneNumber . setCellPhoneNumber ( "(555) 303-2322" ) ; myPhoneNumber . setAreaCode ( 555 ) ; manager . saveEntity ( myPhoneNumber ) ; CallLog callToMom = new CallLog ( ) ; callToMom . setDestinationNumber ( "(555) 323-2222" ) ; callToMom . setNSAListening ( true ) ; callToMom . setCallFrom ( myPhoneNumber ) ; callToMom . setCallFromAreaCode ( myPhoneNumber . getAreaCode ( ) ) ; manager . saveEntity ( callToMom ) ; @ SuppressWarnings ( "SpellCheckingInspection" ) CallLog callToEdwardSnowden = new CallLog ( ) ; callToEdwardSnowden . setDestinationNumber ( "(555) 122-2341" ) ; callToEdwardSnowden . setNSAListening ( false ) ; callToEdwardSnowden . setCallFrom ( myPhoneNumber ) ; callToEdwardSnowden . setCallFromAreaCode ( myPhoneNumber . getAreaCode ( ) ) ; manager . saveEntity ( callToEdwardSnowden ) ; // Create a call log for area code (123) // Note: Identifiers are not unique among partitions. Since the entire object graph is saved, // it is possible in this example to have the same identifiers for a CallLog in area code 555 as well as 123 CellPhone mySecretPhone = new CellPhone ( ) ; mySecretPhone . setCellPhoneNumber ( "(123) 936-3733" ) ; mySecretPhone . setAreaCode ( 123 ) ; manager . saveEntity ( mySecretPhone ) ; CallLog callToSomeoneShady = new CallLog ( ) ; callToSomeoneShady . setDestinationNumber ( "(555) 322-1143" ) ; callToSomeoneShady . setNSAListening ( false ) ; callToSomeoneShady . setCallFrom ( mySecretPhone ) ; callToSomeoneShady . setCallFromAreaCode ( mySecretPhone . getAreaCode ( ) ) ; manager . saveEntity ( callToSomeoneShady ) ; CallLog callToJoe = new CallLog ( ) ; callToJoe . setDestinationNumber ( "(555) 286-9987" ) ; callToJoe . setNSAListening ( true ) ; callToJoe . setCallFrom ( mySecretPhone ) ; callToJoe . setCallFromAreaCode ( mySecretPhone . getAreaCode ( ) ) ; manager . saveEntity ( callToJoe ) ; }
Seed Cell phone log data
578
6
23,880
public void update ( Object object ) { try { persistenceManager . saveEntity ( ( IManagedEntity ) object ) ; } catch ( InitializationException ignore ) { } catch ( Exception e ) { e . printStackTrace ( ) ; } }
Update an entity that must already exist . Within onyx there is no differentiation between inserting and updating so either way it will call the saveEntity method
52
29
23,881
public List list ( Class clazz , String key , Object value ) { QueryCriteria criteria = new QueryCriteria ( key , QueryCriteriaOperator . EQUAL , value ) ; Query query = new Query ( clazz , criteria ) ; try { return persistenceManager . executeLazyQuery ( query ) ; } catch ( InitializationException ignore ) { } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; }
Execute query with criteria of key = key
95
9
23,882
public void insert ( Object object ) { EntityManager entityManager = null ; try { entityManager = entityManagers . poll ( ) ; entityManager . getTransaction ( ) . begin ( ) ; try { entityManager . persist ( object ) ; entityManager . getTransaction ( ) . commit ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; entityManager . getTransaction ( ) . rollback ( ) ; } } finally { if ( entityManager != null ) entityManagers . add ( entityManager ) ; } }
Insert an entity that must not already exist within the database . Within JPA this uses the persist method as opposed to the merge .
114
26
23,883
public List list ( Class clazz , String key , Object value ) { EntityManager entityManager = null ; try { entityManager = entityManagers . poll ( ) ; Query query = entityManager . createQuery ( "SELECT c FROM " + clazz . getCanonicalName ( ) + " c where c." + key + " = :param" ) ; query . setParameter ( "param" , value ) ; return query . getResultList ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { if ( entityManager != null ) entityManagers . add ( entityManager ) ; } return null ; }
Execute query with criteria of key = key . This will auto generate a sql statement .
138
18
23,884
static void assertNotNull ( String message , Object nonNullObject ) { if ( nonNullObject == null ) { System . err . println ( message ) ; } }
Helper method to verify an the object is not null .
35
11
23,885
static void assertEquals ( String message , Object comparison1 , Object comparison2 ) { if ( comparison1 == comparison2 ) { return ; } if ( comparison1 . equals ( comparison2 ) ) { return ; } System . err . println ( message ) ; }
Helper method to verify 2 objects have the same key
55
10
23,886
@ SuppressWarnings ( "ResultOfMethodCallIgnored" ) static private void deleteDirectory ( File path ) { if ( path . exists ( ) ) { //noinspection ConstantConditions for ( File f : path . listFiles ( ) ) { if ( f . isDirectory ( ) ) { deleteDirectory ( f ) ; } f . delete ( ) ; } path . delete ( ) ; } }
Helper method for deleting the database directory
87
7
23,887
public Integer countPost ( Query query ) throws ApiException { ApiResponse < Integer > resp = countPostWithHttpInfo ( query ) ; return resp . getData ( ) ; }
Get count for query Get the number of items matching query criteria
39
12
23,888
public ApiResponse < Void > deleteEntitiesPostWithHttpInfo ( DeleteEntitiesRequest request ) throws ApiException { com . squareup . okhttp . Call call = deleteEntitiesPostValidateBeforeCall ( request , null , null ) ; return apiClient . execute ( call ) ; }
Bulk Delete Managed Entities This is used to batch delete entities in order to provide optimized throughput .
63
21
23,889
public Integer executeUpdatePost ( Query query ) throws ApiException { ApiResponse < Integer > resp = executeUpdatePostWithHttpInfo ( query ) ; return resp . getData ( ) ; }
Execute Update Query Execute update query with defined criteria and update instructions
41
14
23,890
public ApiResponse < Void > saveEntitiesPostWithHttpInfo ( SaveEntitiesRequest request ) throws ApiException { com . squareup . okhttp . Call call = saveEntitiesPostValidateBeforeCall ( request , null , null ) ; return apiClient . execute ( call ) ; }
Bulk Save Managed Entities This is used to batch save entities in order to provide optimized throughput .
63
21
23,891
private static void seedData ( PersistenceManager manager ) throws OnyxException { Account account = new Account ( ) ; //noinspection SpellCheckingInspection account . setAccountName ( "Timbob's Lawn Care" ) ; account . setBalanceDue ( 55.43f ) ; Invoice marchLawnInvoice = new Invoice ( ) ; marchLawnInvoice . setDueDate ( parseDate ( "04-01-2016" ) ) ; marchLawnInvoice . setInvoiceDate ( parseDate ( "03-01-2016" ) ) ; marchLawnInvoice . setNotes ( "Why did we need to mow your lawn. Its basically a dirt field." ) ; marchLawnInvoice . setInvoiceId ( 1L ) ; marchLawnInvoice . setAmount ( 44.32 ) ; marchLawnInvoice . setAccount ( account ) ; Invoice aprilLawnInvoice = new Invoice ( ) ; aprilLawnInvoice . setDueDate ( parseDate ( "04-01-2016" ) ) ; aprilLawnInvoice . setInvoiceDate ( parseDate ( "03-01-2016" ) ) ; aprilLawnInvoice . setNotes ( "Its April, your lawn should be growing by now." ) ; aprilLawnInvoice . setInvoiceId ( 2L ) ; aprilLawnInvoice . setAmount ( 44.32 ) ; aprilLawnInvoice . setAccount ( account ) ; manager . saveEntity ( account ) ; manager . saveEntity ( marchLawnInvoice ) ; manager . saveEntity ( aprilLawnInvoice ) ; Payment marchLawnCarePayment = new Payment ( ) ; marchLawnCarePayment . setPaymentId ( 1L ) ; marchLawnCarePayment . setInvoice ( marchLawnInvoice ) ; marchLawnCarePayment . setAmount ( 44.32 ) ; manager . saveEntity ( marchLawnCarePayment ) ; Account account1 = manager . findById ( Account . class , 1 ) ; assert account1 != null ; assert account1 . getAccountId ( ) == 1L ; }
Fill the database with some test data so that we can show how the data model updates impact the changes to the values .
467
24
23,892
private static void deleteDatabase ( String pathToDb ) { File database = new File ( pathToDb ) ; if ( database . exists ( ) ) { delete ( database ) ; } database . delete ( ) ; }
Delete a database so you have a clean slate prior to testing
45
12
23,893
public static void setCoordinates ( MavenArtifactDescriptor artifactDescriptor , Coordinates coordinates ) { artifactDescriptor . setGroup ( coordinates . getGroup ( ) ) ; artifactDescriptor . setName ( coordinates . getName ( ) ) ; artifactDescriptor . setVersion ( coordinates . getVersion ( ) ) ; artifactDescriptor . setClassifier ( coordinates . getClassifier ( ) ) ; artifactDescriptor . setType ( coordinates . getType ( ) ) ; }
Apply the given coordinates to an artifact descriptor .
108
9
23,894
public static void setId ( MavenArtifactDescriptor artifactDescriptor , Coordinates coordinates ) { artifactDescriptor . setFullQualifiedName ( MavenArtifactHelper . getId ( coordinates ) ) ; }
Set the fully qualified name of an artifact descriptor .
48
10
23,895
public static String getId ( Coordinates coordinates ) { StringBuilder id = new StringBuilder ( ) ; if ( StringUtils . isNotEmpty ( coordinates . getGroup ( ) ) ) { id . append ( coordinates . getGroup ( ) ) ; } id . append ( ' ' ) ; id . append ( coordinates . getName ( ) ) ; id . append ( ' ' ) ; id . append ( coordinates . getType ( ) ) ; String classifier = coordinates . getClassifier ( ) ; if ( StringUtils . isNotEmpty ( classifier ) ) { id . append ( ' ' ) ; id . append ( classifier ) ; } String version = coordinates . getVersion ( ) ; if ( StringUtils . isNotEmpty ( version ) ) { id . append ( ' ' ) ; id . append ( version ) ; } return id . toString ( ) ; }
Creates the id of an coordinates descriptor by the given items .
186
13
23,896
public static void purgeOAuthAccessTokens ( RequestContext requestContext , String provider ) { String key = String . format ( PROVIDER_ACCESS_TOKENS , provider ) ; HttpSession session = requestContext . getRequest ( ) . getSession ( ) ; OAuthAccessToken [ ] accessTokens = ( OAuthAccessToken [ ] ) session . getAttribute ( key ) ; if ( accessTokens != null ) { session . removeAttribute ( key ) ; } }
Purges all OAuth tokens from given provider
99
9
23,897
public static OAuthAccessToken getOAuthAccessToken ( RequestContext requestContext , String provider , String ... scopes ) { HttpSession session = requestContext . getRequest ( ) . getSession ( ) ; OAuthAccessToken [ ] accessTokens = ( OAuthAccessToken [ ] ) session . getAttribute ( String . format ( PROVIDER_ACCESS_TOKENS , provider ) ) ; if ( accessTokens != null ) { for ( OAuthAccessToken accessToken : accessTokens ) { List < String > accessTokenScopes = accessToken . getScopes ( ) != null ? Arrays . asList ( accessToken . getScopes ( ) ) : Collections . emptyList ( ) ; if ( scopes == null || accessTokenScopes . containsAll ( Arrays . asList ( scopes ) ) ) { if ( isOAuthTokenExpired ( accessToken ) ) { if ( "Keycloak" . equals ( provider ) ) { return getKeycloakStrategy ( ) . refreshToken ( requestContext , accessToken ) ; } } else { return accessToken ; } } } } return null ; }
Returns OAuth previously stored access token from HTTP session
239
10
23,898
private String getRefreshToken ( Token accessToken ) { JSONObject rawJson = JSONObject . fromObject ( accessToken . getRawResponse ( ) ) ; return rawJson . getString ( "refresh_token" ) ; }
Parses refresh token from the access token
51
9
23,899
protected String extractLastName ( String name ) { if ( StringUtils . isBlank ( name ) ) { return null ; } int lastIndexOf = name . lastIndexOf ( ' ' ) ; if ( lastIndexOf == - 1 ) return null ; else return name . substring ( lastIndexOf + 1 ) ; }
Extracts a last name of full name string
70
10