idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
141,000
public final double getDistanceKmToPath ( Position p1 , Position p2 ) { double d = radiusEarthKm * asin ( sin ( getDistanceToKm ( p1 ) / radiusEarthKm ) * sin ( toRadians ( getBearingDegrees ( p1 ) - p1 . getBearingDegrees ( p2 ) ) ) ) ; return abs ( d ) ; }
calculates the distance of a point to the great circle path between p1 and p2 .
89
20
141,001
@ SuppressWarnings ( "unchecked" ) public static void setModelClass ( Class < ? > modelClass ) throws IllegalArgumentException { if ( ! DefaultModelImpl . class . isAssignableFrom ( modelClass ) ) { throw new IllegalArgumentException ( "Modelclass, " + modelClass . getName ( ) + ", is not a subtype of " + DefaultModelImpl . class . getName ( ) ) ; } ModelFactory . modelClass = ( Class < DefaultModelImpl > ) modelClass ; }
Register a custom model class must be a subclass to DefaultModelImpl .
113
14
141,002
public static void resetModelClass ( ) { ModelFactory . modelClass = DefaultModelImpl . class ; System . err . println ( "[INFO] Reset model-class: " + ModelFactory . modelClass . getName ( ) ) ; }
Reset model class to the default class .
50
9
141,003
public static IModel newModel ( String groupId , String artifactId , String version , String service , MuleVersionEnum muleVersion , TransportEnum inboundTransport , TransportEnum outboundTransport , TransformerEnum transformerType ) { return doCreateNewModel ( groupId , artifactId , version , service , muleVersion , null , null , inboundTransport , outboundTransport , transformerType , null , null ) ; }
Constructor - method to use when services with inbound and outbound services
97
15
141,004
public static void lockMemory ( boolean useSystemJNADisabled ) { if ( useSystemJNADisabled ) disableUsingSystemJNA ( ) ; try { int errorCode = MemoryLockerLinux . INSTANCE . mlockall ( MemoryLockerLinux . LOCK_CURRENT_MEMORY ) ; if ( errorCode != 0 ) { final String errorMessage ; int lastError = Native . getLastError ( ) ; switch ( lastError ) { case MemoryLockerLinux . EPERM : errorMessage = "The calling process does not have the appropriate privilege to perform the requested operation(EPERM)." ; break ; case MemoryLockerLinux . EAGAIN : errorMessage = "Some or all of the memory identified by the operation could not be locked when the call was made(EAGAIN)." ; break ; case MemoryLockerLinux . ENOMEM : errorMessage = "Unable to lock JVM memory. This can result in part of the JVM being swapped out, especially if mmapping of files enabled. Increase RLIMIT_MEMLOCK or run OrientDB server as root(ENOMEM)." ; break ; case MemoryLockerLinux . EINVAL : errorMessage = "The flags argument is zero, or includes unimplemented flags(EINVAL)." ; break ; case MemoryLockerLinux . ENOSYS : errorMessage = "The implementation does not support this memory locking interface(ENOSYS)." ; break ; default : errorMessage = "Unexpected exception with code " + lastError + "." ; break ; } OLogManager . instance ( ) . error ( null , "[MemoryLocker.lockMemory] Error occurred while locking memory: %s" , errorMessage ) ; } else { OLogManager . instance ( ) . info ( null , "[MemoryLocker.lockMemory] Memory locked successfully!" ) ; } } catch ( UnsatisfiedLinkError e ) { OLogManager . instance ( ) . config ( null , "[MemoryLocker.lockMemory] Cannot lock virtual memory. It seems that you OS (%s) doesn't support this feature" , System . getProperty ( "os.name" ) ) ; } }
This method locks memory to prevent swapping . This method provide information about success or problems with locking memory . You can reed console output to know if memory locked successfully or not . If system error occurred such as permission any specific exception will be thrown .
460
49
141,005
public OMVRBTreeEntry < K , V > getFirstInMemory ( ) { OMVRBTreeEntry < K , V > node = this ; OMVRBTreeEntry < K , V > prev = this ; while ( node != null ) { prev = node ; node = node . getPreviousInMemory ( ) ; } return prev ; }
Returns the first Entry only by traversing the memory or null if no such .
73
16
141,006
public OMVRBTreeEntry < K , V > getPreviousInMemory ( ) { OMVRBTreeEntry < K , V > t = this ; OMVRBTreeEntry < K , V > p = null ; if ( t . getLeftInMemory ( ) != null ) { p = t . getLeftInMemory ( ) ; while ( p . getRightInMemory ( ) != null ) p = p . getRightInMemory ( ) ; } else { p = t . getParentInMemory ( ) ; while ( p != null && t == p . getLeftInMemory ( ) ) { t = p ; p = p . getParentInMemory ( ) ; } } return p ; }
Returns the previous of the current Entry only by traversing the memory or null if no such .
148
19
141,007
private V linearSearch ( final K iKey ) { V value = null ; int i = 0 ; tree . pageItemComparator = - 1 ; for ( int s = getSize ( ) ; i < s ; ++ i ) { if ( tree . comparator != null ) tree . pageItemComparator = tree . comparator . compare ( getKeyAt ( i ) , iKey ) ; else tree . pageItemComparator = ( ( Comparable < ? super K > ) getKeyAt ( i ) ) . compareTo ( iKey ) ; if ( tree . pageItemComparator == 0 ) { // FOUND: SET THE INDEX AND RETURN THE NODE tree . pageItemFound = true ; value = getValueAt ( i ) ; break ; } else if ( tree . pageItemComparator > 0 ) break ; } tree . pageIndex = i ; return value ; }
Linear search inside the node
188
6
141,008
private V binarySearch ( final K iKey ) { int low = 0 ; int high = getSize ( ) - 1 ; int mid = 0 ; while ( low <= high ) { mid = ( low + high ) >>> 1 ; Object midVal = getKeyAt ( mid ) ; if ( tree . comparator != null ) tree . pageItemComparator = tree . comparator . compare ( ( K ) midVal , iKey ) ; else tree . pageItemComparator = ( ( Comparable < ? super K > ) midVal ) . compareTo ( iKey ) ; if ( tree . pageItemComparator == 0 ) { // FOUND: SET THE INDEX AND RETURN THE NODE tree . pageItemFound = true ; tree . pageIndex = mid ; return getValueAt ( tree . pageIndex ) ; } if ( low == high ) break ; if ( tree . pageItemComparator < 0 ) low = mid + 1 ; else high = mid ; } tree . pageIndex = mid ; return null ; }
Binary search inside the node
216
6
141,009
public int compareTo ( final OMVRBTreeEntry < K , V > o ) { if ( o == null ) return 1 ; if ( o == this ) return 0 ; if ( getSize ( ) == 0 ) return - 1 ; if ( o . getSize ( ) == 0 ) return 1 ; if ( tree . comparator != null ) return tree . comparator . compare ( getFirstKey ( ) , o . getFirstKey ( ) ) ; return ( ( Comparable < K > ) getFirstKey ( ) ) . compareTo ( o . getFirstKey ( ) ) ; }
Compares two nodes by their first keys .
125
9
141,010
public static long parsePeriod ( String periodStr ) { PeriodFormatter fmt = PeriodFormat . getDefault ( ) ; Period p = fmt . parsePeriod ( periodStr ) ; return p . toStandardDuration ( ) . getMillis ( ) ; }
Returns the period in msecs
54
6
141,011
public Date getEndDate ( Date startDate , long period ) { long now = getNow ( ) . getTime ( ) ; long endDate = startDate . getTime ( ) + period ; if ( now - period > endDate ) { return new Date ( endDate ) ; } else { return null ; } }
Returns the end date given the start date end the period . The end date is startDate + period but only if endDate is at least one period ago . That is we always leave the last incomplete period unprocessed .
67
45
141,012
protected List < MigrationJob > createJobs ( Date startDate , Date endDate , ActiveExecution ae ) throws Exception { List < MigrationJob > ret = new ArrayList < MigrationJob > ( ) ; LOGGER . debug ( "Creating the migrator to setup new jobs" ) ; // We setup a new migration job MigrationJob mj = new MigrationJob ( ) ; mj . setConfigurationName ( getMigrationConfiguration ( ) . getConfigurationName ( ) ) ; mj . setScheduledDate ( getNow ( ) ) ; mj . setGenerated ( true ) ; mj . setStatus ( MigrationJob . STATE_AVAILABLE ) ; mj . setConsistencyChecker ( new MigrationJob . ConsistencyChecker ( ) ) ; mj . getConsistencyChecker ( ) . setJobRangeBegin ( ClientConstants . getDateFormat ( ) . format ( startDate ) ) ; mj . getConsistencyChecker ( ) . setJobRangeEnd ( ClientConstants . getDateFormat ( ) . format ( endDate ) ) ; mj . getConsistencyChecker ( ) . setConfigurationName ( mj . getConfigurationName ( ) ) ; Migrator migrator = createMigrator ( mj , ae ) ; mj . setQuery ( migrator . createRangeQuery ( startDate , endDate ) ) ; // At this point, mj.query contains the range query LOGGER . debug ( "Migration job query:{}" , mj . getQuery ( ) ) ; ret . add ( mj ) ; return ret ; }
Create a migration job or jobs to process records created between the given dates . startDate is inclusive end date is exclusive
345
23
141,013
private OMMapBufferEntry [ ] searchAmongExisting ( OFileMMap file , final OMMapBufferEntry [ ] fileEntries , final long beginOffset , final int size ) { if ( fileEntries . length == 0 ) { return EMPTY_BUFFER_ENTRIES ; } final OMMapBufferEntry lastEntry = fileEntries [ fileEntries . length - 1 ] ; if ( lastEntry . beginOffset + lastEntry . size <= beginOffset ) { return EMPTY_BUFFER_ENTRIES ; } final LastMMapEntrySearchInfo entrySearchInfo = mapEntrySearchInfo . get ( file ) ; final int beginSearchPosition ; final int endSearchPosition ; if ( entrySearchInfo == null ) { beginSearchPosition = 0 ; endSearchPosition = fileEntries . length - 1 ; } else { if ( entrySearchInfo . requestedPosition <= beginOffset ) { beginSearchPosition = entrySearchInfo . foundMmapIndex ; endSearchPosition = fileEntries . length - 1 ; } else { beginSearchPosition = 0 ; endSearchPosition = entrySearchInfo . foundMmapIndex ; } } final int resultFirstPosition ; if ( endSearchPosition - beginSearchPosition > BINARY_SEARCH_THRESHOLD ) resultFirstPosition = binarySearch ( fileEntries , beginOffset , beginSearchPosition , endSearchPosition ) ; else resultFirstPosition = linearSearch ( fileEntries , beginOffset , beginSearchPosition , endSearchPosition ) ; if ( beginSearchPosition < 0 ) return EMPTY_BUFFER_ENTRIES ; int resultLastPosition = fileEntries . length - 1 ; for ( int i = resultFirstPosition ; i <= resultLastPosition ; i ++ ) { final OMMapBufferEntry entry = fileEntries [ i ] ; if ( entry . beginOffset + entry . size >= beginOffset + size ) { resultLastPosition = i ; break ; } } final int length = resultLastPosition - resultFirstPosition + 1 ; final OMMapBufferEntry [ ] foundEntries = new OMMapBufferEntry [ length ] ; if ( length > 0 ) { System . arraycopy ( fileEntries , resultFirstPosition , foundEntries , 0 , length ) ; mapEntrySearchInfo . put ( file , new LastMMapEntrySearchInfo ( resultFirstPosition , beginOffset ) ) ; } return foundEntries ; }
This method search in already mapped entries to find if necessary entry is already mapped and can be returned .
506
20
141,014
private OMMapBufferEntry mapNew ( final OFileMMap file , final long beginOffset ) throws IOException { return new OMMapBufferEntry ( file , file . map ( beginOffset , file . getFileSize ( ) - ( int ) beginOffset ) , beginOffset , file . getFileSize ( ) - ( int ) beginOffset ) ; }
This method maps new part of file if not all file content is mapped .
76
15
141,015
private void acquireLocksOnEntries ( final OMMapBufferEntry [ ] entries , OPERATION_TYPE operationType ) { if ( operationType == OPERATION_TYPE . WRITE ) for ( OMMapBufferEntry entry : entries ) { entry . acquireWriteLock ( ) ; entry . setDirty ( ) ; } else for ( OMMapBufferEntry entry : entries ) entry . acquireReadLock ( ) ; }
Locks all entries .
89
5
141,016
private void removeFileEntries ( OMMapBufferEntry [ ] fileEntries ) { if ( fileEntries != null ) { for ( OMMapBufferEntry entry : fileEntries ) { removeEntry ( entry ) ; } } }
Removes all files entries . Flush will be performed before removing .
51
14
141,017
public static String getRelativePath ( File file , File srcDir ) { String base = srcDir . getPath ( ) ; String filePath = file . getPath ( ) ; String relativePath = new File ( base ) . toURI ( ) . relativize ( new File ( filePath ) . toURI ( ) ) . getPath ( ) ; return relativePath ; }
Returns the relative path .
80
5
141,018
public static void copyFile ( File srcFile , File destFile ) { OutputStream out = null ; InputStream in = null ; try { if ( ! destFile . getParentFile ( ) . exists ( ) ) destFile . getParentFile ( ) . mkdirs ( ) ; in = new FileInputStream ( srcFile ) ; out = new FileOutputStream ( destFile ) ; // Transfer bytes from in to out byte [ ] buf = new byte [ 1024 ] ; int len ; while ( ( len = in . read ( buf ) ) > 0 ) { out . write ( buf , 0 , len ) ; } in . close ( ) ; out . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Copy a file to new destination .
161
7
141,019
public static ContextLoaderListener createSpringContextLoader ( final WebApplicationContext webApplicationContext ) { return new ContextLoaderListener ( ) { @ SuppressWarnings ( "unchecked" ) @ Override protected WebApplicationContext createWebApplicationContext ( ServletContext sc ) { return webApplicationContext ; } } ; }
Creates a spring context loader listener
66
7
141,020
public static JsonNode getFieldValue ( JsonNode doc , String field ) { StringTokenizer tkz = new StringTokenizer ( field , ". " ) ; JsonNode trc = doc ; while ( tkz . hasMoreTokens ( ) && trc != null ) { String tok = tkz . nextToken ( ) ; trc = trc . get ( tok ) ; } return trc ; }
Ooes not do array index lookup!
93
8
141,021
public OPhysicalPosition getPhysicalPosition ( final OPhysicalPosition iPPosition ) throws IOException { final long filePosition = iPPosition . clusterPosition * RECORD_SIZE ; acquireSharedLock ( ) ; try { final long [ ] pos = fileSegment . getRelativePosition ( filePosition ) ; final OFile f = fileSegment . files [ ( int ) pos [ 0 ] ] ; long p = pos [ 1 ] ; iPPosition . dataSegmentId = f . readShort ( p ) ; iPPosition . dataSegmentPos = f . readLong ( p += OBinaryProtocol . SIZE_SHORT ) ; iPPosition . recordType = f . readByte ( p += OBinaryProtocol . SIZE_LONG ) ; iPPosition . recordVersion = f . readInt ( p += OBinaryProtocol . SIZE_BYTE ) ; return iPPosition ; } finally { releaseSharedLock ( ) ; } }
Fills and return the PhysicalPosition object received as parameter with the physical position of logical record iPosition
200
20
141,022
public void removePhysicalPosition ( final long iPosition ) throws IOException { final long position = iPosition * RECORD_SIZE ; acquireExclusiveLock ( ) ; try { final long [ ] pos = fileSegment . getRelativePosition ( position ) ; final OFile file = fileSegment . files [ ( int ) pos [ 0 ] ] ; final long p = pos [ 1 ] + OBinaryProtocol . SIZE_SHORT + OBinaryProtocol . SIZE_LONG + OBinaryProtocol . SIZE_BYTE ; holeSegment . pushPosition ( position ) ; // MARK DELETED SETTING VERSION TO NEGATIVE NUMBER final int version = file . readInt ( p ) ; file . writeInt ( p , ( version + 1 ) * - 1 ) ; updateBoundsAfterDeletion ( iPosition ) ; } finally { releaseExclusiveLock ( ) ; } }
Removes the Logical position entry . Add to the hole segment and add the minus to the version .
194
21
141,023
public void addPhysicalPosition ( final OPhysicalPosition iPPosition ) throws IOException { final long [ ] pos ; final boolean recycled ; long offset ; acquireExclusiveLock ( ) ; try { offset = holeSegment . popLastEntryPosition ( ) ; if ( offset > - 1 ) { // REUSE THE HOLE pos = fileSegment . getRelativePosition ( offset ) ; recycled = true ; } else { // NO HOLES FOUND: ALLOCATE MORE SPACE pos = allocateRecord ( ) ; offset = fileSegment . getAbsolutePosition ( pos ) ; recycled = false ; } final OFile file = fileSegment . files [ ( int ) pos [ 0 ] ] ; long p = pos [ 1 ] ; file . writeShort ( p , ( short ) iPPosition . dataSegmentId ) ; file . writeLong ( p += OBinaryProtocol . SIZE_SHORT , iPPosition . dataSegmentPos ) ; file . writeByte ( p += OBinaryProtocol . SIZE_LONG , iPPosition . recordType ) ; if ( recycled ) // GET LAST VERSION iPPosition . recordVersion = file . readInt ( p + OBinaryProtocol . SIZE_BYTE ) * - 1 ; else iPPosition . recordVersion = 0 ; file . writeInt ( p + OBinaryProtocol . SIZE_BYTE , iPPosition . recordVersion ) ; iPPosition . clusterPosition = offset / RECORD_SIZE ; updateBoundsAfterInsertion ( iPPosition . clusterPosition ) ; } finally { releaseExclusiveLock ( ) ; } }
Adds a new entry .
334
5
141,024
private void setDataSegmentInternal ( final String iName ) { final int dataId = storage . getDataSegmentIdByName ( iName ) ; config . setDataSegmentId ( dataId ) ; storage . getConfiguration ( ) . update ( ) ; }
Assigns a different data - segment id .
57
10
141,025
protected Object getCustomEventLoggerFromRegistry ( MuleContext muleContext ) { Object obj = muleContext . getRegistry ( ) . lookupObject ( CUSTOM_EVENT_LOGGER_BEAN_NAME ) ; return obj ; }
open up for testing without a live MuleContext
55
10
141,026
public void addIndex ( final OIndexDefinition indexDefinition ) { indexDefinitions . add ( indexDefinition ) ; if ( indexDefinition instanceof OIndexDefinitionMultiValue ) { if ( multiValueDefinitionIndex == - 1 ) multiValueDefinitionIndex = indexDefinitions . size ( ) - 1 ; else throw new OIndexException ( "Composite key can not contain more than one collection item" ) ; } }
Add new indexDefinition in current composite .
86
8
141,027
public OIdentifiableIterator < REC > setReuseSameRecord ( final boolean reuseSameRecord ) { reusedRecord = ( ORecordInternal < ? > ) ( reuseSameRecord ? database . newInstance ( ) : null ) ; return this ; }
Tell to the iterator to use the same record for browsing . The record will be reset before every use . This improve the performance and reduce memory utilization since it does not create a new one for each operation but pay attention to copy the data of the record once read otherwise they will be reset to the next operation .
52
62
141,028
protected ORecordInternal < ? > getRecord ( ) { final ORecordInternal < ? > record ; if ( reusedRecord != null ) { // REUSE THE SAME RECORD AFTER HAVING RESETTED IT record = reusedRecord ; record . reset ( ) ; } else record = null ; return record ; }
Return the record to use for the operation .
68
9
141,029
protected ORecordInternal < ? > readCurrentRecord ( ORecordInternal < ? > iRecord , final int iMovement ) { if ( limit > - 1 && browsedRecords >= limit ) // LIMIT REACHED return null ; current . clusterPosition += iMovement ; if ( iRecord != null ) { iRecord . setIdentity ( current ) ; iRecord = lowLevelDatabase . load ( iRecord , fetchPlan ) ; } else iRecord = lowLevelDatabase . load ( current , fetchPlan ) ; if ( iRecord != null ) browsedRecords ++ ; return iRecord ; }
Read the current record and increment the counter if the record was found .
130
14
141,030
public void bindParameters ( final Map < Object , Object > iArgs ) { if ( parameterItems == null || iArgs == null || iArgs . size ( ) == 0 ) return ; for ( Entry < Object , Object > entry : iArgs . entrySet ( ) ) { if ( entry . getKey ( ) instanceof Integer ) parameterItems . get ( ( ( Integer ) entry . getKey ( ) ) ) . setValue ( entry . setValue ( entry . getValue ( ) ) ) ; else { String paramName = entry . getKey ( ) . toString ( ) ; for ( OSQLFilterItemParameter value : parameterItems ) { if ( value . getName ( ) . equalsIgnoreCase ( paramName ) ) { value . setValue ( entry . getValue ( ) ) ; break ; } } } } }
Binds parameters .
175
4
141,031
@ Override public boolean send ( Context context , Report report ) { if ( url != null ) { String reportStr = report . asJSON ( ) . toString ( ) ; try { postReport ( url , reportStr ) ; return true ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } return false ; }
If the reporter was configured correctly post the report to the set URL .
74
14
141,032
public static void post ( URL url , String params ) throws IOException { URLConnection conn = url . openConnection ( ) ; if ( conn instanceof HttpURLConnection ) { ( ( HttpURLConnection ) conn ) . setRequestMethod ( "POST" ) ; conn . setRequestProperty ( "Content-Type" , "application/json" ) ; } OutputStreamWriter writer = null ; try { conn . setDoOutput ( true ) ; writer = new OutputStreamWriter ( conn . getOutputStream ( ) , Charset . forName ( "UTF-8" ) ) ; // write parameters writer . write ( params ) ; writer . flush ( ) ; } finally { if ( writer != null ) { writer . close ( ) ; } } }
Executes the given request as a HTTP POST action .
159
11
141,033
public static String read ( InputStream in ) throws IOException { InputStreamReader isReader = new InputStreamReader ( in , "UTF-8" ) ; BufferedReader reader = new BufferedReader ( isReader ) ; StringBuffer out = new StringBuffer ( ) ; char [ ] c = new char [ 4096 ] ; for ( int n ; ( n = reader . read ( c ) ) != - 1 ; ) { out . append ( new String ( c , 0 , n ) ) ; } reader . close ( ) ; return out . toString ( ) ; }
Reads an input stream and returns the result as a String .
120
13
141,034
public Object joinGame ( long id , String password ) { return client . sendRpcAndWait ( SERVICE , "joinGame" , id , password ) ; }
Join a password - protected game .
34
7
141,035
public Object observeGame ( long id , String password ) { return client . sendRpcAndWait ( SERVICE , "observeGame" , id , password ) ; }
Join a password - protected game as a spectator
36
9
141,036
public boolean switchToPlayer ( long id , PlayerSide team ) { return client . sendRpcAndWait ( SERVICE , "switchObserverToPlayer" , id , team . id ) ; }
Switch from observer to player
41
5
141,037
protected byte [ ] serializeStreamValue ( final int iIndex ) throws IOException { if ( serializedValues [ iIndex ] <= 0 ) { // NEW OR MODIFIED: MARSHALL CONTENT OProfiler . getInstance ( ) . updateCounter ( "OMVRBTreeMapEntry.serializeValue" , 1 ) ; return ( ( OMVRBTreeMapProvider < K , V > ) treeDataProvider ) . valueSerializer . toStream ( values [ iIndex ] ) ; } // RETURN ORIGINAL CONTENT return stream . getAsByteArray ( serializedValues [ iIndex ] ) ; }
Serialize only the new values or the changed .
130
10
141,038
public MigrationJob [ ] retrieveJobs ( int batchSize , int startIndex , JobType jobType ) throws IOException , LightblueException { LOGGER . debug ( "Retrieving jobs: batchSize={}, startIndex={}" , batchSize , startIndex ) ; DataFindRequest findRequest = new DataFindRequest ( "migrationJob" , null ) ; List < Query > conditions = new ArrayList <> ( Arrays . asList ( new Query [ ] { // get jobs for this configuration Query . withValue ( "configurationName" , Query . eq , migrationConfiguration . getConfigurationName ( ) ) , // get jobs whose state ara available Query . withValue ( "status" , Query . eq , "available" ) , // only get jobs that are Query . withValue ( "scheduledDate" , Query . lte , new Date ( ) ) } ) ) ; if ( jobType == JobType . GENERATED ) { LOGGER . debug ( "Looking for generated job" ) ; conditions . add ( Query . withValue ( "generated" , Query . eq , true ) ) ; } else if ( jobType == JobType . NONGENERATED ) { LOGGER . debug ( "Looking for non generated job" ) ; conditions . add ( Query . withValue ( "generated" , Query . eq , false ) ) ; } findRequest . where ( Query . and ( conditions ) ) ; findRequest . select ( Projection . includeField ( "*" ) ) ; findRequest . range ( startIndex , startIndex + batchSize - 1 ) ; LOGGER . debug ( "Finding Jobs to execute: {}" , findRequest . getBody ( ) ) ; return lbClient . data ( findRequest , MigrationJob [ ] . class ) ; }
Retrieves jobs that are available and their scheduled time has passed . Returns at most batchSize jobs starting at startIndex
376
24
141,039
public ActiveExecution lock ( String id ) throws Exception { LOGGER . debug ( "locking {}" , id ) ; if ( ! myLocks . contains ( id ) ) { if ( locking . acquire ( id , null ) ) { myLocks . add ( id ) ; ActiveExecution ae = new ActiveExecution ( ) ; ae . setMigrationJobId ( id ) ; ae . set_id ( id ) ; ae . setStartTime ( new Date ( ) ) ; return ae ; } } return null ; }
Attempts to lock a migration job . If successful return the migration job and the active execution
117
17
141,040
public < H extends EventHandler > H getHandler ( GwtEvent . Type < H > type , int index ) { return this . eventBus . superGetHandler ( type , index ) ; }
Gets the handler at the given index .
41
9
141,041
public < H extends EventHandler > void removeHandler ( GwtEvent . Type < H > type , final H handler ) { this . eventBus . superDoRemove ( type , null , handler ) ; }
Removes the given handler from the specified event type .
43
11
141,042
@ Override public void sendFailure ( String message ) { System . out . print ( "Warning: " + message ) ; System . exit ( 1 ) ; }
logs message with status code 1 - warn
34
9
141,043
@ Override public void sendError ( String message ) { System . out . print ( "Critical: " + message ) ; System . exit ( 2 ) ; }
logs message with status code 2 - critical
34
9
141,044
public Object execute ( final Map < Object , Object > iArgs ) { if ( className == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseRecord database = getDatabase ( ) ; if ( database . getMetadata ( ) . getSchema ( ) . existsClass ( className ) ) throw new OCommandExecutionException ( "Class " + className + " already exists" ) ; final OClassImpl sourceClass = ( OClassImpl ) ( ( OSchemaProxy ) database . getMetadata ( ) . getSchema ( ) ) . createClassInternal ( className , superClass , clusterIds ) ; sourceClass . saveInternal ( ) ; if ( superClass != null ) { int [ ] clustersToIndex = superClass . getPolymorphicClusterIds ( ) ; String [ ] clusterNames = new String [ clustersToIndex . length ] ; for ( int i = 0 ; i < clustersToIndex . length ; i ++ ) { clusterNames [ i ] = database . getClusterNameById ( clustersToIndex [ i ] ) ; } for ( OIndex < ? > index : superClass . getIndexes ( ) ) for ( String clusterName : clusterNames ) index . getInternal ( ) . addCluster ( clusterName ) ; } return database . getMetadata ( ) . getSchema ( ) . getClasses ( ) . size ( ) ; }
Execute the CREATE CLASS .
314
7
141,045
public boolean callbackHooks ( final TYPE iType , final OIdentifiable id ) { if ( ! OHookThreadLocal . INSTANCE . push ( id ) ) return false ; try { final ORecord < ? > rec = id . getRecord ( ) ; if ( rec == null ) return false ; boolean recordChanged = false ; for ( ORecordHook hook : hooks ) if ( hook . onTrigger ( iType , rec ) ) recordChanged = true ; return recordChanged ; } finally { OHookThreadLocal . INSTANCE . pop ( id ) ; } }
Callback the registeted hooks if any .
121
9
141,046
public String execute ( String url , String urlParameters , String clientId , String secret , String method ) throws Exception { HttpURLConnection connection ; String credentials = clientId + ":" + secret ; String authorizationHeader = "Basic " + Base64 . getEncoder ( ) . encodeToString ( credentials . getBytes ( ) ) ; if ( "POST" . equalsIgnoreCase ( method ) ) { connection = ( HttpURLConnection ) new URL ( url ) . openConnection ( ) ; connection . setRequestMethod ( method ) ; connection . setRequestProperty ( "Content-Type" , "application/x-www-form-urlencoded" ) ; connection . setRequestProperty ( "Authorization" , authorizationHeader ) ; connection . setDoInput ( true ) ; connection . setDoOutput ( true ) ; if ( null != urlParameters ) { try ( PrintWriter out = new PrintWriter ( connection . getOutputStream ( ) ) ) { out . print ( urlParameters ) ; } } } else { connection = ( HttpURLConnection ) new URL ( url + "?" + urlParameters ) . openConnection ( ) ; connection . setRequestMethod ( method ) ; connection . setRequestProperty ( "Authorization" , authorizationHeader ) ; } int timeout = Integer . parseInt ( System . getProperty ( "org.hawkular.accounts.http.timeout" , "5000" ) ) ; connection . setConnectTimeout ( timeout ) ; connection . setReadTimeout ( timeout ) ; StringBuilder response = new StringBuilder ( ) ; int statusCode ; try { statusCode = connection . getResponseCode ( ) ; } catch ( SocketTimeoutException timeoutException ) { throw new UsernamePasswordConversionException ( "Timed out when trying to contact the Keycloak server." ) ; } InputStream inputStream ; if ( statusCode < 300 ) { inputStream = connection . getInputStream ( ) ; } else { inputStream = connection . getErrorStream ( ) ; } try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream , "UTF-8" ) ) ) { for ( String line ; ( line = reader . readLine ( ) ) != null ; ) { response . append ( line ) ; } } return response . toString ( ) ; }
Performs an HTTP call to the Keycloak server returning the server s response as String .
483
19
141,047
private void buildReport ( Context context ) { try { buildBaseReport ( ) ; buildApplicationData ( context ) ; buildDeviceData ( context ) ; buildLog ( ) ; report . put ( "application" , app ) ; report . put ( "device" , device ) ; report . put ( "log" , logs ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; } }
Creates the report as a JSON Object .
88
9
141,048
private void buildLog ( ) throws JSONException { logs = new JSONObject ( ) ; List < String > list = Log . getReportedEntries ( ) ; if ( list != null ) { logs . put ( "numberOfEntry" , list . size ( ) ) ; JSONArray array = new JSONArray ( ) ; for ( String s : list ) { array . put ( s ) ; } logs . put ( "log" , array ) ; } }
Adds the log entries to the report .
97
8
141,049
private void buildDeviceData ( Context context ) throws JSONException { device = new JSONObject ( ) ; device . put ( "device" , Build . DEVICE ) ; device . put ( "brand" , Build . BRAND ) ; Object windowService = context . getSystemService ( Context . WINDOW_SERVICE ) ; if ( windowService instanceof WindowManager ) { Display display = ( ( WindowManager ) windowService ) . getDefaultDisplay ( ) ; device . put ( "resolution" , display . getWidth ( ) + "x" + display . getHeight ( ) ) ; device . put ( "orientation" , display . getOrientation ( ) ) ; } device . put ( "display" , Build . DISPLAY ) ; device . put ( "manufacturer" , Build . MANUFACTURER ) ; device . put ( "model" , Build . MODEL ) ; device . put ( "product" , Build . PRODUCT ) ; device . put ( "build.type" , Build . TYPE ) ; device . put ( "android.version" , Build . VERSION . SDK_INT ) ; }
Adds the device data to the report .
239
8
141,050
private void buildApplicationData ( Context context ) throws JSONException { app = new JSONObject ( ) ; app . put ( "package" , context . getPackageName ( ) ) ; try { PackageInfo info = context . getPackageManager ( ) . getPackageInfo ( context . getPackageName ( ) , 0 ) ; app . put ( "versionCode" , info . versionCode ) ; app . put ( "versionName" , info . versionName ) ; // TODO firstInstallTime and lastUpdate } catch ( NameNotFoundException e ) { // Cannot happen as we're checking a know package. } }
Adds the application data to the report .
129
8
141,051
public Set < ODocument > getEdgesBetweenVertexes ( final ODocument iVertex1 , final ODocument iVertex2 ) { return getEdgesBetweenVertexes ( iVertex1 , iVertex2 , null , null ) ; }
Returns all the edges between the vertexes iVertex1 and iVertex2 .
56
18
141,052
public Set < ODocument > getEdgesBetweenVertexes ( final ODocument iVertex1 , final ODocument iVertex2 , final String [ ] iLabels ) { return getEdgesBetweenVertexes ( iVertex1 , iVertex2 , iLabels , null ) ; }
Returns all the edges between the vertexes iVertex1 and iVertex2 with label between the array of labels passed as iLabels .
66
30
141,053
public Set < ODocument > getEdgesBetweenVertexes ( final ODocument iVertex1 , final ODocument iVertex2 , final String [ ] iLabels , final String [ ] iClassNames ) { final Set < ODocument > result = new HashSet < ODocument > ( ) ; if ( iVertex1 != null && iVertex2 != null ) { // CHECK OUT EDGES for ( OIdentifiable e : getOutEdges ( iVertex1 ) ) { final ODocument edge = ( ODocument ) e ; if ( checkEdge ( edge , iLabels , iClassNames ) ) { if ( edge . < ODocument > field ( "in" ) . equals ( iVertex2 ) ) result . add ( edge ) ; } } // CHECK IN EDGES for ( OIdentifiable e : getInEdges ( iVertex1 ) ) { final ODocument edge = ( ODocument ) e ; if ( checkEdge ( edge , iLabels , iClassNames ) ) { if ( edge . < ODocument > field ( "out" ) . equals ( iVertex2 ) ) result . add ( edge ) ; } } } return result ; }
Returns all the edges between the vertexes iVertex1 and iVertex2 with label between the array of labels passed as iLabels and with class between the array of class names passed as iClassNames .
257
44
141,054
public Set < OIdentifiable > getOutEdgesHavingProperties ( final OIdentifiable iVertex , Iterable < String > iProperties ) { final ODocument vertex = iVertex . getRecord ( ) ; checkVertexClass ( vertex ) ; return filterEdgesByProperties ( ( OMVRBTreeRIDSet ) vertex . field ( VERTEX_FIELD_OUT ) , iProperties ) ; }
Retrieves the outgoing edges of vertex iVertex having the requested properties iProperties
91
18
141,055
public Set < OIdentifiable > getInEdgesHavingProperties ( final OIdentifiable iVertex , Iterable < String > iProperties ) { final ODocument vertex = iVertex . getRecord ( ) ; checkVertexClass ( vertex ) ; return filterEdgesByProperties ( ( OMVRBTreeRIDSet ) vertex . field ( VERTEX_FIELD_IN ) , iProperties ) ; }
Retrieves the incoming edges of vertex iVertex having the requested properties iProperties
91
18
141,056
public Set < OIdentifiable > getInEdgesHavingProperties ( final ODocument iVertex , final Map < String , Object > iProperties ) { checkVertexClass ( iVertex ) ; return filterEdgesByProperties ( ( OMVRBTreeRIDSet ) iVertex . field ( VERTEX_FIELD_IN ) , iProperties ) ; }
Retrieves the incoming edges of vertex iVertex having the requested properties iProperties set to the passed values
82
23
141,057
public synchronized OServerAdmin connect ( final String iUserName , final String iUserPassword ) throws IOException { storage . createConnectionPool ( ) ; storage . setSessionId ( - 1 ) ; try { final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_CONNECT ) ; storage . sendClientInfo ( network ) ; try { network . writeString ( iUserName ) ; network . writeString ( iUserPassword ) ; } finally { storage . endRequest ( network ) ; } try { storage . beginResponse ( network ) ; sessionId = network . readInt ( ) ; storage . setSessionId ( sessionId ) ; } finally { storage . endResponse ( network ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Cannot connect to the remote server: " + storage . getName ( ) , e , OStorageException . class ) ; storage . close ( true ) ; } return this ; }
Connects to a remote server .
213
7
141,058
@ SuppressWarnings ( "unchecked" ) public synchronized Map < String , String > listDatabases ( ) throws IOException { storage . checkConnection ( ) ; final ODocument result = new ODocument ( ) ; try { final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_DB_LIST ) ; storage . endRequest ( network ) ; try { storage . beginResponse ( network ) ; result . fromStream ( network . readBytes ( ) ) ; } finally { storage . endResponse ( network ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . exception ( "Cannot retrieve the configuration list" , e , OStorageException . class ) ; storage . close ( true ) ; } return ( Map < String , String > ) result . field ( "databases" ) ; }
List the databases on a remote server .
183
8
141,059
public synchronized OServerAdmin createDatabase ( final String iDatabaseType , String iStorageMode ) throws IOException { storage . checkConnection ( ) ; try { if ( storage . getName ( ) == null || storage . getName ( ) . length ( ) <= 0 ) { OLogManager . instance ( ) . error ( this , "Cannot create unnamed remote storage. Check your syntax" , OStorageException . class ) ; } else { if ( iStorageMode == null ) iStorageMode = "csv" ; final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_DB_CREATE ) ; try { network . writeString ( storage . getName ( ) ) ; if ( network . getSrvProtocolVersion ( ) >= 8 ) network . writeString ( iDatabaseType ) ; network . writeString ( iStorageMode ) ; } finally { storage . endRequest ( network ) ; } storage . getResponse ( network ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . error ( this , "Cannot create the remote storage: " + storage . getName ( ) , e , OStorageException . class ) ; storage . close ( true ) ; } return this ; }
Creates a database in a remote server .
266
9
141,060
public synchronized boolean existsDatabase ( ) throws IOException { storage . checkConnection ( ) ; try { final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_DB_EXIST ) ; try { network . writeString ( storage . getName ( ) ) ; } finally { storage . endRequest ( network ) ; } try { storage . beginResponse ( network ) ; return network . readByte ( ) == 1 ; } finally { storage . endResponse ( network ) ; } } catch ( Exception e ) { OLogManager . instance ( ) . exception ( "Error on checking existence of the remote storage: " + storage . getName ( ) , e , OStorageException . class ) ; storage . close ( true ) ; } return false ; }
Checks if a database exists in the remote server .
165
11
141,061
public synchronized OServerAdmin dropDatabase ( ) throws IOException { storage . checkConnection ( ) ; boolean retry = true ; while ( retry ) try { final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_DB_DROP ) ; try { network . writeString ( storage . getName ( ) ) ; } finally { storage . endRequest ( network ) ; } storage . getResponse ( network ) ; retry = false ; } catch ( OModificationOperationProhibitedException oope ) { retry = handleDBFreeze ( ) ; } catch ( Exception e ) { OLogManager . instance ( ) . exception ( "Cannot delete the remote storage: " + storage . getName ( ) , e , OStorageException . class ) ; } for ( OStorage s : Orient . instance ( ) . getStorages ( ) ) { if ( s . getURL ( ) . startsWith ( getURL ( ) ) ) { s . removeResource ( OSchema . class . getSimpleName ( ) ) ; s . removeResource ( OIndexManager . class . getSimpleName ( ) ) ; s . removeResource ( OSecurity . class . getSimpleName ( ) ) ; } } ODatabaseRecordThreadLocal . INSTANCE . set ( null ) ; return this ; }
Drops a database from a remote server instance .
282
10
141,062
public ODocument clusterStatus ( ) { final ODocument response = sendRequest ( OChannelBinaryProtocol . REQUEST_CLUSTER , new ODocument ( ) . field ( "operation" , "status" ) , "Cluster status" ) ; OLogManager . instance ( ) . debug ( this , "Cluster status %s" , response . toJSON ( ) ) ; return response ; }
Gets the cluster status .
86
6
141,063
public synchronized OServerAdmin replicationStop ( final String iDatabaseName , final String iRemoteServer ) throws IOException { sendRequest ( OChannelBinaryProtocol . REQUEST_REPLICATION , new ODocument ( ) . field ( "operation" , "stop" ) . field ( "node" , iRemoteServer ) . field ( "db" , iDatabaseName ) , "Stop replication" ) ; OLogManager . instance ( ) . debug ( this , "Stopped replication of database '%s' from server '%s' to '%s'" , iDatabaseName , storage . getURL ( ) , iRemoteServer ) ; return this ; }
Stops the replication between two servers .
140
8
141,064
public synchronized ODocument getReplicationJournal ( final String iDatabaseName , final String iRemoteServer ) throws IOException { OLogManager . instance ( ) . debug ( this , "Retrieving the replication log for database '%s' from server '%s'..." , iDatabaseName , storage . getURL ( ) ) ; final ODocument response = sendRequest ( OChannelBinaryProtocol . REQUEST_REPLICATION , new ODocument ( ) . field ( "operation" , "getJournal" ) . field ( "node" , iRemoteServer ) . field ( "db" , iDatabaseName ) , "Retrieve replication log" ) ; OLogManager . instance ( ) . debug ( this , "Returned %d replication log entries for the database '%s' from server '%s' against server '%s'" , response . fields ( ) , iDatabaseName , storage . getURL ( ) , iRemoteServer ) ; return response ; }
Gets the replication journal for a database .
205
9
141,065
public OServerAdmin replicationAlign ( final String iDatabaseName , final String iRemoteServer , final String iOptions ) { OLogManager . instance ( ) . debug ( this , "Started the alignment of database '%s' from server '%s' to '%s' with options %s" , iDatabaseName , storage . getURL ( ) , iRemoteServer , iOptions ) ; sendRequest ( OChannelBinaryProtocol . REQUEST_REPLICATION , new ODocument ( ) . field ( "operation" , "align" ) . field ( "node" , iRemoteServer ) . field ( "db" , iDatabaseName ) . field ( "options" , iOptions ) , "Align databases" ) ; OLogManager . instance ( ) . debug ( this , "Alignment finished" ) ; return this ; }
Aligns a database between two servers
181
8
141,066
public synchronized OServerAdmin copyDatabase ( final String iDatabaseName , final String iDatabaseUserName , final String iDatabaseUserPassword , final String iRemoteName , final String iRemoteEngine ) throws IOException { storage . checkConnection ( ) ; try { final OChannelBinaryClient network = storage . beginRequest ( OChannelBinaryProtocol . REQUEST_DB_COPY ) ; try { network . writeString ( iDatabaseName ) ; network . writeString ( iDatabaseUserName ) ; network . writeString ( iDatabaseUserPassword ) ; network . writeString ( iRemoteName ) ; network . writeString ( iRemoteEngine ) ; } finally { storage . endRequest ( network ) ; } storage . getResponse ( network ) ; OLogManager . instance ( ) . debug ( this , "Database '%s' has been copied to the server '%s'" , iDatabaseName , iRemoteName ) ; } catch ( Exception e ) { OLogManager . instance ( ) . exception ( "Cannot copy the database: " + iDatabaseName , e , OStorageException . class ) ; } return this ; }
Copies a database to a remote server instance .
239
10
141,067
public Object execute ( final OIdentifiable o , final OCommandExecutor iRequester ) { // RESOLVE VALUES USING THE CURRENT RECORD for ( int i = 0 ; i < configuredParameters . length ; ++ i ) { if ( configuredParameters [ i ] instanceof OSQLFilterItemField ) runtimeParameters [ i ] = ( ( OSQLFilterItemField ) configuredParameters [ i ] ) . getValue ( o , null ) ; else if ( configuredParameters [ i ] instanceof OSQLFunctionRuntime ) runtimeParameters [ i ] = ( ( OSQLFunctionRuntime ) configuredParameters [ i ] ) . execute ( o , iRequester ) ; } final Object functionResult = function . execute ( o , runtimeParameters , iRequester ) ; return transformValue ( o , functionResult ) ; }
Execute a function .
170
5
141,068
public static EmbeddedJettyBuilder . ServletContextHandlerBuilder addWicketHandler ( EmbeddedJettyBuilder embeddedJettyBuilder , String contextPath , EventListener springContextloader , Class < ? extends WebApplication > wicketApplication , boolean development ) { EmbeddedJettyBuilder . ServletContextHandlerBuilder wicketHandler = embeddedJettyBuilder . createRootServletContextHandler ( contextPath ) . setClassLoader ( Thread . currentThread ( ) . getContextClassLoader ( ) ) . addEventListener ( springContextloader ) ; return addWicketHandler ( wicketHandler , wicketApplication , development ) ; }
Adds wicket handler at root context .
130
8
141,069
public boolean add ( final OIdentifiable e ) { if ( e . getIdentity ( ) . isNew ( ) ) { final ORecord < ? > record = e . getRecord ( ) ; // ADD IN TEMP LIST if ( newItems == null ) newItems = new IdentityHashMap < ORecord < ? > , Object > ( ) ; else if ( newItems . containsKey ( record ) ) return false ; newItems . put ( record , NEWMAP_VALUE ) ; setDirty ( ) ; return true ; } else if ( OGlobalConfiguration . LAZYSET_WORK_ON_STREAM . getValueAsBoolean ( ) && getStreamedContent ( ) != null ) { // FAST INSERT final String ridString = e . getIdentity ( ) . toString ( ) ; final StringBuilder buffer = getStreamedContent ( ) ; if ( buffer . indexOf ( ridString ) < 0 ) { if ( buffer . length ( ) > 0 ) buffer . append ( ' ' ) ; e . getIdentity ( ) . toString ( buffer ) ; setDirty ( ) ; return true ; } return false ; } else { final int pos = indexOf ( e ) ; if ( pos < 0 ) { // FOUND delegate . add ( pos * - 1 - 1 , e ) ; return true ; } return false ; } }
Adds the item in the underlying List preserving the order of the collection .
291
14
141,070
public int indexOf ( final OIdentifiable iElement ) { if ( delegate . isEmpty ( ) ) return - 1 ; final boolean prevConvert = delegate . isAutoConvertToRecord ( ) ; if ( prevConvert ) delegate . setAutoConvertToRecord ( false ) ; final int pos = Collections . binarySearch ( delegate , iElement ) ; if ( prevConvert ) // RESET PREVIOUS SETTINGS delegate . setAutoConvertToRecord ( true ) ; return pos ; }
Returns the position of the element in the set . Execute a binary search since the elements are always ordered .
107
22
141,071
public ORDER compare ( OQueryOperator other ) { final Class < ? > thisClass = this . getClass ( ) ; final Class < ? > otherClass = other . getClass ( ) ; int thisPosition = - 1 ; int otherPosition = - 1 ; for ( int i = 0 ; i < DEFAULT_OPERATORS_ORDER . length ; i ++ ) { // subclass of default operators inherit their parent ordering final Class < ? > clazz = DEFAULT_OPERATORS_ORDER [ i ] ; if ( clazz . isAssignableFrom ( thisClass ) ) { thisPosition = i ; } if ( clazz . isAssignableFrom ( otherClass ) ) { otherPosition = i ; } } if ( thisPosition == - 1 || otherPosition == - 1 ) { // can not decide which comes first return ORDER . UNKNOWNED ; } if ( thisPosition > otherPosition ) { return ORDER . AFTER ; } else if ( thisPosition < otherPosition ) { return ORDER . BEFORE ; } return ORDER . EQUAL ; }
Check priority of this operator compare to given operator .
223
10
141,072
public Object execute ( final Map < Object , Object > iArgs ) { if ( attribute == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; final ODatabaseRecord database = getDatabase ( ) ; database . checkSecurity ( ODatabaseSecurityResources . DATABASE , ORole . PERMISSION_UPDATE ) ; ( ( ODatabaseComplex < ? > ) database ) . setInternal ( attribute , value ) ; return null ; }
Execute the ALTER DATABASE .
106
10
141,073
@ Override public boolean open ( ) throws IOException { lock . acquireExclusiveLock ( ) ; try { // IGNORE IF IT'S SOFTLY CLOSED super . open ( ) ; // CHECK FOR PENDING TRANSACTION ENTRIES TO RECOVER recoverTransactions ( ) ; return true ; } finally { lock . releaseExclusiveLock ( ) ; } }
Opens the file segment and recovers pending transactions if any
79
11
141,074
public void addLog ( final byte iOperation , final int iTxId , final int iClusterId , final long iClusterOffset , final byte iRecordType , final int iRecordVersion , final byte [ ] iRecordContent , int dataSegmentId ) throws IOException { final int contentSize = iRecordContent != null ? iRecordContent . length : 0 ; final int size = OFFSET_RECORD_CONTENT + contentSize ; lock . acquireExclusiveLock ( ) ; try { int offset = file . allocateSpace ( size ) ; file . writeByte ( offset , STATUS_COMMITTING ) ; offset += OBinaryProtocol . SIZE_BYTE ; file . writeByte ( offset , iOperation ) ; offset += OBinaryProtocol . SIZE_BYTE ; file . writeInt ( offset , iTxId ) ; offset += OBinaryProtocol . SIZE_INT ; file . writeShort ( offset , ( short ) iClusterId ) ; offset += OBinaryProtocol . SIZE_SHORT ; file . writeLong ( offset , iClusterOffset ) ; offset += OBinaryProtocol . SIZE_LONG ; file . writeByte ( offset , iRecordType ) ; offset += OBinaryProtocol . SIZE_BYTE ; file . writeInt ( offset , iRecordVersion ) ; offset += OBinaryProtocol . SIZE_INT ; file . writeInt ( offset , dataSegmentId ) ; offset += OBinaryProtocol . SIZE_INT ; file . writeInt ( offset , contentSize ) ; offset += OBinaryProtocol . SIZE_INT ; file . write ( offset , iRecordContent ) ; offset += contentSize ; if ( synchEnabled ) file . synch ( ) ; } finally { lock . releaseExclusiveLock ( ) ; } }
Appends a log entry
390
5
141,075
private Set < Integer > scanForTransactionsToRecover ( ) throws IOException { // SCAN ALL THE FILE SEARCHING FOR THE TRANSACTIONS TO RECOVER final Set < Integer > txToRecover = new HashSet < Integer > ( ) ; final Set < Integer > txToNotRecover = new HashSet < Integer > ( ) ; // BROWSE ALL THE ENTRIES for ( long offset = 0 ; eof ( offset ) ; offset = nextEntry ( offset ) ) { // READ STATUS final byte status = file . readByte ( offset ) ; // READ TX-ID final int txId = file . readInt ( offset + OFFSET_TX_ID ) ; switch ( status ) { case STATUS_FREE : // NOT RECOVER IT SINCE IF FIND AT LEAST ONE "FREE" STATUS MEANS THAT ALL THE LOGS WAS COMMITTED BUT THE USER DIDN'T // RECEIVED THE ACK txToNotRecover . add ( txId ) ; break ; case STATUS_COMMITTING : // TO RECOVER UNLESS THE REQ/TX IS IN THE MAP txToNotRecover txToRecover . add ( txId ) ; break ; } } if ( txToNotRecover . size ( ) > 0 ) // FILTER THE TX MAP TO RECOVER BY REMOVING THE TX WITH AT LEAST ONE "FREE" STATUS txToRecover . removeAll ( txToNotRecover ) ; return txToRecover ; }
Scans the segment and returns the set of transactions ids to recover .
324
15
141,076
private int recoverTransaction ( final int iTxId ) throws IOException { int recordsRecovered = 0 ; final ORecordId rid = new ORecordId ( ) ; final List < Long > txRecordPositions = new ArrayList < Long > ( ) ; // BROWSE ALL THE ENTRIES for ( long beginEntry = 0 ; eof ( beginEntry ) ; beginEntry = nextEntry ( beginEntry ) ) { long offset = beginEntry ; final byte status = file . readByte ( offset ) ; offset += OBinaryProtocol . SIZE_BYTE ; if ( status != STATUS_FREE ) { // DIRTY TX LOG ENTRY offset += OBinaryProtocol . SIZE_BYTE ; final int txId = file . readInt ( offset ) ; if ( txId == iTxId ) { txRecordPositions . add ( beginEntry ) ; } } } for ( int i = txRecordPositions . size ( ) - 1 ; i >= 0 ; i -- ) { final long beginEntry = txRecordPositions . get ( i ) ; long offset = beginEntry ; final byte status = file . readByte ( offset ) ; offset += OBinaryProtocol . SIZE_BYTE ; // DIRTY TX LOG ENTRY final byte operation = file . readByte ( offset ) ; offset += OBinaryProtocol . SIZE_BYTE ; // TX ID FOUND final int txId = file . readInt ( offset ) ; offset += OBinaryProtocol . SIZE_INT ; rid . clusterId = file . readShort ( offset ) ; offset += OBinaryProtocol . SIZE_SHORT ; rid . clusterPosition = file . readLong ( offset ) ; offset += OBinaryProtocol . SIZE_LONG ; final byte recordType = file . readByte ( offset ) ; offset += OBinaryProtocol . SIZE_BYTE ; final int recordVersion = file . readInt ( offset ) ; offset += OBinaryProtocol . SIZE_INT ; final int dataSegmentId = file . readInt ( offset ) ; offset += OBinaryProtocol . SIZE_INT ; final int recordSize = file . readInt ( offset ) ; offset += OBinaryProtocol . SIZE_INT ; final byte [ ] buffer ; if ( recordSize > 0 ) { buffer = new byte [ recordSize ] ; file . read ( offset , buffer , recordSize ) ; offset += recordSize ; } else buffer = null ; recoverTransactionEntry ( status , operation , txId , rid , recordType , recordVersion , buffer , dataSegmentId ) ; recordsRecovered ++ ; // CLEAR THE ENTRY BY WRITING '0' file . writeByte ( beginEntry , STATUS_FREE ) ; } return recordsRecovered ; }
Recover a transaction .
590
5
141,077
public static String pingJdbcEndpoint ( MuleContext muleContext , String muleJdbcDataSourceName , String tableName ) { DataSource ds = JdbcUtil . lookupDataSource ( muleContext , muleJdbcDataSourceName ) ; Connection c = null ; Statement s = null ; ResultSet rs = null ; try { c = ds . getConnection ( ) ; s = c . createStatement ( ) ; rs = s . executeQuery ( "select 1 from " + tableName ) ; } catch ( SQLException e ) { return ERROR_PREFIX + ": The table " + tableName + " was not found in the data source " + muleJdbcDataSourceName + ", reason: " + e . getMessage ( ) ; } finally { try { if ( rs != null ) rs . close ( ) ; } catch ( SQLException e ) { } try { if ( s != null ) s . close ( ) ; } catch ( SQLException e ) { } try { if ( c != null ) c . close ( ) ; } catch ( SQLException e ) { } } return OK_PREFIX + ": The table " + tableName + " was found in the data source " + muleJdbcDataSourceName ; }
Verify access to a JDBC endpoint by verifying that a specified table is accessible .
286
17
141,078
public static String pingJmsEndpoint ( MuleContext muleContext , String queueName ) { return pingJmsEndpoint ( muleContext , DEFAULT_MULE_JMS_CONNECTOR , queueName ) ; }
Verify access to a JMS endpoint by browsing a specified queue for messages .
50
16
141,079
@ SuppressWarnings ( "rawtypes" ) private static boolean isQueueEmpty ( MuleContext muleContext , String muleJmsConnectorName , String queueName ) throws JMSException { JmsConnector muleCon = ( JmsConnector ) MuleUtil . getSpringBean ( muleContext , muleJmsConnectorName ) ; Session s = null ; QueueBrowser b = null ; try { // Get a jms connection from mule and create a jms session s = muleCon . getConnection ( ) . createSession ( false , Session . AUTO_ACKNOWLEDGE ) ; Queue q = s . createQueue ( queueName ) ; b = s . createBrowser ( q ) ; Enumeration e = b . getEnumeration ( ) ; return ! e . hasMoreElements ( ) ; } finally { try { if ( b != null ) b . close ( ) ; } catch ( JMSException e ) { } try { if ( s != null ) s . close ( ) ; } catch ( JMSException e ) { } } }
Browse a queue for messages
234
6
141,080
@ Override public T select ( Object item ) { if ( item == null ) { return null ; } if ( itemClass . isInstance ( item ) ) { return itemClass . cast ( item ) ; } logger . debug ( "item [{}] is not assignable to class [{}], returning null" , item , itemClass ) ; return null ; }
If the item is null return null . If the item is instance of the constructor parameter itemClass return the type cast result otherwise return null .
78
28
141,081
public BeanQuery < T > orderBy ( String orderByProperty , Comparator propertyValueComparator ) { this . comparator = new DelegatedSortOrderableComparator ( new PropertyComparator ( orderByProperty , propertyValueComparator ) ) ; return this ; }
Specify the property of the beans to be compared by the propertyValueComparator when sorting the result . If there is not a accessible public read method of the property the value of the property passed to the propertyValueComparator will be null .
56
49
141,082
public BeanQuery < T > orderBy ( Comparator ... beanComparator ) { this . comparator = new DelegatedSortOrderableComparator ( ComparatorUtils . chainedComparator ( beanComparator ) ) ; return this ; }
Using an array of Comparators applied in sequence until one returns not equal or the array is exhausted .
50
20
141,083
public T executeFrom ( Object bean ) { List < T > executeFromCollectionResult = executeFrom ( Collections . singleton ( bean ) ) ; if ( CollectionUtils . isEmpty ( executeFromCollectionResult ) ) { return null ; } else { return executeFromCollectionResult . get ( 0 ) ; } }
Execute from a bean to check does it match the filtering condition and convert it .
65
17
141,084
public List < T > execute ( ) { if ( CollectionUtils . isEmpty ( from ) ) { logger . info ( "Querying from an empty collection, returning empty list." ) ; return Collections . emptyList ( ) ; } List copied = new ArrayList ( this . from ) ; logger . info ( "Start apply predicate [{}] to collection with [{}] items." , predicate , copied . size ( ) ) ; CollectionUtils . filter ( copied , this . predicate ) ; logger . info ( "Done filtering collection, filtered result size is [{}]" , copied . size ( ) ) ; if ( null != this . comparator && copied . size ( ) > 1 ) { Comparator actualComparator = this . descSorting ? comparator . desc ( ) : comparator . asc ( ) ; logger . info ( "Start to sort the filtered collection with comparator [{}]" , actualComparator ) ; Collections . sort ( copied , actualComparator ) ; logger . info ( "Done sorting the filtered collection." ) ; } logger . info ( "Start to slect from filtered collection with selector [{}]." , selector ) ; List < T > select = this . selector . select ( copied ) ; logger . info ( "Done select from filtered collection." ) ; return select ; }
Execute this Query . If query from a null or empty collection an empty list will be returned .
278
20
141,085
public static BeanQuery < Map < String , Object > > select ( KeyValueMapSelector ... selectors ) { return new BeanQuery < Map < String , Object > > ( new CompositeSelector ( selectors ) ) ; }
Create a BeanQuery instance with multiple Selectors .
48
10
141,086
@ Override public void write ( final Writer writer ) throws ConfigurationException , IOException { Preconditions . checkNotNull ( writer ) ; @ SuppressWarnings ( "unchecked" ) final HashMap < String , Object > settings = ( HashMap < String , Object > ) fromNode ( this . getModel ( ) . getInMemoryRepresentation ( ) ) ; this . mapper . writerWithDefaultPrettyPrinter ( ) . writeValue ( writer , settings ) ; }
Writes the configuration .
102
5
141,087
private ImmutableNode toNode ( final Builder builder , final Object obj ) { assert ! ( obj instanceof List ) ; if ( obj instanceof Map ) { return mapToNode ( builder , ( Map < String , Object > ) obj ) ; } else { return valueToNode ( builder , obj ) ; } }
Creates a node for the specified object .
66
9
141,088
private ImmutableNode mapToNode ( final Builder builder , final Map < String , Object > map ) { for ( final Map . Entry < String , Object > entry : map . entrySet ( ) ) { final String key = entry . getKey ( ) ; final Object value = entry . getValue ( ) ; if ( value instanceof List ) { // For a list, add each list item as a child of this node. for ( final Object item : ( List ) value ) { addChildNode ( builder , key , item ) ; } } else { // Otherwise, add the value as a child of this node. addChildNode ( builder , key , value ) ; } } return builder . create ( ) ; }
Creates a node for the specified map .
150
9
141,089
private void addChildNode ( final Builder builder , final String name , final Object value ) { assert ! ( value instanceof List ) ; final Builder childBuilder = new Builder ( ) ; // Set the name of the child node. childBuilder . name ( name ) ; // Set the value of the child node. final ImmutableNode childNode = toNode ( childBuilder , value ) ; // Add the node to the children of the node being built. builder . addChild ( childNode ) ; }
Adds a child node to the specified builder .
103
9
141,090
private ImmutableNode valueToNode ( final Builder builder , final Object value ) { // Set the value of the node being built. return builder . value ( value ) . create ( ) ; }
Creates a node for the specified value .
40
9
141,091
private Object fromNode ( final ImmutableNode node ) { if ( ! node . getChildren ( ) . isEmpty ( ) ) { final Map < String , List < ImmutableNode > > children = getChildrenWithName ( node ) ; final HashMap < String , Object > map = new HashMap <> ( ) ; for ( final Map . Entry < String , List < ImmutableNode > > entry : children . entrySet ( ) ) { assert ! entry . getValue ( ) . isEmpty ( ) ; if ( entry . getValue ( ) . size ( ) == 1 ) { // Just one node. final ImmutableNode child = entry . getValue ( ) . get ( 0 ) ; final Object childValue = fromNode ( child ) ; map . put ( entry . getKey ( ) , childValue ) ; } else { // Multiple nodes. final ArrayList < Object > list = new ArrayList <> ( ) ; for ( final ImmutableNode child : entry . getValue ( ) ) { final Object childValue = fromNode ( child ) ; list . add ( childValue ) ; } map . put ( entry . getKey ( ) , list ) ; } } return map ; } else { return node . getValue ( ) ; } }
Gets a serialization object from a node .
264
10
141,092
public ClassSelector except ( String ... propertyNames ) { if ( ArrayUtils . isEmpty ( propertyNames ) ) { return this ; } boolean updated = false ; for ( String propertyToRemove : propertyNames ) { if ( removePropertySelector ( propertyToRemove ) ) { updated = true ; } } if ( updated ) { compositeSelector = new CompositeSelector ( this . propertySelectors ) ; } return this ; }
Exclude properties from the result map .
91
8
141,093
public ClassSelector add ( String ... propertyNames ) { if ( ArrayUtils . isNotEmpty ( propertyNames ) ) { for ( String propertyNameToAdd : propertyNames ) { addPropertySelector ( propertyNameToAdd ) ; } } return this ; }
Include properties in the result map .
56
8
141,094
public ViewSelectionAttributeAssert attribute ( String attributeName ) { isNotEmpty ( ) ; ViewSelectionAttribute attributeValues = new ViewSelectionAttribute ( actual , attributeName ) ; return new ViewSelectionAttributeAssert ( attributeValues ) ; }
Creates an object for making assertions about an attribute set extracted from each view in the selection . This always fails for an empty selection .
53
27
141,095
private static Message generateHeader ( HeaderValues param ) { HeaderFields header = new HeaderFields ( ) ; setValues ( header , param ) ; Message headerMsg = header . unwrap ( ) ; for ( String comment : param . comments ) { headerMsg . addComment ( comment ) ; } return headerMsg ; }
This more general generate method is private along with the HeaderValues object until we decide what the public API should be .
67
23
141,096
public ViewSelection selectViews ( View view ) { ViewSelection result = new ViewSelection ( ) ; for ( List < Selector > selectorParts : selectorGroups ) { result . addAll ( selectViewsForGroup ( selectorParts , view ) ) ; } return result ; }
Applies this selector to the given view selecting all descendants of the view that match this selector .
62
19
141,097
@ Override public int compareTo ( final Problem o ) { final int ix = this . severity . ordinal ( ) ; final int oid = o . severity . ordinal ( ) ; return ix - oid ; }
Compare such that most severe Problems will appear last least first .
49
12
141,098
public static String fixValue ( String value ) { if ( value != null && ! value . equals ( "" ) ) { final String [ ] words = value . toLowerCase ( ) . split ( "_" ) ; value = "" ; for ( final String word : words ) { if ( word . length ( ) > 1 ) { value += word . substring ( 0 , 1 ) . toUpperCase ( ) + word . substring ( 1 ) + " " ; } else { value = word ; } } } if ( value . contains ( "\\n" ) ) { value = value . replace ( "\\n" , System . getProperty ( "line.separator" ) ) ; } return value ; }
replace under score with space replace \ n char with platform indepent line . separator
152
18
141,099
public static String removeLast ( String original , String string ) { int lastIndexOf = original . lastIndexOf ( string ) ; if ( lastIndexOf == - 1 ) { return original ; } return original . substring ( 0 , lastIndexOf ) ; }
This method create nre properties from the origianl one and remove any key with the password then call toString method on this prperties .
55
29