idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
140,800
private static long getTime ( int year , int month , int day , int hour , int minute , int second , int millisecond ) { Calendar cal = Calendar . getInstance ( Util . TIME_ZONE_UTC ) ; cal . set ( year , month - 1 , day , hour , minute , second ) ; cal . set ( Calendar . MILLISECOND , millisecond ) ; return cal . getTimeInMillis ( ) ; }
Returns the epoch time in ms .
94
7
140,801
private String getFolderAndCreateIfMissing ( String inFolder ) { String folder = outputFolder ; if ( inFolder != null ) { folder += "/" + inFolder ; } mkdirs ( folder ) ; return folder ; }
Computes foldername and creates the folders that does not already exist
48
13
140,802
public static EventBus get ( ) { if ( EventBus . instance == null ) { EventBus . instance = new EventBus ( ) ; } return EventBus . instance ; }
Get the singleton .
37
5
140,803
@ Override public ORecordIteratorClusters < REC > last ( ) { currentClusterIdx = clusterIds . length - 1 ; current . clusterPosition = liveUpdated ? database . countClusterElements ( clusterIds [ currentClusterIdx ] ) : lastClusterPosition + 1 ; return this ; }
Move the iterator to the end of the range . If no range was specified move to the last record of the cluster .
70
24
140,804
private static OIdentifiable linkToStream ( final StringBuilder buffer , final ORecordSchemaAware < ? > iParentRecord , Object iLinked ) { if ( iLinked == null ) // NULL REFERENCE return null ; OIdentifiable resultRid = null ; ORID rid ; final ODatabaseRecord database = ODatabaseRecordThreadLocal . INSTANCE . get ( ) ; if ( iLinked instanceof ORID ) { // JUST THE REFERENCE rid = ( ORID ) iLinked ; if ( rid . isValid ( ) && rid . isNew ( ) ) { // SAVE AT THE FLY AND STORE THE NEW RID final ORecord < ? > record = rid . getRecord ( ) ; if ( database . getTransaction ( ) . isActive ( ) ) { // USE THE DEFAULT CLUSTER database . save ( ( ORecordInternal < ? > ) record ) ; } else database . save ( ( ORecordInternal < ? > ) record ) ; if ( record != null ) rid = record . getIdentity ( ) ; resultRid = rid ; } } else { if ( iLinked instanceof String ) iLinked = new ORecordId ( ( String ) iLinked ) ; else if ( ! ( iLinked instanceof ORecordInternal < ? > ) ) { // NOT RECORD: TRY TO EXTRACT THE DOCUMENT IF ANY final String boundDocumentField = OObjectSerializerHelperManager . getInstance ( ) . getDocumentBoundField ( iLinked . getClass ( ) ) ; if ( boundDocumentField != null ) iLinked = OObjectSerializerHelperManager . getInstance ( ) . getFieldValue ( iLinked , boundDocumentField ) ; } if ( ! ( iLinked instanceof OIdentifiable ) ) throw new IllegalArgumentException ( "Invalid object received. Expected a OIdentifiable but received type=" + iLinked . getClass ( ) . getName ( ) + " and value=" + iLinked ) ; // RECORD ORecordInternal < ? > iLinkedRecord = ( ( OIdentifiable ) iLinked ) . getRecord ( ) ; rid = iLinkedRecord . getIdentity ( ) ; if ( rid . isNew ( ) || iLinkedRecord . isDirty ( ) ) { if ( iLinkedRecord instanceof ODocument ) { final OClass schemaClass = ( ( ODocument ) iLinkedRecord ) . getSchemaClass ( ) ; database . save ( iLinkedRecord , schemaClass != null ? database . getClusterNameById ( schemaClass . getDefaultClusterId ( ) ) : null ) ; } else // STORE THE TRAVERSED OBJECT TO KNOW THE RECORD ID. CALL THIS VERSION TO AVOID CLEAR OF STACK IN THREAD-LOCAL database . save ( iLinkedRecord ) ; final ODatabaseComplex < ? > dbOwner = database . getDatabaseOwner ( ) ; dbOwner . registerUserObjectAfterLinkSave ( iLinkedRecord ) ; resultRid = iLinkedRecord ; } if ( iParentRecord != null && database instanceof ODatabaseRecord ) { final ODatabaseRecord db = database ; if ( ! db . isRetainRecords ( ) ) // REPLACE CURRENT RECORD WITH ITS ID: THIS SAVES A LOT OF MEMORY resultRid = iLinkedRecord . getIdentity ( ) ; } } if ( rid . isValid ( ) ) rid . toString ( buffer ) ; return resultRid ; }
Serialize the link .
763
5
140,805
@ Override public ODocument toStream ( ) { acquireExclusiveLock ( ) ; try { document . setInternalStatus ( ORecordElement . STATUS . UNMARSHALLING ) ; try { final ORecordTrackedSet idxs = new ORecordTrackedSet ( document ) ; for ( final OIndexInternal < ? > i : indexes . values ( ) ) { idxs . add ( i . updateConfiguration ( ) ) ; } document . field ( CONFIG_INDEXES , idxs , OType . EMBEDDEDSET ) ; } finally { document . setInternalStatus ( ORecordElement . STATUS . LOADED ) ; } document . setDirty ( ) ; return document ; } finally { releaseExclusiveLock ( ) ; } }
Binds POJO to ODocument .
166
8
140,806
private void releaseCallbacks ( Exception ex ) { synchronized ( callbacks ) { for ( Map . Entry < Integer , InvokeCallback > cb : callbacks . entrySet ( ) ) { cb . getValue ( ) . release ( ex ) ; } } }
Release waiting threads if we fail for some reason
56
9
140,807
synchronized void line ( String line , long arrivalTime ) { if ( count . incrementAndGet ( ) % logCountFrequency == 0 ) log . info ( "count=" + count . get ( ) + ",buffer size=" + lines . size ( ) ) ; NmeaMessage nmea ; try { nmea = NmeaUtil . parseNmea ( line ) ; } catch ( NmeaMessageParseException e ) { listener . invalidNmea ( line , arrivalTime , e . getMessage ( ) ) ; return ; } // if is multi line message then don't report to listener till last // message in sequence has been received. if ( ! nmea . isSingleSentence ( ) ) { Optional < List < NmeaMessage >> messages = nmeaBuffer . add ( nmea ) ; if ( messages . isPresent ( ) ) { Optional < NmeaMessage > joined = AisNmeaBuffer . concatenateMessages ( messages . get ( ) ) ; if ( joined . isPresent ( ) ) { if ( joined . get ( ) . getUnixTimeMillis ( ) != null ) listener . message ( joined . get ( ) . toLine ( ) , joined . get ( ) . getUnixTimeMillis ( ) ) ; else listener . message ( joined . get ( ) . toLine ( ) , arrivalTime ) ; } // TODO else report error, might need to change signature of // listener to handle problem with multi-line message } return ; } if ( nmea . getUnixTimeMillis ( ) != null ) { listener . message ( line , nmea . getUnixTimeMillis ( ) ) ; return ; } if ( ! matchWithTimestampLine ) { listener . message ( line , arrivalTime ) ; return ; } if ( ! NmeaUtil . isValid ( line ) ) return ; addLine ( line , arrivalTime ) ; log . debug ( "buffer lines=" + lines . size ( ) ) ; Integer earliestTimestampLineIndex = getEarliestTimestampLineIndex ( lines ) ; Set < Integer > removeThese ; if ( earliestTimestampLineIndex != null ) { removeThese = matchWithClosestAisMessageIfBufferLargeEnough ( arrivalTime , earliestTimestampLineIndex ) ; } else removeThese = findExpiredIndexesBeforeIndex ( lastIndex ( ) ) ; TreeSet < Integer > orderedIndexes = Sets . newTreeSet ( removeThese ) ; for ( int index : orderedIndexes . descendingSet ( ) ) { removeLineWithIndex ( index ) ; } }
Handles the arrival of a new NMEA line at the given arrival time .
555
17
140,808
private Set < Integer > findExpiredIndexesBeforeIndex ( int index ) { long indexTime = getLineTime ( index ) ; Set < Integer > removeThese = Sets . newHashSet ( ) ; for ( int i = index - 1 ; i >= 0 ; i -- ) { if ( indexTime - getLineTime ( i ) > MAXIMUM_ARRIVAL_TIME_DIFFERENCE_MS ) { listener . timestampNotFound ( getLine ( i ) , getLineTime ( i ) ) ; removeThese . add ( i ) ; } } return removeThese ; }
Returns the list of those indexes that can be removed from the buffer because they have a timestamp more than MAXIMUM_ARRIVAL_TIME_DIFFERENCE_MS from the arrival time of the given index .
125
45
140,809
private Set < Integer > matchWithClosestAisMessageIfBufferLargeEnough ( long arrivalTime , Integer earliestTimestampLineIndex ) { String timestampLine = getLine ( earliestTimestampLineIndex ) ; long time = getLineTime ( earliestTimestampLineIndex ) ; log . debug ( "ts=" + timestampLine + ",time=" + time ) ; Set < Integer > removeThese ; if ( arrivalTime - time > MAXIMUM_ARRIVAL_TIME_DIFFERENCE_MS ) { removeThese = matchWithClosestAisMessageAndFindIndexesToRemove ( earliestTimestampLineIndex , timestampLine , time ) ; } else removeThese = findExpiredIndexesBeforeIndex ( earliestTimestampLineIndex ) ; return removeThese ; }
Finds matches and reports them to the listeners if buffer has a sufficent span of time in it . Returns the indexes that should be removed from the buffer .
163
33
140,810
private Set < Integer > reportMatchAndFindIndexesToRemove ( Integer earliestTimestampLineIndex , NmeaMessageExactEarthTimestamp timestamp , Integer lowestTimeDiffIndex ) { String msg = getLine ( lowestTimeDiffIndex ) ; log . debug ( "found matching msg=" + msg ) ; listener . message ( msg , timestamp . getTime ( ) ) ; int maxIndex = Math . max ( lowestTimeDiffIndex , earliestTimestampLineIndex ) ; int minIndex = Math . min ( lowestTimeDiffIndex , earliestTimestampLineIndex ) ; // now remove from lists must remove bigger index first, // otherwise indexes will change return Sets . newHashSet ( minIndex , maxIndex ) ; }
Reports a found match and returns the indexes that can be removed from the buffer .
149
16
140,811
public static MimeMessage createMimeMessage ( Session session , String from , String [ ] to , String subject , String content , DataSource [ ] attachments ) { logger . debug ( "Creates a mime message with {} attachments" , ( attachments == null ) ? 0 : attachments . length ) ; try { MimeMessage message = new MimeMessage ( session ) ; if ( from != null ) { message . setSender ( new InternetAddress ( from ) ) ; } if ( subject != null ) { message . setSubject ( subject , "UTF-8" ) ; } if ( to != null ) { for ( String toAdr : to ) { message . addRecipient ( Message . RecipientType . TO , new InternetAddress ( toAdr ) ) ; } } if ( attachments == null || attachments . length == 0 ) { // Setup a plain text message message . setContent ( content , "text/plain; charset=UTF-8" ) ; } else { // Setup a multipart message Multipart multipart = new MimeMultipart ( ) ; message . setContent ( multipart ) ; // Create the message part BodyPart messageBodyPart = new MimeBodyPart ( ) ; messageBodyPart . setContent ( content , "text/plain; charset=UTF-8" ) ; multipart . addBodyPart ( messageBodyPart ) ; // Add attachments, if any if ( attachments != null ) { for ( DataSource attachment : attachments ) { BodyPart attatchmentBodyPart = new MimeBodyPart ( ) ; attatchmentBodyPart . setDataHandler ( new DataHandler ( attachment ) ) ; attatchmentBodyPart . setFileName ( attachment . getName ( ) ) ; multipart . addBodyPart ( attatchmentBodyPart ) ; } } } return message ; } catch ( AddressException e ) { throw new RuntimeException ( e ) ; } catch ( MessagingException e ) { throw new RuntimeException ( e ) ; } }
Creates a mime - message multipart if attachements are supplied otherwise as plain text . Assumes UTF - 8 encoding for both subject and content .
421
32
140,812
public static void disableTlsServerCertificateCheck ( Client client ) { if ( ! ( client . getConduit ( ) instanceof HTTPConduit ) ) { log . warn ( "Conduit not of type HTTPConduit (" + client . getConduit ( ) . getClass ( ) . getName ( ) + ") , skip disabling server certification validation." ) ; return ; } log . warn ( "Disables server certification validation for: " + client . getEndpoint ( ) . getEndpointInfo ( ) . getAddress ( ) ) ; HTTPConduit httpConduit = ( HTTPConduit ) client . getConduit ( ) ; TLSClientParameters tlsParams = new TLSClientParameters ( ) ; TrustManager [ ] trustAllCerts = new TrustManager [ ] { new FakeTrustManager ( ) } ; tlsParams . setTrustManagers ( trustAllCerts ) ; tlsParams . setDisableCNCheck ( true ) ; httpConduit . setTlsClientParameters ( tlsParams ) ; }
Disables validation of https server certificates only to be used during development and tests!!!
228
16
140,813
public boolean isRuleDefined ( final String iResource ) { for ( ORole r : roles ) if ( r . hasRule ( iResource ) ) return true ; return false ; }
Checks if a rule was defined for the user .
39
11
140,814
public Object execute ( final Map < Object , Object > iArgs ) { if ( attribute == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not yet been parsed" ) ; final OClassImpl sourceClass = ( OClassImpl ) getDatabase ( ) . getMetadata ( ) . getSchema ( ) . getClass ( className ) ; if ( sourceClass == null ) throw new OCommandExecutionException ( "Source class '" + className + "' not found" ) ; final OPropertyImpl prop = ( OPropertyImpl ) sourceClass . getProperty ( fieldName ) ; if ( prop == null ) throw new OCommandExecutionException ( "Property '" + className + "." + fieldName + "' not exists" ) ; prop . setInternalAndSave ( attribute , value ) ; return null ; }
Execute the ALTER PROPERTY .
182
9
140,815
public void flush ( ) { lock . writeLock ( ) . lock ( ) ; try { OMMapBufferEntry entry ; for ( Iterator < OMMapBufferEntry > it = bufferPoolLRU . iterator ( ) ; it . hasNext ( ) ; ) { entry = it . next ( ) ; if ( entry . file != null && entry . file . isClosed ( ) ) { if ( removeEntry ( entry ) ) it . remove ( ) ; } } } finally { lock . writeLock ( ) . unlock ( ) ; } }
Flushes away all the buffers of closed files . This frees the memory .
116
16
140,816
public void flushFile ( final OFileMMap iFile ) { lock . readLock ( ) . lock ( ) ; try { final List < OMMapBufferEntry > entries = bufferPoolPerFile . get ( iFile ) ; if ( entries != null ) for ( OMMapBufferEntry entry : entries ) entry . flush ( ) ; } finally { lock . readLock ( ) . unlock ( ) ; } }
Flushes all the buffers of the passed file .
88
10
140,817
private static int searchEntry ( final List < OMMapBufferEntry > fileEntries , final long iBeginOffset , final int iSize ) { if ( fileEntries == null || fileEntries . size ( ) == 0 ) return - 1 ; int high = fileEntries . size ( ) - 1 ; if ( high < 0 ) // NOT FOUND return - 1 ; int low = 0 ; int mid = - 1 ; // BINARY SEARCH OMMapBufferEntry e ; while ( low <= high ) { mid = ( low + high ) >>> 1 ; e = fileEntries . get ( mid ) ; if ( iBeginOffset >= e . beginOffset && iBeginOffset + iSize <= e . beginOffset + e . size ) { // FOUND: USE IT OProfiler . getInstance ( ) . updateCounter ( "OMMapManager.reusedPage" , 1 ) ; e . counter ++ ; return mid ; } if ( low == high ) { if ( iBeginOffset > e . beginOffset ) // NEXT POSITION low ++ ; // NOT FOUND return ( low + 2 ) * - 1 ; } if ( iBeginOffset >= e . beginOffset ) low = mid + 1 ; else high = mid ; } // NOT FOUND return mid ; }
Search for a buffer in the ordered list .
271
9
140,818
public static Observable < Fix > from ( File file , boolean backpressure , BinaryFixesFormat format ) { if ( backpressure ) return BinaryFixesOnSubscribeWithBackp . from ( file , format ) ; else return BinaryFixesOnSubscribeFastPath . from ( file , format ) ; }
Automatically detects gzip based on filename .
63
9
140,819
public void encodeAmf3 ( Object obj , Amf3Type marker ) throws IOException { out . write ( marker . ordinal ( ) ) ; if ( marker == Amf3Type . NULL ) { return ; // Null marker is enough } serializeAmf3 ( obj , marker ) ; }
Encodes an object in amf3 as an object of the specified type
64
15
140,820
@ SneakyThrows ( value = { InstantiationException . class , IllegalAccessException . class } ) public void serializeAmf3 ( Object obj , Amf3Type marker ) throws IOException { if ( checkReferenceable ( obj , marker ) ) { return ; } Serialization context ; if ( amf3Serializers . containsKey ( obj . getClass ( ) ) ) { amf3Serializers . get ( obj . getClass ( ) ) . serialize ( obj , out ) ; } else if ( ( context = Util . searchClassHierarchy ( obj . getClass ( ) , Serialization . class ) ) != null && ! context . deserializeOnly ( ) ) { Amf3ObjectSerializer serializer = context . amf3Serializer ( ) . newInstance ( ) ; serializer . setTraitRefTable ( traitRefTable ) ; serializer . setTraitDefCache ( traitDefCache ) ; serializer . setWriter ( this ) ; serializer . serialize ( obj , out ) ; } else if ( obj . getClass ( ) . isArray ( ) ) { // Arrays require special handling serializeArrayAmf3 ( obj ) ; } else if ( obj instanceof Enum ) { // Enums are written by name serializeAmf3 ( ( ( Enum ) obj ) . name ( ) ) ; } else { Amf3ObjectSerializer serializer = new Amf3ObjectSerializer ( ) ; serializer . setTraitRefTable ( traitRefTable ) ; serializer . setTraitDefCache ( traitDefCache ) ; serializer . setWriter ( this ) ; serializer . serialize ( obj , out ) ; } out . flush ( ) ; }
Serializes the specified object to amf3
369
9
140,821
@ Override public Object evaluateRecord ( final OIdentifiable iRecord , final OSQLFilterCondition iCondition , final Object iLeft , final Object iRight , OCommandContext iContext ) { return true ; }
At run - time the evaluation per record must return always true since the recordset are filtered at the begin .
44
22
140,822
public Object execute ( final Map < Object , Object > iArgs ) { if ( name == null ) throw new OCommandExecutionException ( "Cannot execute the command because it has not been parsed yet" ) ; getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . dropIndex ( name ) ; return null ; }
Execute the REMOVE INDEX .
72
9
140,823
public void close ( ) { for ( Entry < String , OResourcePool < String , CH > > pool : pools . entrySet ( ) ) { for ( CH channel : pool . getValue ( ) . getResources ( ) ) { channel . close ( ) ; } } }
Closes all the channels .
58
6
140,824
public PlayerLifetimeStats retrievePlayerStatsByAccountId ( long accountId , Season season ) { return client . sendRpcAndWait ( SERVICE , "retrievePlayerStatsByAccountId" , accountId , season ) ; }
Retrieve player stats
49
4
140,825
public List < ChampionStatInfo > retrieveTopPlayedChampions ( long accId , GameMode mode ) { return client . sendRpcAndWait ( SERVICE , "retrieveTopPlayedChampions" , accId , mode ) ; }
Retrieve the most played champions for the target player
51
10
140,826
public AggregatedStats getAggregatedStats ( long id , GameMode gameMode , Season season ) { return client . sendRpcAndWait ( SERVICE , "getAggregatedStats" , id , gameMode , season . numeric ) ; }
Retrieve a player s stats
53
6
140,827
public EndOfGameStats getTeamEndOfGameStats ( TeamId teamId , long gameId ) { return client . sendRpcAndWait ( SERVICE , "getTeamEndOfGameStats" , teamId , gameId ) ; }
Retrieve post - game stats for a team
50
9
140,828
public void indexDocument ( final ODocument iDocument ) { modificationLock . requestModificationLock ( ) ; try { Object fieldValue ; for ( final String fieldName : iDocument . fieldNames ( ) ) { fieldValue = iDocument . field ( fieldName ) ; put ( fieldValue , iDocument ) ; } acquireExclusiveLock ( ) ; try { map . save ( ) ; } finally { releaseExclusiveLock ( ) ; } } finally { modificationLock . releaseModificationLock ( ) ; } }
Index an entire document field by field and save the index at the end .
107
15
140,829
@ Override public OIndexFullText put ( final Object iKey , final OIdentifiable iSingleValue ) { if ( iKey == null ) return this ; modificationLock . requestModificationLock ( ) ; try { final List < String > words = splitIntoWords ( iKey . toString ( ) ) ; // FOREACH WORD CREATE THE LINK TO THE CURRENT DOCUMENT for ( final String word : words ) { acquireExclusiveLock ( ) ; try { Set < OIdentifiable > refs ; // SEARCH FOR THE WORD refs = map . get ( word ) ; if ( refs == null ) // WORD NOT EXISTS: CREATE THE KEYWORD CONTAINER THE FIRST TIME THE WORD IS FOUND refs = new OMVRBTreeRIDSet ( ) . setAutoConvert ( false ) ; // ADD THE CURRENT DOCUMENT AS REF FOR THAT WORD refs . add ( iSingleValue ) ; // SAVE THE INDEX ENTRY map . put ( word , refs ) ; } finally { releaseExclusiveLock ( ) ; } } return this ; } finally { modificationLock . releaseModificationLock ( ) ; } }
Indexes a value and save the index . Splits the value in single words and index each one . Save of the index is responsibility of the caller .
256
31
140,830
@ Override public boolean remove ( final Object iKey , final OIdentifiable value ) { modificationLock . requestModificationLock ( ) ; try { final List < String > words = splitIntoWords ( iKey . toString ( ) ) ; boolean removed = false ; for ( final String word : words ) { acquireExclusiveLock ( ) ; try { final Set < OIdentifiable > recs = map . get ( word ) ; if ( recs != null && ! recs . isEmpty ( ) ) { if ( recs . remove ( value ) ) { if ( recs . isEmpty ( ) ) map . remove ( word ) ; else map . put ( word , recs ) ; removed = true ; } } } finally { releaseExclusiveLock ( ) ; } } return removed ; } finally { modificationLock . releaseModificationLock ( ) ; } }
Splits passed in key on several words and remove records with keys equals to any item of split result and values equals to passed in value .
184
28
140,831
public List < ORecordOperation > getRecordEntriesByClass ( final String iClassName ) { final List < ORecordOperation > result = new ArrayList < ORecordOperation > ( ) ; if ( iClassName == null || iClassName . length ( ) == 0 ) // RETURN ALL THE RECORDS for ( ORecordOperation entry : recordEntries . values ( ) ) { result . add ( entry ) ; } else // FILTER RECORDS BY CLASSNAME for ( ORecordOperation entry : recordEntries . values ( ) ) { if ( entry . getRecord ( ) != null && entry . getRecord ( ) instanceof ODocument && iClassName . equals ( ( ( ODocument ) entry . getRecord ( ) ) . getClassName ( ) ) ) result . add ( entry ) ; } return result ; }
Called by class iterator .
182
6
140,832
public List < ORecordOperation > getRecordEntriesByClusterIds ( final int [ ] iIds ) { final List < ORecordOperation > result = new ArrayList < ORecordOperation > ( ) ; if ( iIds == null ) // RETURN ALL THE RECORDS for ( ORecordOperation entry : recordEntries . values ( ) ) { result . add ( entry ) ; } else // FILTER RECORDS BY ID for ( ORecordOperation entry : recordEntries . values ( ) ) { for ( int id : iIds ) { if ( entry . getRecord ( ) != null && entry . getRecord ( ) . getIdentity ( ) . getClusterId ( ) == id ) { result . add ( entry ) ; break ; } } } return result ; }
Called by cluster iterator .
176
6
140,833
protected static int getValueByBinStr ( String binaryString , boolean signed ) { Integer value = Integer . parseInt ( binaryString , 2 ) ; if ( signed && binaryString . charAt ( 0 ) == ' ' ) { char [ ] invert = new char [ binaryString . length ( ) ] ; Arrays . fill ( invert , ' ' ) ; value ^= Integer . parseInt ( new String ( invert ) , 2 ) ; value += 1 ; value = - value ; } return value ; }
Get a value for specified bits from the binary string .
110
11
140,834
@ VisibleForTesting static byte [ ] ascii8To6bitBin ( byte [ ] toDecBytes ) { byte [ ] convertedBytes = new byte [ toDecBytes . length ] ; int sum = 0 ; int _6bitBin = 0 ; for ( int i = 0 ; i < toDecBytes . length ; i ++ ) { sum = 0 ; _6bitBin = 0 ; if ( toDecBytes [ i ] < 48 ) { throw new AisParseException ( AisParseException . INVALID_CHARACTER + " " + ( char ) toDecBytes [ i ] ) ; } else { if ( toDecBytes [ i ] > 119 ) { throw new AisParseException ( AisParseException . INVALID_CHARACTER + " " + ( char ) toDecBytes [ i ] ) ; } else { if ( toDecBytes [ i ] > 87 ) { if ( toDecBytes [ i ] < 96 ) { throw new AisParseException ( AisParseException . INVALID_CHARACTER + " " + ( char ) toDecBytes [ i ] ) ; } else { sum = toDecBytes [ i ] + 40 ; } } else { sum = toDecBytes [ i ] + 40 ; } if ( sum != 0 ) { if ( sum > 128 ) { sum += 32 ; } else { sum += 40 ; } _6bitBin = sum & 0x3F ; convertedBytes [ i ] = ( byte ) _6bitBin ; } } } } return convertedBytes ; }
Returns conversion of ASCII - coded character to 6 - bit binary byte array .
343
15
140,835
private static String getDecodedStr ( byte [ ] decBytes ) { // prepare StringBuilder with capacity being the smallest power of 2 // greater than decBytes.length*6 int n = decBytes . length * 6 ; int capacity = leastPowerOf2GreaterThanOrEqualTo ( n ) ; StringBuilder decStr = new StringBuilder ( capacity ) ; for ( int i = 0 ; i < decBytes . length ; i ++ ) { int decByte = decBytes [ i ] ; String bitStr = Integer . toBinaryString ( decByte ) ; int padding = Math . max ( 0 , 6 - bitStr . length ( ) ) ; for ( int j = 0 ; j < padding ; j ++ ) { decStr . append ( ' ' ) ; } for ( int j = 0 ; j < 6 - padding ; j ++ ) { decStr . append ( bitStr . charAt ( j ) ) ; } } return decStr . toString ( ) ; }
Get decoded string from bytes .
208
7
140,836
protected static String getAsciiStringFrom6BitStr ( String str ) { StringBuilder txt = new StringBuilder ( ) ; for ( int i = 0 ; i < str . length ( ) ; i = i + 6 ) { byte _byte = ( byte ) Integer . parseInt ( str . substring ( i , i + 6 ) , 2 ) ; _byte = convert6BitCharToStandardAscii ( _byte ) ; char convChar = ( char ) _byte ; if ( convChar == ' ' ) { break ; } txt . append ( ( char ) _byte ) ; } return txt . toString ( ) . trim ( ) ; }
Decode 6 bit String to standard ASCII String
143
9
140,837
@ VisibleForTesting static byte convert6BitCharToStandardAscii ( byte byteToConvert ) { byte b = 0 ; if ( byteToConvert < 32 ) { b = ( byte ) ( byteToConvert + 64 ) ; } else if ( byteToConvert < 63 ) { b = byteToConvert ; } return b ; }
Convert one 6 bit ASCII character to 8 bit ASCII character
77
12
140,838
public static void checkLatLong ( double lat , double lon ) { checkArgument ( lon <= 181.0 , "longitude out of range " + lon ) ; checkArgument ( lon > - 180.0 , "longitude out of range " + lon ) ; checkArgument ( lat <= 91.0 , "latitude out of range " + lat ) ; checkArgument ( lat > - 90.0 , "latitude out of range " + lat ) ; }
Check lat lon are withing allowable range as per 1371 - 4 . pdf . Note that values of long = 181 lat = 91 have special meaning .
106
32
140,839
public static void checkMessageId ( int messageId , AisMessageType ... messageTypes ) { boolean found = false ; for ( AisMessageType messageType : messageTypes ) { if ( messageType . getId ( ) == messageId ) found = true ; } if ( ! found ) { StringBuffer s = new StringBuffer ( ) ; for ( AisMessageType messageType : messageTypes ) { if ( s . length ( ) > 0 ) s . append ( "," ) ; s . append ( messageType . getId ( ) + "" ) ; } checkArgument ( found , "messageId must be in [" + s + "] but was " + messageId ) ; } }
Check message id corresponds to one of the given list of message types .
147
14
140,840
public static OMMapManager getInstance ( ) { if ( instanceRef . get ( ) == null ) { synchronized ( instanceRef ) { if ( instanceRef . compareAndSet ( null , createInstance ( ) ) ) { instanceRef . get ( ) . init ( ) ; } } } return instanceRef . get ( ) ; }
This method returns instance of mmap manager .
70
9
140,841
public void addArrayIdentity ( String array , String ... identities ) { arrayIdentities . put ( array , new ArrayIdentityFields ( identities ) ) ; }
Adds a group of fields that can uniquely identify array elements for object arrays
35
14
140,842
public Difference < BaseType > compareNodes ( BaseType node1 , BaseType node2 ) throws InvalidArrayIdentity , DuplicateArrayIdentity { return compareNodes ( new ArrayList < String > ( ) , node1 , new ArrayList < String > ( ) , node2 ) ; }
Compares two documents and returns the difference
60
8
140,843
public Difference < BaseType > compareObjects ( List < String > field1 , ObjectType node1 , List < String > field2 , ObjectType node2 ) throws InvalidArrayIdentity , DuplicateArrayIdentity { Difference < BaseType > ret = new Difference <> ( ) ; // Field by field comparison of obj1 to obj2. for ( Iterator < Map . Entry < String , BaseType > > fields = getFields ( node1 ) ; fields . hasNext ( ) ; ) { Map . Entry < String , BaseType > field = fields . next ( ) ; String fieldName = field . getKey ( ) ; field1 . add ( fieldName ) ; BaseType value1 = field . getValue ( ) ; if ( hasField ( node2 , fieldName ) ) { // If both obj1 and obj2 have the same field, compare recursively field2 . add ( fieldName ) ; BaseType value2 = getField ( node2 , fieldName ) ; ret . add ( compareNodes ( field1 , value1 , field2 , value2 ) ) ; pop ( field2 ) ; } else { // obj1.field1 exists, obj2.field1 does not, so it is removed ret . add ( new Removal ( field1 , value1 ) ) ; } pop ( field1 ) ; } // Now compare any new nodes added to obj2 for ( Iterator < Map . Entry < String , BaseType > > fields = getFields ( node2 ) ; fields . hasNext ( ) ; ) { Map . Entry < String , BaseType > field = fields . next ( ) ; String fieldName = field . getKey ( ) ; if ( ! hasField ( node1 , fieldName ) ) { field2 . add ( fieldName ) ; ret . add ( new Addition ( field2 , field . getValue ( ) ) ) ; pop ( field2 ) ; } } return ret ; }
Compares two object nodes recursively and returns the differences
402
12
140,844
public Difference < BaseType > compareArraysWithId ( List < String > field1 , ArrayType node1 , List < String > field2 , ArrayType node2 , IdentityExtractor idex ) throws InvalidArrayIdentity , DuplicateArrayIdentity { Difference < BaseType > ret = new Difference <> ( ) ; // Build a map of identity -> index for both arrays final Map < Object , Integer > identities1 = getIdentityMap ( field1 , node1 , idex ) ; final Map < Object , Integer > identities2 = getIdentityMap ( field2 , node2 , idex ) ; // Iterate all elements of array 1 for ( Map . Entry < Object , Integer > entry1 : identities1 . entrySet ( ) ) { // Append index to the field name field1 . add ( Integer . toString ( entry1 . getValue ( ) ) ) ; // If array2 doesn't have an element with the same ID, this is a deletion Integer index2 = identities2 . get ( entry1 . getKey ( ) ) ; if ( index2 == null ) { ret . add ( new Removal ( field1 , getElement ( node1 , entry1 . getValue ( ) ) ) ) ; } else { field2 . add ( Integer . toString ( index2 ) ) ; // array2 has the same element // If it is at a different index, this is a move if ( index2 != entry1 . getValue ( ) ) { ret . add ( new Move ( field1 , field2 , getElement ( node1 , entry1 . getValue ( ) ) ) ) ; } // Recursively compare contents to get detailed diff ret . add ( compareNodes ( field1 , getElement ( node1 , entry1 . getValue ( ) ) , field2 , getElement ( node2 , index2 ) ) ) ; pop ( field2 ) ; } pop ( field1 ) ; } // Now check elements of array 2 that are not in array 1 for ( Map . Entry < Object , Integer > entry2 : identities2 . entrySet ( ) ) { if ( ! identities1 . containsKey ( entry2 . getKey ( ) ) ) { // entry2 is not in array 1: addition field2 . add ( Integer . toString ( entry2 . getValue ( ) ) ) ; ret . add ( new Addition ( field2 , getElement ( node2 , entry2 . getValue ( ) ) ) ) ; pop ( field2 ) ; } } return ret ; }
Computes difference between arrays whose elements can be identitied by a unique identifier
528
16
140,845
@ Deprecated public OPropertyImpl dropIndexes ( ) { getDatabase ( ) . checkSecurity ( ODatabaseSecurityResources . SCHEMA , ORole . PERMISSION_DELETE ) ; final OIndexManager indexManager = getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) ; final ArrayList < OIndex < ? > > relatedIndexes = new ArrayList < OIndex < ? > > ( ) ; for ( final OIndex < ? > index : indexManager . getClassIndexes ( owner . getName ( ) ) ) { final OIndexDefinition definition = index . getDefinition ( ) ; if ( OCollections . indexOf ( definition . getFields ( ) , name , new OCaseIncentiveComparator ( ) ) > - 1 ) { if ( definition instanceof OPropertyIndexDefinition ) { relatedIndexes . add ( index ) ; } else { throw new IllegalArgumentException ( "This operation applicable only for property indexes. " + index . getName ( ) + " is " + index . getDefinition ( ) ) ; } } } for ( final OIndex < ? > index : relatedIndexes ) { getDatabase ( ) . getMetadata ( ) . getIndexManager ( ) . dropIndex ( index . getName ( ) ) ; } return this ; }
Remove the index on property
278
5
140,846
@ Deprecated public OIndex < ? > getIndex ( ) { Set < OIndex < ? > > indexes = owner . getInvolvedIndexes ( name ) ; if ( indexes != null && ! indexes . isEmpty ( ) ) return indexes . iterator ( ) . next ( ) ; return null ; }
Returns the first index defined for the property .
64
9
140,847
public OClass getLinkedClass ( ) { if ( linkedClass == null && linkedClassName != null ) linkedClass = owner . owner . getClass ( linkedClassName ) ; return linkedClass ; }
Returns the linked class in lazy mode because while unmarshalling the class could be not loaded yet .
43
20
140,848
public void setTypeInternal ( final OType iType ) { getDatabase ( ) . checkSecurity ( ODatabaseSecurityResources . SCHEMA , ORole . PERMISSION_UPDATE ) ; if ( iType == type ) // NO CHANGES return ; boolean ok = false ; switch ( type ) { case LINKLIST : ok = iType == OType . LINKSET ; break ; case LINKSET : ok = iType == OType . LINKLIST ; break ; } if ( ! ok ) throw new IllegalArgumentException ( "Cannot change property type from " + type + " to " + iType ) ; type = iType ; }
Change the type . It checks for compatibility between the change of type .
135
14
140,849
@ Override public void putAll ( final Map < ? extends K , ? extends V > map ) { int mapSize = map . size ( ) ; if ( size ( ) == 0 && mapSize != 0 && map instanceof SortedMap ) { Comparator < ? > c = ( ( SortedMap < ? extends K , ? extends V > ) map ) . comparator ( ) ; if ( c == comparator || ( c != null && c . equals ( comparator ) ) ) { ++ modCount ; try { buildFromSorted ( mapSize , map . entrySet ( ) . iterator ( ) , null , null ) ; } catch ( java . io . IOException cannotHappen ) { } catch ( ClassNotFoundException cannotHappen ) { } return ; } } super . putAll ( map ) ; }
Copies all of the mappings from the specified map to this map . These mappings replace any mappings that this map had for any of the keys currently in the specified map .
177
37
140,850
@ Override public V remove ( final Object key ) { OMVRBTreeEntry < K , V > p = getEntry ( key , PartialSearchMode . NONE ) ; setLastSearchNode ( null , null ) ; if ( p == null ) return null ; V oldValue = p . getValue ( ) ; deleteEntry ( p ) ; return oldValue ; }
Removes the mapping for this key from this OMVRBTree if present .
78
16
140,851
public static < K , V > OMVRBTreeEntry < K , V > next ( final OMVRBTreeEntry < K , V > t ) { if ( t == null ) return null ; final OMVRBTreeEntry < K , V > succ ; if ( t . tree . pageIndex < t . getSize ( ) - 1 ) { // ITERATE INSIDE THE NODE succ = t ; t . tree . pageIndex ++ ; } else { // GET THE NEXT NODE succ = OMVRBTree . successor ( t ) ; t . tree . pageIndex = 0 ; } return succ ; }
Returns the next item of the tree .
130
8
140,852
public static < K , V > OMVRBTreeEntry < K , V > previous ( final OMVRBTreeEntry < K , V > t ) { if ( t == null ) return null ; final int index = t . getTree ( ) . getPageIndex ( ) ; final OMVRBTreeEntry < K , V > prev ; if ( index <= 0 ) { prev = predecessor ( t ) ; if ( prev != null ) t . tree . pageIndex = prev . getSize ( ) - 1 ; else t . tree . pageIndex = 0 ; } else { prev = t ; t . tree . pageIndex = index - 1 ; } return prev ; }
Returns the previous item of the tree .
141
8
140,853
OMVRBTreeEntry < K , V > deleteEntry ( OMVRBTreeEntry < K , V > p ) { setSizeDelta ( - 1 ) ; modCount ++ ; if ( pageIndex > - 1 ) { // DELETE INSIDE THE NODE p . remove ( ) ; if ( p . getSize ( ) > 0 ) return p ; } final OMVRBTreeEntry < K , V > next = successor ( p ) ; // DELETE THE ENTIRE NODE, RE-BUILDING THE STRUCTURE removeNode ( p ) ; // RETURN NEXT NODE return next ; }
Delete node p and then re - balance the tree .
130
11
140,854
protected OMVRBTreeEntry < K , V > removeNode ( OMVRBTreeEntry < K , V > p ) { modCount ++ ; // If strictly internal, copy successor's element to p and then make p // point to successor. if ( p . getLeft ( ) != null && p . getRight ( ) != null ) { OMVRBTreeEntry < K , V > s = next ( p ) ; p . copyFrom ( s ) ; p = s ; } // p has 2 children // Start fixup at replacement node, if it exists. final OMVRBTreeEntry < K , V > replacement = ( p . getLeft ( ) != null ? p . getLeft ( ) : p . getRight ( ) ) ; if ( replacement != null ) { // Link replacement to parent replacement . setParent ( p . getParent ( ) ) ; if ( p . getParent ( ) == null ) setRoot ( replacement ) ; else if ( p == p . getParent ( ) . getLeft ( ) ) p . getParent ( ) . setLeft ( replacement ) ; else p . getParent ( ) . setRight ( replacement ) ; // Null out links so they are OK to use by fixAfterDeletion. p . setLeft ( null ) ; p . setRight ( null ) ; p . setParent ( null ) ; // Fix replacement if ( p . getColor ( ) == BLACK ) fixAfterDeletion ( replacement ) ; } else if ( p . getParent ( ) == null ) { // return if we are the only node. clear ( ) ; } else { // No children. Use self as phantom replacement and unlink. if ( p . getColor ( ) == BLACK ) fixAfterDeletion ( p ) ; if ( p . getParent ( ) != null ) { if ( p == p . getParent ( ) . getLeft ( ) ) p . getParent ( ) . setLeft ( null ) ; else if ( p == p . getParent ( ) . getRight ( ) ) p . getParent ( ) . setRight ( null ) ; p . setParent ( null ) ; } } return p ; }
Remove a node from the tree .
455
7
140,855
void readOTreeSet ( int iSize , ObjectInputStream s , V defaultVal ) throws java . io . IOException , ClassNotFoundException { buildFromSorted ( iSize , null , s , defaultVal ) ; }
Intended to be called only from OTreeSet . readObject
49
13
140,856
void addAllForOTreeSet ( SortedSet < ? extends K > set , V defaultVal ) { try { buildFromSorted ( set . size ( ) , set . iterator ( ) , null , defaultVal ) ; } catch ( java . io . IOException cannotHappen ) { } catch ( ClassNotFoundException cannotHappen ) { } }
Intended to be called only from OTreeSet . addAll
78
13
140,857
public static Observable < Fix > from ( final File file , BinaryFixesFormat format ) { Func0 < InputStream > resourceFactory = new Func0 < InputStream > ( ) { @ Override public InputStream call ( ) { try { if ( file . getName ( ) . endsWith ( ".gz" ) ) return new GZIPInputStream ( new FileInputStream ( file ) ) ; else return new FileInputStream ( file ) ; } catch ( FileNotFoundException e ) { throw new RuntimeException ( e ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } } ; Func1 < InputStream , Observable < Fix > > obsFactory = new Func1 < InputStream , Observable < Fix > > ( ) { @ Override public Observable < Fix > call ( InputStream is ) { Optional < Integer > mmsi ; if ( format == BinaryFixesFormat . WITH_MMSI ) mmsi = Optional . absent ( ) ; else mmsi = Optional . of ( BinaryFixesUtil . getMmsi ( file ) ) ; return Observable . create ( new BinaryFixesOnSubscribeWithBackp ( is , mmsi , format ) ) ; } } ; Action1 < InputStream > disposeAction = new Action1 < InputStream > ( ) { @ Override public void call ( InputStream is ) { try { is . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } } ; return Observable . using ( resourceFactory , obsFactory , disposeAction , true ) ; }
Returns stream of fixes from the given file . If the file name ends in . gz then the file is unzipped before being read .
348
29
140,858
protected String parserOptionalWord ( final boolean iUpperCase ) { previousPos = currentPos ; parserNextWord ( iUpperCase ) ; if ( parserLastWord . length ( ) == 0 ) return null ; return parserLastWord . toString ( ) ; }
Parses the next word . It returns the word parsed if any .
56
15
140,859
protected String parseOptionalWord ( final boolean iUpperCase , final String ... iWords ) { parserNextWord ( iUpperCase ) ; if ( iWords . length > 0 ) { if ( parserLastWord . length ( ) == 0 ) return null ; boolean found = false ; for ( String w : iWords ) { if ( parserLastWord . toString ( ) . equals ( w ) ) { found = true ; break ; } } if ( ! found ) throwSyntaxErrorException ( "Found unexpected keyword '" + parserLastWord + "' while it was expected '" + Arrays . toString ( iWords ) + "'" ) ; } return parserLastWord . toString ( ) ; }
Parses the next word . If any word is parsed it s checked against the word array received as parameter . If the parsed word is not enlisted in it a SyntaxError exception is thrown . It returns the word parsed if any .
150
48
140,860
protected String parserRequiredWord ( final boolean iUpperCase , final String iCustomMessage , String iSeparators ) { if ( iSeparators == null ) iSeparators = " =><(),\r\n" ; parserNextWord ( iUpperCase , iSeparators ) ; if ( parserLastWord . length ( ) == 0 ) throwSyntaxErrorException ( iCustomMessage ) ; return parserLastWord . toString ( ) ; }
Parses the next word . If no word is found or the parsed word is not present in the word array received as parameter then a SyntaxError exception with the custom message received as parameter is thrown . It returns the word parsed if any .
99
50
140,861
protected void parserNextWord ( final boolean iForceUpperCase , final String iSeparatorChars ) { previousPos = currentPos ; parserLastWord . setLength ( 0 ) ; parserSkipWhiteSpaces ( ) ; if ( currentPos == - 1 ) return ; char stringBeginChar = ' ' ; final String text2Use = iForceUpperCase ? textUpperCase : text ; while ( currentPos < text2Use . length ( ) ) { final char c = text2Use . charAt ( currentPos ) ; boolean found = false ; for ( int sepIndex = 0 ; sepIndex < iSeparatorChars . length ( ) ; ++ sepIndex ) { if ( iSeparatorChars . charAt ( sepIndex ) == c ) { // SEPARATOR AT THE BEGINNING: JUMP IT found = true ; break ; } } if ( ! found ) break ; currentPos ++ ; } try { while ( currentPos < text2Use . length ( ) ) { final char c = text2Use . charAt ( currentPos ) ; if ( c == ' ' || c == ' ' ) { if ( stringBeginChar != ' ' ) { // CLOSE THE STRING? if ( stringBeginChar == c ) { // SAME CHAR AS THE BEGIN OF THE STRING: CLOSE IT AND PUSH stringBeginChar = ' ' ; } } else { // START STRING stringBeginChar = c ; } } else if ( stringBeginChar == ' ' ) { for ( int sepIndex = 0 ; sepIndex < iSeparatorChars . length ( ) ; ++ sepIndex ) { if ( iSeparatorChars . charAt ( sepIndex ) == c && parserLastWord . length ( ) > 0 ) { // SEPARATOR (OUTSIDE A STRING): PUSH parserLastSeparator = c ; return ; } } } parserLastWord . append ( c ) ; currentPos ++ ; } parserLastSeparator = ' ' ; } finally { if ( currentPos >= text2Use . length ( ) ) // END OF TEXT currentPos = - 1 ; } }
Parses the next word .
455
7
140,862
public HandlerBuilder < ContextHandler > createRootContextHandler ( String subPath ) { ContextHandler contextHandler = new ContextHandler ( ) ; HandlerBuilder < ContextHandler > e = new HandlerBuilder <> ( contextHandler ) ; String usePath = contextPath + subPath ; setPath ( contextHandler , usePath ) ; handlers . add ( e ) ; return e ; }
Creates a HandlerBuilder that is mounted on top of the root path of this builder
77
17
140,863
public Optional < List < NmeaMessage > > add ( NmeaMessage nmea ) { // use compare-and-swap semantics instead of synchronizing to squeak a // bit more performance out of this. Contention is expected to be low so // this should help. while ( true ) { if ( adding . compareAndSet ( false , true ) ) { Optional < List < NmeaMessage >> result = doAdd ( nmea ) ; adding . set ( false ) ; return result ; } } }
Returns the complete message only once the whole group of messages has arrived otherwise returns null .
111
17
140,864
public static String getServiceName ( MuleEventContext event ) { // Mule 2.2 implementation // Service service = (event == null)? null : event.getService(); FlowConstruct service = ( event == null ) ? null : event . getFlowConstruct ( ) ; String name = ( service == null ) ? "" : service . getName ( ) ; return name ; }
Different implementations for retrieving the service name from a MuleEventContext - object in Mule 2 . 2 . x and Mule
79
26
140,865
public static ImmutableEndpoint getImmutableEndpoint ( MuleContext muleContext , String endpointName ) throws IOException { ImmutableEndpoint endpoint = null ; Object o = muleContext . getRegistry ( ) . lookupObject ( endpointName ) ; if ( o instanceof ImmutableEndpoint ) { // For Inbound and Outbound Endpoints endpoint = ( ImmutableEndpoint ) o ; } else if ( o instanceof EndpointBuilder ) { // For Endpoint-references EndpointBuilder eb = ( EndpointBuilder ) o ; try { endpoint = eb . buildInboundEndpoint ( ) ; } catch ( Exception e ) { throw new IOException ( e . getMessage ( ) ) ; } } return endpoint ; }
Lookup an ImmutableEndpoint based on its name
156
11
140,866
@ Override public OMVRBTreeEntryMemory < K , V > getNextInMemory ( ) { OMVRBTreeEntryMemory < K , V > t = this ; OMVRBTreeEntryMemory < K , V > p = null ; if ( t . right != null ) { p = t . right ; while ( p . left != null ) p = p . left ; } else { p = t . parent ; while ( p != null && t == p . right ) { t = p ; p = p . parent ; } } return p ; }
Returns the successor of the current Entry only by traversing the memory or null if no such .
119
19
140,867
public V setValue ( final V value ) { V oldValue = this . getValue ( ) ; this . values [ tree . pageIndex ] = value ; return oldValue ; }
Replaces the value currently associated with the key with the given value .
38
14
140,868
private void convertLink2Record ( final int iIndex ) { if ( ridOnly || ! autoConvertToRecord ) // PRECONDITIONS return ; final OIdentifiable o = super . get ( iIndex ) ; if ( contentType == MULTIVALUE_CONTENT_TYPE . ALL_RECORDS && ! o . getIdentity ( ) . isNew ( ) ) // ALL RECORDS AND THE OBJECT IS NOT NEW, DO NOTHING return ; if ( o != null && o instanceof ORecordId ) { final ORecordId rid = ( ORecordId ) o ; marshalling = true ; try { super . set ( iIndex , rid . getRecord ( ) ) ; } catch ( ORecordNotFoundException e ) { // IGNORE THIS } finally { marshalling = false ; } } }
Convert the item requested from link to record .
180
10
140,869
private boolean convertRecord2Link ( final int iIndex ) { if ( contentType == MULTIVALUE_CONTENT_TYPE . ALL_RIDS ) // PRECONDITIONS return true ; final Object o = super . get ( iIndex ) ; if ( o != null ) { if ( o instanceof ORecord < ? > && ! ( ( ORecord < ? > ) o ) . isDirty ( ) ) { marshalling = true ; try { super . set ( iIndex , ( ( ORecord < ? > ) o ) . getIdentity ( ) ) ; // CONVERTED return true ; } catch ( ORecordNotFoundException e ) { // IGNORE THIS } finally { marshalling = false ; } } else if ( o instanceof ORID ) // ALREADY CONVERTED return true ; } return false ; }
Convert the item requested from record to link .
183
10
140,870
public static String convertStreamToString ( InputStream is , String charset ) { if ( is == null ) return null ; StringBuilder sb = new StringBuilder ( ) ; String line ; long linecount = 0 ; long size = 0 ; try { // TODO: Can this be a performance killer if many many lines or is BufferedReader handling that in a good way? boolean emptyBuffer = true ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( new BOMStripperInputStream ( is ) , charset ) ) ; while ( ( line = reader . readLine ( ) ) != null ) { // Skip adding line break before the first line if ( emptyBuffer ) { emptyBuffer = false ; } else { sb . append ( ' ' ) ; size ++ ; } sb . append ( line ) ; linecount ++ ; size += line . length ( ) ; if ( logger . isTraceEnabled ( ) ) { if ( linecount % 50000 == 0 ) { logger . trace ( "Lines read: {}, {} characters and counting..." , linecount , size ) ; printMemUsage ( ) ; } } } } catch ( IOException e ) { throw new RuntimeException ( e ) ; } finally { if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Lines read: {}, {} characters" , linecount , size ) ; printMemUsage ( ) ; } // Ignore exceptions on call to the close method try { if ( is != null ) is . close ( ) ; } catch ( IOException e ) { } } return sb . toString ( ) ; }
Converts an InputStream to a String .
346
9
140,871
static Properties convertResourceBundleToProperties ( ResourceBundle resource ) { Properties properties = new Properties ( ) ; Enumeration < String > keys = resource . getKeys ( ) ; while ( keys . hasMoreElements ( ) ) { String key = keys . nextElement ( ) ; properties . put ( key , resource . getString ( key ) ) ; } return properties ; }
Convert ResourceBundle into a Properties object .
81
10
140,872
protected Map < Method , Object > getConsoleMethods ( ) { // search for declared command collections final Iterator < OConsoleCommandCollection > ite = ServiceRegistry . lookupProviders ( OConsoleCommandCollection . class ) ; final Collection < Object > candidates = new ArrayList < Object > ( ) ; candidates . add ( this ) ; while ( ite . hasNext ( ) ) { try { // make a copy and set it's context final OConsoleCommandCollection cc = ite . next ( ) . getClass ( ) . newInstance ( ) ; cc . setContext ( this ) ; candidates . add ( cc ) ; } catch ( InstantiationException ex ) { Logger . getLogger ( OConsoleApplication . class . getName ( ) ) . log ( Level . WARNING , ex . getMessage ( ) ) ; } catch ( IllegalAccessException ex ) { Logger . getLogger ( OConsoleApplication . class . getName ( ) ) . log ( Level . WARNING , ex . getMessage ( ) ) ; } } final Map < Method , Object > consoleMethods = new TreeMap < Method , Object > ( new Comparator < Method > ( ) { public int compare ( Method o1 , Method o2 ) { return o1 . getName ( ) . compareTo ( o2 . getName ( ) ) ; } } ) ; for ( final Object candidate : candidates ) { final Method [ ] methods = candidate . getClass ( ) . getMethods ( ) ; for ( Method m : methods ) { if ( Modifier . isAbstract ( m . getModifiers ( ) ) || Modifier . isStatic ( m . getModifiers ( ) ) || ! Modifier . isPublic ( m . getModifiers ( ) ) ) { continue ; } if ( m . getReturnType ( ) != Void . TYPE ) { continue ; } consoleMethods . put ( m , candidate ) ; } } return consoleMethods ; }
Returns a map of all console method and the object they can be called on .
405
16
140,873
static public List < String > listFilesInDirectory ( MuleContext muleContext , String endpointName ) { logger . info ( "List endpoint: {}" , endpointName ) ; FTPClient ftpClient = null ; List < String > fileNames = new ArrayList < String > ( ) ; try { ftpClient = getFtpClient ( muleContext , endpointName ) ; EndpointURI endpointURI = getImmutableEndpoint ( muleContext , endpointName ) . getEndpointURI ( ) ; String path = endpointURI . getPath ( ) ; logger . info ( "List directory: {}" , path ) ; FTPFile [ ] ftpFiles = ftpClient . listFiles ( path ) ; logger . debug ( "Number of files and sub-folders found: {}" , ftpFiles . length ) ; for ( FTPFile ftpFile : ftpFiles ) { if ( ftpFile . getType ( ) == FTPFile . FILE_TYPE ) { String filename = path + "/" + ftpFile . getName ( ) ; fileNames . add ( filename ) ; logger . debug ( "Added file {}" , filename ) ; } } logger . debug ( "Found {} files in {}" , fileNames . size ( ) , path ) ; } catch ( Exception e ) { if ( logger . isErrorEnabled ( ) ) logger . error ( "Failed to list files in endpoint " + endpointName , e ) ; throw new RuntimeException ( e ) ; } finally { if ( ftpClient != null ) { try { ftpClient . disconnect ( ) ; } catch ( IOException e ) { } } } return fileNames ; }
List files in a directory . Do not return sub - directories just plain files
353
15
140,874
static public void recursiveDeleteDirectory ( FTPClient ftpClient , String path ) throws IOException { logger . info ( "Delete directory: {}" , path ) ; FTPFile [ ] ftpFiles = ftpClient . listFiles ( path ) ; logger . debug ( "Number of files that will be deleted: {}" , ftpFiles . length ) ; for ( FTPFile ftpFile : ftpFiles ) { String filename = path + "/" + ftpFile . getName ( ) ; if ( ftpFile . getType ( ) == FTPFile . FILE_TYPE ) { boolean deleted = ftpClient . deleteFile ( filename ) ; logger . debug ( "Deleted {}? {}" , filename , deleted ) ; } else { recursiveDeleteDirectory ( ftpClient , filename ) ; } } boolean dirDeleted = ftpClient . deleteFile ( path ) ; logger . debug ( "Directory {} deleted: {}" , path , dirDeleted ) ; }
Deletes a directory with all its files and sub - directories .
205
13
140,875
static public void recursiveCreateDirectory ( FTPClient ftpClient , String path ) throws IOException { logger . info ( "Create Directory: {}" , path ) ; int createDirectoryStatus = ftpClient . mkd ( path ) ; // makeDirectory... logger . debug ( "Create Directory Status: {}" , createDirectoryStatus ) ; if ( createDirectoryStatus == FTP_FILE_NOT_FOUND ) { int sepIdx = path . lastIndexOf ( ' ' ) ; if ( sepIdx > - 1 ) { String parentPath = path . substring ( 0 , sepIdx ) ; recursiveCreateDirectory ( ftpClient , parentPath ) ; logger . debug ( "2'nd CreateD irectory: {}" , path ) ; createDirectoryStatus = ftpClient . mkd ( path ) ; // makeDirectory... logger . debug ( "2'nd Create Directory Status: {}" , createDirectoryStatus ) ; } } }
Create a directory and all missing parent - directories .
200
10
140,876
private void insertLinks ( Theme theme ) { if ( theme != null ) { for ( CssLink link : theme . getLinks ( ) ) { this . getHead ( ) . appendChild ( link . getLink ( ) ) ; } } }
Insert links in the document head tag .
52
8
140,877
private void removeCssLinks ( ) { if ( this . isInit ) { return ; } this . isInit = true ; // Remove all existing link element NodeList < Element > links = this . getHead ( ) . getElementsByTagName ( LinkElement . TAG ) ; int size = links . getLength ( ) ; for ( int i = 0 ; i < size ; i ++ ) { LinkElement elem = LinkElement . as ( links . getItem ( 0 ) ) ; if ( "stylesheet" . equals ( elem . getRel ( ) ) ) { elem . removeFromParent ( ) ; } } }
Removes all link tags in the head if not initialized .
135
12
140,878
protected HeadElement getHead ( ) { if ( this . head == null ) { Element elt = Document . get ( ) . getElementsByTagName ( "head" ) . getItem ( 0 ) ; assert elt != null : "The host HTML page does not have a <head> element" + " which is required by this injector" ; this . head = HeadElement . as ( elt ) ; } return this . head ; }
Gets the head tag element .
96
7
140,879
public static void reset ( ) { deactivateLogging ( ) ; deactivateReporting ( ) ; defaultLogLevel = Constants . INFO ; defaultReportLevel = Constants . INFO ; detectWTFMethods ( ) ; logLevels . clear ( ) ; maxOfEntriesInReports = 25 ; enableLogEntryCollection = false ; entries = null ; reporters . clear ( ) ; reportTriggerLevel = Constants . ASSERT ; Thread . setDefaultUncaughtExceptionHandler ( originalHandler ) ; originalHandler = null ; }
Resets the configuration .
109
5
140,880
private static Integer getLogLevel ( String tag ) { Integer result = logLevels . get ( tag ) ; if ( tag != null && result == null ) { int index = tag . lastIndexOf ( "." ) ; while ( result == null && index > - 1 ) { result = logLevels . get ( tag . substring ( 0 , index ) ) ; index = tag . lastIndexOf ( "." , index - 1 ) ; } } return result ; }
If called with a . b . c . d it will test for a . b . c . d a . b . c a . b a
100
30
140,881
public static boolean report ( String message , Throwable error ) { boolean acc = true ; for ( Reporter reporter : reporters ) { if ( reportFactory != null && reporter instanceof EnhancedReporter ) { Report report = reportFactory . create ( context , message , error ) ; acc = acc && ( ( EnhancedReporter ) reporter ) . send ( context , report ) ; } else { acc = acc && reporter . send ( context , message , error ) ; } } return acc ; }
Triggers a Report . This method generates the report and send it with all configured reporters .
100
19
140,882
private static synchronized void collectLogEntry ( int level , String tag , final String message , final Throwable err ) { if ( ! isReportable ( level ) ) { return ; } if ( maxOfEntriesInReports > 0 && entries . size ( ) == maxOfEntriesInReports ) { entries . remove ( 0 ) ; // Remove the first element. } entries . add ( LogHelper . print ( level , tag , message , err , addTimestampToReportLogs ) ) ; if ( level >= reportTriggerLevel ) { // Must be in another thread new Thread ( new Runnable ( ) { public void run ( ) { try { report ( message , err ) ; } catch ( Throwable e ) { // Ignore } } } ) . start ( ) ; } }
Adds a log entry to the collected entry list . This method managed the maximum number of entries and triggers report if the entry priority is superior or equals to the report trigger level .
165
35
140,883
public void grant ( final String iResource , final int iOperation ) { final Byte current = rules . get ( iResource ) ; byte currentValue = current == null ? PERMISSION_NONE : current . byteValue ( ) ; currentValue |= ( byte ) iOperation ; rules . put ( iResource , currentValue ) ; document . field ( "rules" , rules ) ; }
Grant a permission to the resource .
82
7
140,884
public static String permissionToString ( final int iPermission ) { int permission = iPermission ; final StringBuilder returnValue = new StringBuilder ( ) ; for ( Entry < Integer , String > p : PERMISSION_BIT_NAMES . entrySet ( ) ) { if ( ( permission & p . getKey ( ) ) == p . getKey ( ) ) { if ( returnValue . length ( ) > 0 ) returnValue . append ( ", " ) ; returnValue . append ( p . getValue ( ) ) ; permission &= ~ p . getKey ( ) ; } } if ( permission != 0 ) { if ( returnValue . length ( ) > 0 ) returnValue . append ( ", " ) ; returnValue . append ( "Unknown 0x" ) ; returnValue . append ( Integer . toHexString ( permission ) ) ; } return returnValue . toString ( ) ; }
Convert the permission code to a readable string .
191
10
140,885
public void start ( ) { try { while ( keepGoing ) { try { // this is a blocking call so it hogs a thread final Socket socket = ss . accept ( ) ; final String socketName = socket . getInetAddress ( ) . getHostAddress ( ) + ":" + socket . getPort ( ) ; log . info ( "accepted socket connection from " + socketName ) ; try { final OutputStream out = socket . getOutputStream ( ) ; Subscriber < String > subscriber = createSubscriber ( socket , socketName , out ) ; subscriptions . add ( subscriber ) ; source . subscribeOn ( Schedulers . io ( ) ) // remove subscriber from subscriptions on unsub . doOnUnsubscribe ( ( ) -> subscriptions . remove ( subscriber ) ) // write each line to the socket OutputStream . subscribe ( subscriber ) ; } catch ( IOException e ) { // could not get output stream (could have closed very // quickly after connecting) // dont' care log . warn ( e . getClass ( ) . getSimpleName ( ) + ": " + e . getMessage ( ) ) ; } } catch ( SocketTimeoutException e ) { // don't care log . warn ( e . getClass ( ) . getSimpleName ( ) + ": " + e . getMessage ( ) ) ; } } } catch ( IOException e ) { if ( keepGoing ) { log . warn ( e . getMessage ( ) , e ) ; throw new RuntimeException ( e ) ; } else log . info ( "server stopped" ) ; } finally { closeServerSocket ( ) ; } }
Starts the server . Each connection to the server will bring about another subscription to the source .
340
19
140,886
protected static int getLevel ( String level , int defaultLogLevel ) { try { return Integer . parseInt ( level ) ; } catch ( NumberFormatException e ) { // Try to read the string. if ( "VERBOSE" . equalsIgnoreCase ( level ) ) { return Constants . VERBOSE ; } else if ( "DEBUG" . equalsIgnoreCase ( level ) ) { return Constants . DEBUG ; } else if ( "INFO" . equalsIgnoreCase ( level ) ) { return Constants . INFO ; } else if ( "WARN" . equalsIgnoreCase ( level ) ) { return Constants . WARN ; } else if ( "ERROR" . equalsIgnoreCase ( level ) ) { return Constants . ERROR ; } else if ( "ASSERT" . equalsIgnoreCase ( level ) ) { return Constants . ASSERT ; } } return defaultLogLevel ; }
Parses the given level to get the log level . This method supports both integer level and String level .
192
22
140,887
public static String getCaller ( ) { StackTraceElement [ ] stacks = Thread . currentThread ( ) . getStackTrace ( ) ; if ( stacks != null ) { for ( int i = 0 ; i < stacks . length ; i ++ ) { String cn = stacks [ i ] . getClassName ( ) ; if ( cn != null && ! Constants . CLASSNAME_TO_ESCAPE . contains ( cn ) ) { return cn ; } } } return null ; }
Extracts the tag from the current stack trace .
108
11
140,888
protected static InputStream getConfigurationFileFromSDCard ( String fileName ) { File sdcard = Environment . getExternalStorageDirectory ( ) ; if ( sdcard == null || ! sdcard . exists ( ) || ! sdcard . canRead ( ) ) { return null ; } String sdCardPath = sdcard . getAbsolutePath ( ) ; File propFile = new File ( sdCardPath + "/" + fileName ) ; if ( ! propFile . exists ( ) ) { return null ; } FileInputStream fileIs = null ; try { fileIs = new FileInputStream ( propFile ) ; } catch ( FileNotFoundException e ) { // should not happen, we check that above return null ; } return fileIs ; }
Gets an input on a configuration file placed on the the SDCard .
157
16
140,889
protected static InputStream getConfigurationFileFromAssets ( Context context , String fileName ) { if ( context == null ) { return null ; } AssetManager assets = context . getAssets ( ) ; if ( assets == null ) { return null ; } try { return assets . open ( fileName ) ; } catch ( IOException e ) { return null ; } }
Gets an input on a configuration file placed in the application assets .
77
14
140,890
public static String print ( int priority , String tag , String msg , Throwable tr , boolean addTimestamp ) { // Compute the letter for the given priority String p = "X" ; // X => Unknown switch ( priority ) { case Constants . DEBUG : p = "D" ; break ; case Constants . INFO : p = "I" ; break ; case Constants . WARN : p = "W" ; break ; case Constants . ERROR : p = "E" ; break ; case Constants . ASSERT : p = "F" ; break ; } CharSequence timestamp = addTimestamp ? new SimpleDateFormat ( TIMESTAMP_PATTERN ) . format ( new Date ( ) ) : "" ; String base = p + "/" + timestamp + tag + ": " + msg ; return tr == null ? base : base + "\n" + getStackTraceString ( tr ) ; }
Gets a String form of the log data .
195
10
140,891
public int readLength ( ) throws IOException { int length = 0 ; byte b = ( byte ) this . read ( ) ; // This is short form. The short form can be used if the number of // octets in the Value part is less than or // equal to 127, and can be used whether the Value part is primitive or // constructed. This form is identified by // encoding bit 8 as zero, with the length count in bits 7 to 1 (as // usual, with bit 7 the most significant bit // of the length). if ( ( b & 0x80 ) == 0 ) { return b ; } // This is indefinite form. The indefinite form of length can only be // used (but does not have to be) if the V // part is constructed, that // is to say, consists of a series of TLVs. In the indefinite form of // length the first bit of the first octet is // set to 1, as for the long form, but the value N is set to zero. b = ( byte ) ( b & 0x7F ) ; if ( b == 0 ) { return Tag . Indefinite_Length ; } // If bit 8 of the first length octet is set to 1, then we have the long // form of length. In long form, the first // octet encodes in its remaining seven bits a value N which is the // length of a series of octets that themselves // encode the length of the Value part. byte temp ; for ( int i = 0 ; i < b ; i ++ ) { temp = ( byte ) this . read ( ) ; length = ( length << 8 ) | ( 0x00FF & temp ) ; } return length ; }
Reads and returns the length field . In case of indefinite length returns Tag . Indefinite_Length value
358
22
140,892
public AsnInputStream readSequenceStreamData ( int length ) throws AsnException , IOException { if ( length == Tag . Indefinite_Length ) { return this . readSequenceIndefinite ( ) ; } else { int startPos = this . pos ; this . advance ( length ) ; return new AsnInputStream ( this , startPos , length ) ; } }
This method can be invoked after the sequence tag and length has been read . Returns the AsnInputStream that contains the sequence data . The origin stream advances to the begin of the next record
82
38
140,893
public byte [ ] readSequenceData ( int length ) throws AsnException , IOException { AsnInputStream ais = this . readSequenceStreamData ( length ) ; byte [ ] res = new byte [ ais . length ] ; System . arraycopy ( ais . buffer , ais . start + ais . pos , res , 0 , ais . length ) ; return res ; }
This method can be invoked after the sequence tag and length has been read . Returns the byte stream that contains the sequence data . The origin stream advances to the begin of the next record
86
36
140,894
public void addPages ( ) { page = new CreateComponentStartPage ( selection ) ; addPage ( page ) ; integrationComponentPage = new CreateIntegrationComponentPage ( selection ) ; addPage ( integrationComponentPage ) ; serviceDescriptionComponentPage = new CreateServiceDescriptionComponentPage ( selection ) ; addPage ( serviceDescriptionComponentPage ) ; page3 = new StatusPage ( selection ) ; addPage ( page3 ) ; }
Adding the page to the wizard .
88
7
140,895
@ SuppressWarnings ( "unchecked" ) public REC next ( ) { checkDirection ( true ) ; ORecordInternal < ? > record = getRecord ( ) ; // ITERATE UNTIL THE NEXT GOOD RECORD while ( hasNext ( ) ) { record = getTransactionEntry ( ) ; if ( record != null ) return ( REC ) record ; if ( ( record = readCurrentRecord ( null , + 1 ) ) != null ) // FOUND return ( REC ) record ; } throw new NoSuchElementException ( ) ; }
Return the element at the current position and move forward the cursor to the next position available .
117
18
140,896
public ORecordIteratorCluster < REC > setRange ( final long iFrom , final long iEnd ) { firstClusterPosition = iFrom ; rangeTo = iEnd ; current . clusterPosition = firstClusterPosition ; return this ; }
Define the range where move the iterator forward and backward .
52
12
140,897
public long getRangeFrom ( ) { final long limit = ( liveUpdated ? database . getStorage ( ) . getClusterDataRange ( current . clusterId ) [ 1 ] : firstClusterPosition ) - 1 ; if ( rangeFrom > - 1 ) return Math . max ( rangeFrom , limit ) ; return limit ; }
Return the lower bound limit of the range if any otherwise 0 .
69
13
140,898
public long getRangeTo ( ) { final long limit = ( liveUpdated ? database . getStorage ( ) . getClusterDataRange ( current . clusterId ) [ 1 ] : lastClusterPosition ) + 1 ; if ( rangeTo > - 1 ) return Math . min ( rangeTo , limit ) ; return limit ; }
Return the upper bound limit of the range if any otherwise the last record .
69
15
140,899
public AisMessage getMessage ( ) { AisMessage m = aisParser . parse ( aisMessage , nmea . getSource ( ) , padBits ) ; return m ; }
Returns the parsed contents of column 5 of the AIS NMEA line .
42
16