idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
6,600 | private void releasePendingMessage ( ) { if ( pendingMessage != null ) { IRTMPEvent body = pendingMessage . getBody ( ) ; if ( body instanceof IStreamData && ( ( IStreamData < ? > ) body ) . getData ( ) != null ) { ( ( IStreamData < ? > ) body ) . getData ( ) . free ( ) ; } pendingMessage = null ; } } | Releases pending message body nullifies pending message object |
6,601 | protected boolean checkSendMessageEnabled ( RTMPMessage message ) { IRTMPEvent body = message . getBody ( ) ; if ( ! receiveAudio && body instanceof AudioData ) { ( ( IStreamData < ? > ) body ) . getData ( ) . free ( ) ; if ( sendBlankAudio ) { sendBlankAudio = false ; body = new AudioData ( ) ; if ( lastMessageTs >= 0 ) { body . setTimestamp ( lastMessageTs - timestampOffset ) ; } else { body . setTimestamp ( - timestampOffset ) ; } message = RTMPMessage . build ( body ) ; } else { return false ; } } else if ( ! receiveVideo && body instanceof VideoData ) { ( ( IStreamData < ? > ) body ) . getData ( ) . free ( ) ; return false ; } return true ; } | Check if sending the given message was enabled by the client . |
6,602 | private void runDeferredStop ( ) { clearWaitJobs ( ) ; log . trace ( "Ran deferred stop" ) ; if ( deferredStop == null ) { deferredStop = subscriberStream . scheduleWithFixedDelay ( new DeferredStopRunnable ( ) , 100 ) ; } } | Schedule a stop to be run from a separate thread to allow the background thread to stop cleanly . |
6,603 | protected void release ( BaseEvent event ) { Info info = events . get ( event ) ; if ( info != null ) { if ( info . refcount . decrementAndGet ( ) == 0 ) { events . remove ( event ) ; } } else { log . warn ( "Release called on already released event." ) ; } } | Release event if there s no more references to it |
6,604 | public static IScope resolveScope ( IScope from , String path ) { log . debug ( "resolveScope from: {} path: {}" , from . getName ( ) , path ) ; IScope current = from ; if ( path . startsWith ( SLASH ) ) { current = ScopeUtils . findRoot ( current ) ; path = path . substring ( 1 , path . length ( ) ) ; } if ( path . endsWith ( SLASH ) ) { path = path . substring ( 0 , path . length ( ) - 1 ) ; } log . trace ( "Current: {}" , current ) ; String [ ] parts = path . split ( SLASH ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Parts: {}" , Arrays . toString ( parts ) ) ; } for ( String part : parts ) { log . trace ( "Part: {}" , part ) ; if ( part . equals ( "." ) ) { continue ; } if ( part . equals ( ".." ) ) { if ( ! current . hasParent ( ) ) { return null ; } current = current . getParent ( ) ; continue ; } if ( ! current . hasChildScope ( part ) ) { return null ; } current = current . getScope ( part ) ; log . trace ( "Current: {}" , current ) ; } return current ; } | Resolves scope for specified scope and path . |
6,605 | public static IScope findRoot ( IScope from ) { IScope current = from ; while ( current . hasParent ( ) ) { current = current . getParent ( ) ; } return current ; } | Finds root scope for specified scope object . Root scope is the top level scope among scope s parents . |
6,606 | public static IScope findApplication ( IScope from ) { IScope current = from ; while ( current . hasParent ( ) && ! current . getType ( ) . equals ( ScopeType . APPLICATION ) ) { current = current . getParent ( ) ; } return current ; } | Returns the application scope for specified scope . Application scope has depth of 1 and has no parent . |
6,607 | public static boolean isAncestor ( IBasicScope from , IBasicScope ancestor ) { IBasicScope current = from ; while ( current . hasParent ( ) ) { current = current . getParent ( ) ; if ( current . equals ( ancestor ) ) { return true ; } } return false ; } | Check whether one scope is an ancestor of another |
6,608 | protected static Object getScopeService ( IScope scope , String name ) { return getScopeService ( scope , name , null ) ; } | Returns scope service by bean name . See overloaded method for details . |
6,609 | private ChannelInfo getChannelInfo ( int channelId ) { ChannelInfo info = channels . putIfAbsent ( channelId , new ChannelInfo ( ) ) ; if ( info == null ) { info = channels . get ( channelId ) ; } return info ; } | Returns channel information for a given channel id . |
6,610 | private void freePacket ( Packet packet ) { if ( packet != null && packet . getData ( ) != null ) { packet . clearData ( ) ; } } | Releases a packet . |
6,611 | private void freeChannels ( ) { for ( ChannelInfo info : channels . values ( ) ) { freePacket ( info . getReadPacket ( ) ) ; freePacket ( info . getWritePacket ( ) ) ; } channels . clear ( ) ; } | Releases the channels . |
6,612 | public void setLastReadPacket ( int channelId , Packet packet ) { final ChannelInfo info = getChannelInfo ( channelId ) ; Packet prevPacket = info . getReadPacket ( ) ; info . setReadPacket ( packet ) ; freePacket ( prevPacket ) ; } | Setter for last read packet . |
6,613 | public static boolean deleteDirectory ( String directory , boolean useOSNativeDelete ) throws IOException { boolean result = false ; if ( ! useOSNativeDelete ) { File dir = new File ( directory ) ; for ( File file : dir . listFiles ( ) ) { if ( file . delete ( ) ) { log . debug ( "{} was deleted" , file . getName ( ) ) ; } else { log . debug ( "{} was not deleted" , file . getName ( ) ) ; file . deleteOnExit ( ) ; } file = null ; } if ( dir . delete ( ) ) { log . debug ( "Directory was deleted" ) ; result = true ; } else { log . debug ( "Directory was not deleted, it may be deleted on exit" ) ; dir . deleteOnExit ( ) ; } dir = null ; } else { Process p = null ; Thread std = null ; try { Runtime runTime = Runtime . getRuntime ( ) ; log . debug ( "Execute runtime" ) ; if ( File . separatorChar == '\\' ) { p = runTime . exec ( "CMD /D /C \"RMDIR /Q /S " + directory . replace ( '/' , '\\' ) + "\"" ) ; } else { p = runTime . exec ( "rm -rf " + directory . replace ( '\\' , File . separatorChar ) ) ; } std = stdOut ( p ) ; while ( std . isAlive ( ) ) { try { Thread . sleep ( 250 ) ; } catch ( Exception e ) { } } log . debug ( "Process threads wait exited" ) ; result = true ; } catch ( Exception e ) { log . error ( "Error running delete script" , e ) ; } finally { if ( null != p ) { log . debug ( "Destroying process" ) ; p . destroy ( ) ; p = null ; } std = null ; } } return result ; } | Deletes a directory and its contents . This will fail if there are any file locks or if the directory cannot be emptied . |
6,614 | private final static Thread stdOut ( final Process p ) { final byte [ ] empty = new byte [ 128 ] ; for ( int b = 0 ; b < empty . length ; b ++ ) { empty [ b ] = ( byte ) 0 ; } Thread std = new Thread ( ) { public void run ( ) { StringBuilder sb = new StringBuilder ( 1024 ) ; byte [ ] buf = new byte [ 128 ] ; BufferedInputStream bis = new BufferedInputStream ( p . getInputStream ( ) ) ; log . debug ( "Process output:" ) ; try { while ( bis . read ( buf ) != - 1 ) { sb . append ( new String ( buf ) . trim ( ) ) ; System . arraycopy ( empty , 0 , buf , 0 , buf . length ) ; } log . debug ( sb . toString ( ) ) ; bis . close ( ) ; } catch ( Exception e ) { log . error ( "{}" , e ) ; } } } ; std . setDaemon ( true ) ; std . start ( ) ; return std ; } | Special method for capture of StdOut . |
6,615 | public static void unzip ( String compressedFileName , String destinationDir ) { String dirName = null ; String applicationName = compressedFileName . substring ( compressedFileName . lastIndexOf ( "/" ) ) ; int dashIndex = applicationName . indexOf ( '-' ) ; if ( dashIndex != - 1 ) { dirName = compressedFileName . substring ( 0 , dashIndex ) ; } else { dirName = compressedFileName . substring ( 0 , compressedFileName . lastIndexOf ( '.' ) ) ; } log . debug ( "Directory: {}" , dirName ) ; File zipDir = new File ( compressedFileName ) ; File parent = zipDir . getParentFile ( ) ; log . debug ( "Parent: {}" , ( parent != null ? parent . getName ( ) : null ) ) ; File tmpDir = new File ( destinationDir ) ; log . debug ( "Making directory: {}" , tmpDir . mkdirs ( ) ) ; ZipFile zf = null ; try { zf = new ZipFile ( compressedFileName ) ; Enumeration < ? > e = zf . entries ( ) ; while ( e . hasMoreElements ( ) ) { ZipEntry ze = ( ZipEntry ) e . nextElement ( ) ; log . debug ( "Unzipping {}" , ze . getName ( ) ) ; if ( ze . isDirectory ( ) ) { log . debug ( "is a directory" ) ; File dir = new File ( tmpDir + "/" + ze . getName ( ) ) ; Boolean tmp = dir . mkdir ( ) ; log . debug ( "{}" , tmp ) ; continue ; } if ( ze . getName ( ) . lastIndexOf ( "/" ) != - 1 ) { String zipName = ze . getName ( ) ; String zipDirStructure = zipName . substring ( 0 , zipName . lastIndexOf ( "/" ) ) ; File completeDirectory = new File ( tmpDir + "/" + zipDirStructure ) ; if ( ! completeDirectory . exists ( ) ) { if ( ! completeDirectory . mkdirs ( ) ) { log . error ( "could not create complete directory structure" ) ; } } } FileOutputStream fout = new FileOutputStream ( tmpDir + "/" + ze . getName ( ) ) ; InputStream in = zf . getInputStream ( ze ) ; copy ( in , fout ) ; in . close ( ) ; fout . close ( ) ; } e = null ; } catch ( IOException e ) { log . error ( "Errored unzipping" , e ) ; } finally { if ( zf != null ) { try { zf . close ( ) ; } catch ( IOException e ) { } } } } | Unzips a war file to an application located under the webapps directory |
6,616 | public static String formatPath ( String absWebappsPath , String contextDirName ) { StringBuilder path = new StringBuilder ( absWebappsPath . length ( ) + contextDirName . length ( ) ) ; path . append ( absWebappsPath ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Path start: {}" , path . toString ( ) ) ; } int idx = - 1 ; if ( File . separatorChar != '/' ) { while ( ( idx = path . indexOf ( File . separator ) ) != - 1 ) { path . deleteCharAt ( idx ) ; path . insert ( idx , '/' ) ; } } if ( log . isTraceEnabled ( ) ) { log . trace ( "Path step 1: {}" , path . toString ( ) ) ; } if ( ( idx = path . indexOf ( "./" ) ) != - 1 ) { path . delete ( idx , idx + 2 ) ; } if ( log . isTraceEnabled ( ) ) { log . trace ( "Path step 2: {}" , path . toString ( ) ) ; } if ( path . charAt ( path . length ( ) - 1 ) != '/' ) { path . append ( '/' ) ; } if ( log . isTraceEnabled ( ) ) { log . trace ( "Path step 3: {}" , path . toString ( ) ) ; } if ( contextDirName . charAt ( 0 ) == '/' && path . charAt ( path . length ( ) - 1 ) == '/' ) { path . append ( contextDirName . substring ( 1 ) ) ; } else { path . append ( contextDirName ) ; } if ( log . isTraceEnabled ( ) ) { log . trace ( "Path step 4: {}" , path . toString ( ) ) ; } return path . toString ( ) ; } | Quick - n - dirty directory formatting to support launching in windows specifically from ant . |
6,617 | public static String generateCustomName ( ) { Random random = new Random ( ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( PropertyConverter . getCurrentTimeSeconds ( ) ) ; sb . append ( '_' ) ; int i = random . nextInt ( 99999 ) ; if ( i < 10 ) { sb . append ( "0000" ) ; } else if ( i < 100 ) { sb . append ( "000" ) ; } else if ( i < 1000 ) { sb . append ( "00" ) ; } else if ( i < 10000 ) { sb . append ( '0' ) ; } sb . append ( i ) ; return sb . toString ( ) ; } | Generates a custom name containing numbers and an underscore ex . 282818_00023 . The name contains current seconds and a random number component . |
6,618 | public static byte [ ] readAsByteArray ( File localSwfFile ) { byte [ ] fileBytes = new byte [ ( int ) localSwfFile . length ( ) ] ; byte [ ] b = new byte [ 1 ] ; FileInputStream fis = null ; try { fis = new FileInputStream ( localSwfFile ) ; for ( int i = 0 ; i < Integer . MAX_VALUE ; i ++ ) { if ( fis . read ( b ) != - 1 ) { fileBytes [ i ] = b [ 0 ] ; } else { break ; } } } catch ( IOException e ) { log . warn ( "Exception reading file bytes" , e ) ; } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException e ) { } } } return fileBytes ; } | Reads all the bytes of a given file into an array . If the file size exceeds Integer . MAX_VALUE it will be truncated . |
6,619 | private Set < ISharedObjectSecurity > getSecurityHandlers ( ) { ISharedObjectSecurityService security = ( ISharedObjectSecurityService ) ScopeUtils . getScopeService ( getParent ( ) , ISharedObjectSecurityService . class ) ; if ( security == null ) { return null ; } return security . getSharedObjectSecurity ( ) ; } | Return security handlers for this shared object or |
6,620 | protected boolean isConnectionAllowed ( ) { for ( ISharedObjectSecurity handler : securityHandlers ) { if ( ! handler . isConnectionAllowed ( this ) ) { return false ; } } final Set < ISharedObjectSecurity > handlers = getSecurityHandlers ( ) ; if ( handlers == null ) { return true ; } for ( ISharedObjectSecurity handler : handlers ) { if ( ! handler . isConnectionAllowed ( this ) ) { return false ; } } return true ; } | Call handlers and check if connection to the existing SO is allowed . |
6,621 | protected boolean isWriteAllowed ( String key , Object value ) { for ( ISharedObjectSecurity handler : securityHandlers ) { if ( ! handler . isWriteAllowed ( this , key , value ) ) { return false ; } } final Set < ISharedObjectSecurity > handlers = getSecurityHandlers ( ) ; if ( handlers == null ) { return true ; } for ( ISharedObjectSecurity handler : handlers ) { if ( ! handler . isWriteAllowed ( this , key , value ) ) { return false ; } } return true ; } | Call handlers and check if writing to the SO is allowed . |
6,622 | protected boolean isDeleteAllowed ( String key ) { for ( ISharedObjectSecurity handler : securityHandlers ) { if ( ! handler . isDeleteAllowed ( this , key ) ) { return false ; } } final Set < ISharedObjectSecurity > handlers = getSecurityHandlers ( ) ; if ( handlers == null ) { return true ; } for ( ISharedObjectSecurity handler : handlers ) { if ( ! handler . isDeleteAllowed ( this , key ) ) { return false ; } } return true ; } | Call handlers and check if deleting a property from the SO is allowed . |
6,623 | protected boolean isSendAllowed ( String message , List < ? > arguments ) { for ( ISharedObjectSecurity handler : securityHandlers ) { if ( ! handler . isSendAllowed ( this , message , arguments ) ) { return false ; } } final Set < ISharedObjectSecurity > handlers = getSecurityHandlers ( ) ; if ( handlers == null ) { return true ; } for ( ISharedObjectSecurity handler : handlers ) { if ( ! handler . isSendAllowed ( this , message , arguments ) ) { return false ; } } return true ; } | Call handlers and check if sending a message to the clients connected to the SO is allowed . |
6,624 | public static void handleError ( HttpResponse response ) throws ParseException , IOException { log . debug ( "{}" , response . getStatusLine ( ) . toString ( ) ) ; HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { log . debug ( "{}" , EntityUtils . toString ( entity ) ) ; } } | Logs details about the request error . |
6,625 | public static void writeReverseInt ( IoBuffer out , int value ) { out . put ( ( byte ) ( 0xFF & value ) ) ; out . put ( ( byte ) ( 0xFF & ( value >> 8 ) ) ) ; out . put ( ( byte ) ( 0xFF & ( value >> 16 ) ) ) ; out . put ( ( byte ) ( 0xFF & ( value >> 24 ) ) ) ; } | Writes reversed integer to buffer . |
6,626 | public static int readUnsignedMediumInt ( IoBuffer in ) { final byte a = in . get ( ) ; final byte b = in . get ( ) ; final byte c = in . get ( ) ; int val = 0 ; val += ( a & 0xff ) << 16 ; val += ( b & 0xff ) << 8 ; val += ( c & 0xff ) ; return val ; } | Read unsigned 24 bit integer . |
6,627 | public static int readMediumInt ( IoBuffer in ) { final byte a = in . get ( ) ; final byte b = in . get ( ) ; final byte c = in . get ( ) ; int val = 0 ; val += ( a & 0xff ) << 16 ; val += ( b & 0xff ) << 8 ; val += ( c & 0xff ) ; return val ; } | Read 24 bit integer . |
6,628 | public static int readReverseInt ( IoBuffer in ) { final byte a = in . get ( ) ; final byte b = in . get ( ) ; final byte c = in . get ( ) ; final byte d = in . get ( ) ; int val = 0 ; val += ( d & 0xff ) << 24 ; val += ( c & 0xff ) << 16 ; val += ( b & 0xff ) << 8 ; val += ( a & 0xff ) ; return val ; } | Read integer in reversed order . |
6,629 | public static void encodeHeaderByte ( IoBuffer out , byte headerSize , int channelId ) { if ( channelId <= 63 ) { out . put ( ( byte ) ( ( headerSize << 6 ) + channelId ) ) ; } else if ( channelId <= 319 ) { out . put ( ( byte ) ( headerSize << 6 ) ) ; out . put ( ( byte ) ( channelId - 64 ) ) ; } else { out . put ( ( byte ) ( ( headerSize << 6 ) | 1 ) ) ; channelId -= 64 ; out . put ( ( byte ) ( channelId & 0xff ) ) ; out . put ( ( byte ) ( channelId >> 8 ) ) ; } } | Encodes header size marker and channel id into header marker . |
6,630 | public static long diffTimestamps ( final int a , final int b ) { final long unsignedA = a & 0xFFFFFFFFL ; final long unsignedB = b & 0xFFFFFFFFL ; final long delta = unsignedA - unsignedB ; return delta ; } | Calculates the delta between two time stamps adjusting for time stamp wrapping . |
6,631 | public void startWaitForHandshake ( ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "startWaitForHandshake - {}" , sessionId ) ; } if ( scheduler != null ) { try { waitForHandshakeTask = scheduler . schedule ( new WaitForHandshakeTask ( ) , new Date ( System . currentTimeMillis ( ) + maxHandshakeTimeout ) ) ; } catch ( TaskRejectedException e ) { log . error ( "WaitForHandshake task was rejected for {}" , sessionId , e ) ; } } } | Start waiting for a valid handshake . |
6,632 | private void stopWaitForHandshake ( ) { if ( waitForHandshakeTask != null ) { boolean cancelled = waitForHandshakeTask . cancel ( true ) ; waitForHandshakeTask = null ; if ( cancelled && log . isDebugEnabled ( ) ) { log . debug ( "waitForHandshake was cancelled for {}" , sessionId ) ; } } } | Cancels wait for handshake task . |
6,633 | private void startRoundTripMeasurement ( ) { if ( scheduler != null ) { if ( pingInterval > 0 ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "startRoundTripMeasurement - {}" , sessionId ) ; } try { keepAliveTask = scheduler . scheduleWithFixedDelay ( new KeepAliveTask ( ) , new Date ( System . currentTimeMillis ( ) + 2000L ) , pingInterval ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Keep alive scheduled for {}" , sessionId ) ; } } catch ( Exception e ) { log . error ( "Error creating keep alive job for {}" , sessionId , e ) ; } } } else { log . error ( "startRoundTripMeasurement cannot be executed due to missing scheduler. This can happen if a connection drops before handshake is complete" ) ; } } | Starts measurement . |
6,634 | private void stopRoundTripMeasurement ( ) { if ( keepAliveTask != null ) { boolean cancelled = keepAliveTask . cancel ( true ) ; keepAliveTask = null ; if ( cancelled && log . isDebugEnabled ( ) ) { log . debug ( "Keep alive was cancelled for {}" , sessionId ) ; } } } | Stops measurement . |
6,635 | public void setup ( String host , String path , Map < String , Object > params ) { this . host = host ; this . path = path ; this . params = params ; if ( Integer . valueOf ( 3 ) . equals ( params . get ( "objectEncoding" ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Setting object encoding to AMF3" ) ; } state . setEncoding ( Encoding . AMF3 ) ; } } | Initialize connection . |
6,636 | public Channel getChannel ( int channelId ) { Channel channel = channels . putIfAbsent ( channelId , new Channel ( this , channelId ) ) ; if ( channel == null ) { channel = channels . get ( channelId ) ; } return channel ; } | Return channel by id . |
6,637 | public void closeChannel ( int channelId ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "closeChannel: {}" , channelId ) ; } Channel chan = channels . remove ( channelId ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "channel: {} for id: {}" , chan , channelId ) ; if ( chan == null ) { log . trace ( "Channels: {}" , channels ) ; } } chan = null ; } | Closes channel . |
6,638 | public boolean isValidStreamId ( Number streamId ) { double d = streamId . doubleValue ( ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Checking validation for streamId {}; reservedStreams: {}; streams: {}, connection: {}" , new Object [ ] { d , reservedStreams , streams , sessionId } ) ; } if ( d <= 0 || ! reservedStreams . contains ( d ) ) { log . warn ( "Stream id: {} was not reserved in connection {}" , d , sessionId ) ; return false ; } if ( streams . get ( d ) != null ) { log . warn ( "Another stream already exists with this id in streams {} in connection: {}" , streams , sessionId ) ; return false ; } if ( log . isTraceEnabled ( ) ) { log . trace ( "Stream id: {} is valid for connection: {}" , d , sessionId ) ; } return true ; } | Returns whether or not a given stream id is valid . |
6,639 | public boolean isIdle ( ) { long lastPingTime = lastPingSentOn . get ( ) ; long lastPongTime = lastPongReceivedOn . get ( ) ; boolean idle = ( lastPongTime > 0 && ( lastPingTime - lastPongTime > maxInactivity ) ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Connection {} {} idle" , getSessionId ( ) , ( idle ? "is" : "is not" ) ) ; } return idle ; } | Returns whether or not the connection has been idle for a maximum period . |
6,640 | public Number getStreamIdForChannelId ( int channelId ) { if ( channelId < 4 ) { return 0 ; } Number streamId = Math . floor ( ( ( channelId - 4 ) / 5.0d ) + 1 ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Stream id: {} requested for channel id: {}" , streamId , channelId ) ; } return streamId ; } | Return stream id for given channel id . |
6,641 | public IClientStream getStreamByChannelId ( int channelId ) { if ( channelId < 4 ) { return null ; } Number streamId = getStreamIdForChannelId ( channelId ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Stream requested for channel id: {} stream id: {} streams: {}" , channelId , streamId , streams ) ; } return getStreamById ( streamId ) ; } | Return stream by given channel id . |
6,642 | public int getChannelIdForStreamId ( Number streamId ) { int channelId = ( int ) ( streamId . doubleValue ( ) * 5 ) - 1 ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Channel id: {} requested for stream id: {}" , channelId , streamId ) ; } return channelId ; } | Return channel id for given stream id . |
6,643 | public OutputStream createOutputStream ( Number streamId ) { int channelId = getChannelIdForStreamId ( streamId ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Create output - stream id: {} channel id: {}" , streamId , channelId ) ; } final Channel data = getChannel ( channelId ++ ) ; final Channel video = getChannel ( channelId ++ ) ; final Channel audio = getChannel ( channelId ++ ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Output stream - data: {} video: {} audio: {}" , data , video , audio ) ; } return new OutputStream ( video , audio , data ) ; } | Creates output stream object from stream id . Output stream consists of audio video and data channels . |
6,644 | private void customizeStream ( Number streamId , AbstractClientStream stream ) { Integer buffer = streamBuffers . get ( streamId . doubleValue ( ) ) ; if ( buffer != null ) { stream . setClientBufferDuration ( buffer ) ; } stream . setName ( createStreamName ( ) ) ; stream . setConnection ( this ) ; stream . setScope ( this . getScope ( ) ) ; stream . setStreamId ( streamId ) ; } | Specify name connection scope and etc for stream |
6,645 | private boolean registerStream ( IClientStream stream ) { if ( streams . putIfAbsent ( stream . getStreamId ( ) . doubleValue ( ) , stream ) == null ) { usedStreams . incrementAndGet ( ) ; return true ; } log . error ( "Unable to register stream {}, stream with id {} was already added" , stream , stream . getStreamId ( ) ) ; return false ; } | Store a stream in the connection . |
6,646 | protected void updateBytesRead ( ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "updateBytesRead" ) ; } long bytesRead = getReadBytes ( ) ; if ( bytesRead >= nextBytesRead ) { BytesRead sbr = new BytesRead ( ( int ) ( bytesRead % Integer . MAX_VALUE ) ) ; getChannel ( 2 ) . write ( sbr ) ; nextBytesRead += bytesReadInterval ; } } | Update number of bytes to read next value . |
6,647 | public void receivedBytesRead ( int bytes ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Client received {} bytes, written {} bytes, {} messages pending" , new Object [ ] { bytes , getWrittenBytes ( ) , getPendingMessages ( ) } ) ; } clientBytesRead . addAndGet ( bytes ) ; } | Read number of received bytes . |
6,648 | protected void writingMessage ( Packet message ) { if ( message . getMessage ( ) instanceof VideoData ) { Number streamId = message . getHeader ( ) . getStreamId ( ) ; final AtomicInteger value = new AtomicInteger ( ) ; AtomicInteger old = pendingVideos . putIfAbsent ( streamId . doubleValue ( ) , value ) ; if ( old == null ) { old = value ; } old . incrementAndGet ( ) ; } } | Mark message as being written . |
6,649 | public void handleMessageReceived ( Packet packet ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "handleMessageReceived - {}" , sessionId ) ; } if ( maxHandlingTimeout > 0 ) { packet . setExpirationTime ( System . currentTimeMillis ( ) + maxHandlingTimeout ) ; } if ( executor != null ) { final byte dataType = packet . getHeader ( ) . getDataType ( ) ; switch ( dataType ) { case Constants . TYPE_PING : case Constants . TYPE_ABORT : case Constants . TYPE_BYTES_READ : case Constants . TYPE_CHUNK_SIZE : case Constants . TYPE_CLIENT_BANDWIDTH : case Constants . TYPE_SERVER_BANDWIDTH : try { handler . messageReceived ( this , packet ) ; } catch ( Exception e ) { log . error ( "Error processing received message {}" , sessionId , e ) ; } break ; default : final String messageType = getMessageType ( packet ) ; try { final long packetNumber = packetSequence . incrementAndGet ( ) ; if ( executorQueueSizeToDropAudioPackets > 0 && currentQueueSize . get ( ) >= executorQueueSizeToDropAudioPackets ) { if ( packet . getHeader ( ) . getDataType ( ) == Constants . TYPE_AUDIO_DATA ) { log . info ( "Queue threshold reached. Discarding packet: session=[{}], msgType=[{}], packetNum=[{}]" , sessionId , messageType , packetNumber ) ; return ; } } int streamId = packet . getHeader ( ) . getStreamId ( ) . intValue ( ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Handling message for streamId: {}, channelId: {} Channels: {}" , streamId , packet . getHeader ( ) . getChannelId ( ) , channels ) ; } ReceivedMessageTask task = new ReceivedMessageTask ( sessionId , packet , handler , this ) ; task . setPacketNumber ( packetNumber ) ; ReceivedMessageTaskQueue newStreamTasks = new ReceivedMessageTaskQueue ( streamId , this ) ; ReceivedMessageTaskQueue currentStreamTasks = tasksByStreams . putIfAbsent ( streamId , newStreamTasks ) ; if ( currentStreamTasks != null ) { currentStreamTasks . addTask ( task ) ; } else { newStreamTasks . addTask ( task ) ; } } catch ( Exception e ) { log . error ( "Incoming message handling failed on session=[" + sessionId + "], messageType=[" + messageType + "]" , e ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Execution rejected on {} - {}" , sessionId , RTMP . states [ getStateCode ( ) ] ) ; log . debug ( "Lock permits - decode: {} encode: {}" , decoderLock . availablePermits ( ) , encoderLock . availablePermits ( ) ) ; } } } } else { log . debug ( "Executor is null on {} state: {}" , sessionId , RTMP . states [ getStateCode ( ) ] ) ; try { handler . messageReceived ( this , packet ) ; } catch ( Exception e ) { log . error ( "Error processing received message {} state: {}" , sessionId , RTMP . states [ getStateCode ( ) ] , e ) ; } } } | Handle the incoming message . |
6,650 | public void messageSent ( Packet message ) { if ( message . getMessage ( ) instanceof VideoData ) { Number streamId = message . getHeader ( ) . getStreamId ( ) ; AtomicInteger pending = pendingVideos . get ( streamId . doubleValue ( ) ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Stream id: {} pending: {} total pending videos: {}" , streamId , pending , pendingVideos . size ( ) ) ; } if ( pending != null ) { pending . decrementAndGet ( ) ; } } writtenMessages . incrementAndGet ( ) ; } | Mark message as sent . |
6,651 | public void sendSharedObjectMessage ( String name , int currentVersion , boolean persistent , Set < ISharedObjectEvent > events ) { SharedObjectMessage syncMessage = state . getEncoding ( ) == Encoding . AMF3 ? new FlexSharedObjectMessage ( null , name , currentVersion , persistent ) : new SharedObjectMessage ( null , name , currentVersion , persistent ) ; syncMessage . addEvents ( events ) ; try { Channel channel = getChannel ( 3 ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Send to channel: {}" , channel ) ; } channel . write ( syncMessage ) ; } catch ( Exception e ) { log . warn ( "Exception sending shared object" , e ) ; } } | Send a shared object message . |
6,652 | public void pingReceived ( Ping pong ) { long now = System . currentTimeMillis ( ) ; long previousPingTime = lastPingSentOn . get ( ) ; int previousPingValue = ( int ) ( previousPingTime & 0xffffffffL ) ; int pongValue = pong . getValue2 ( ) . intValue ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Pong received: session=[{}] at {} with value {}, previous received at {}" , new Object [ ] { getSessionId ( ) , now , pongValue , previousPingValue } ) ; } if ( pongValue == previousPingValue ) { lastPingRoundTripTime . set ( ( int ) ( ( now - previousPingTime ) & 0xffffffffL ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Ping response session=[{}], RTT=[{} ms]" , new Object [ ] { getSessionId ( ) , lastPingRoundTripTime . get ( ) } ) ; } } else { if ( getPendingMessages ( ) > 4 ) { int pingRtt = ( int ) ( ( now & 0xffffffffL ) ) - pongValue ; log . info ( "Pong delayed: session=[{}], ping response took [{} ms] to arrive. Connection may be congested, or loopback" , new Object [ ] { getSessionId ( ) , pingRtt } ) ; } } lastPongReceivedOn . set ( now ) ; } | Marks that ping back was received . |
6,653 | public void printAutomaton ( final PrintStream out ) { out . println ( "digraph ahocorasick {" ) ; printDebug ( out , root ) ; out . println ( "}" ) ; } | Prints dot description of the automaton to out for visualization in GraphViz . Used for debugging and education . |
6,654 | public void setJavaScriptEscapeChars ( final int [ ] escapeCharacters ) { final CharacterEscapes ce = new CharacterEscapes ( ) { private static final long serialVersionUID = 1L ; public int [ ] getEscapeCodesForAscii ( ) { if ( escapeCharacters == null ) { return CharacterEscapes . standardAsciiEscapesForJSON ( ) ; } return escapeCharacters ; } public SerializableString getEscapeSequence ( final int ch ) { final String jsEscaped = escapeChar ( ( char ) ch ) ; return new SerializedString ( jsEscaped ) ; } } ; jsonGenerator . setCharacterEscapes ( ce ) ; } | By default JSON output does only have escaping where it is strictly necessary . This is recommended in the most cases . Nevertheless it can be sometimes useful to have some more escaping . |
6,655 | public void replay ( ) { int index = 0 ; for ( MessageType type : typeBuffer ) { switch ( type ) { case RECORD_START : getReceiver ( ) . startRecord ( valueBuffer . get ( index ) ) ; ++ index ; break ; case RECORD_END : getReceiver ( ) . endRecord ( ) ; break ; case ENTITY_START : getReceiver ( ) . startEntity ( valueBuffer . get ( index ) ) ; ++ index ; break ; case ENTITY_END : getReceiver ( ) . endEntity ( ) ; break ; default : getReceiver ( ) . literal ( valueBuffer . get ( index ) , valueBuffer . get ( index + 1 ) ) ; index += 2 ; break ; } } } | Replays the buffered event . |
6,656 | public InlineMorph with ( String line ) { if ( scriptBuilder . length ( ) == 0 ) { appendBoilerplate ( line ) ; } scriptBuilder . append ( line ) . append ( "\n" ) ; return this ; } | Adds a line to the morph script . |
6,657 | public static String repeatChars ( final char ch , final int count ) { return CharBuffer . allocate ( count ) . toString ( ) . replace ( '\0' , ch ) ; } | Creates a string which contains a sequence of repeated characters . |
6,658 | public String getCurrentPathWith ( final String literalName ) { if ( entityStack . size ( ) == 0 ) { return literalName ; } return getCurrentPath ( ) + entitySeparator + literalName ; } | Returns the current entity path with the given literal name appended . |
6,659 | String stringAt ( final int fromIndex , final int length , final Charset charset ) { return new String ( byteArray , fromIndex , length , charset ) ; } | Returns a string containing the characters in the specified part of the record . |
6,660 | private static MemoryPoolMXBean findTenuredGenPool ( ) { for ( final MemoryPoolMXBean pool : ManagementFactory . getMemoryPoolMXBeans ( ) ) if ( pool . getType ( ) == MemoryType . HEAP && pool . isUsageThresholdSupported ( ) ) { return pool ; } throw new AssertionError ( "Could not find tenured space" ) ; } | Tenured Space Pool can be determined by it being of type HEAP and by it being possible to set the usage threshold . |
6,661 | public ListRet listLive ( String prefix , int limit , String marker ) throws PiliException { return list ( true , prefix , limit , marker ) ; } | list streams which is live |
6,662 | public BatchLiveStatus [ ] batchLiveStatus ( String [ ] streamTitles ) throws PiliException { String path = baseUrl + "/livestreams" ; String json = gson . toJson ( new BatchLiveStatusOptions ( streamTitles ) ) ; try { String resp = cli . callWithJson ( path , json ) ; BatchLiveStatusRet ret = gson . fromJson ( resp , BatchLiveStatusRet . class ) ; return ret . items ; } catch ( PiliException e ) { throw e ; } catch ( Exception e ) { throw new PiliException ( e ) ; } } | batch get live status |
6,663 | public Stream info ( ) throws PiliException { try { String resp = cli . callWithGet ( baseUrl ) ; StreamInfo ret = gson . fromJson ( resp , StreamInfo . class ) ; ret . setMeta ( info . getHub ( ) , info . getKey ( ) ) ; this . info = ret ; return this ; } catch ( PiliException e ) { throw e ; } catch ( Exception e ) { throw new PiliException ( e ) ; } } | fetch stream info |
6,664 | public LiveStatus liveStatus ( ) throws PiliException { String path = baseUrl + "/live" ; try { String resp = cli . callWithGet ( path ) ; LiveStatus status = gson . fromJson ( resp , LiveStatus . class ) ; return status ; } catch ( PiliException e ) { throw e ; } catch ( Exception e ) { throw new PiliException ( e ) ; } } | get the status of live stream |
6,665 | public String save ( SaveOptions opts ) throws PiliException { String path = baseUrl + "/saveas" ; String json = gson . toJson ( opts ) ; try { String resp = cli . callWithJson ( path , json ) ; SaveRet ret = gson . fromJson ( resp , SaveRet . class ) ; return ret . fname ; } catch ( PiliException e ) { throw e ; } catch ( Exception e ) { throw new PiliException ( e ) ; } } | save playback with more options |
6,666 | public String snapshot ( SnapshotOptions opts ) throws PiliException { String path = baseUrl + "/snapshot" ; String json = gson . toJson ( opts ) ; try { String resp = cli . callWithJson ( path , json ) ; SnapshotRet ret = gson . fromJson ( resp , SnapshotRet . class ) ; return ret . fname ; } catch ( PiliException e ) { throw e ; } catch ( Exception e ) { throw new PiliException ( e ) ; } } | snapshot the live stream |
6,667 | public void updateConverts ( String [ ] profiles ) throws PiliException { String path = baseUrl + "/converts" ; String json = gson . toJson ( new ConvertsOptions ( profiles ) ) ; try { cli . callWithJson ( path , json ) ; } catch ( PiliException e ) { throw e ; } catch ( Exception e ) { throw new PiliException ( e ) ; } } | update convert configs |
6,668 | public Record [ ] historyRecord ( long start , long end ) throws PiliException { String path = appendQuery ( baseUrl + "/historyrecord" , start , end ) ; try { String resp = cli . callWithGet ( path ) ; HistoryRet ret = gson . fromJson ( resp , HistoryRet . class ) ; return ret . items ; } catch ( PiliException e ) { throw e ; } catch ( Exception e ) { throw new PiliException ( e ) ; } } | query the stream history |
6,669 | public String toXML ( ) { Error error = getError ( ) ; if ( error != null ) { return error . toXML ( ) ; } StringWriter sw = new StringWriter ( ) ; String xml = "" ; try { JAXBContext context = JAXBContext . newInstance ( this . getClass ( ) ) ; Marshaller marshaller = context . createMarshaller ( ) ; marshaller . marshal ( this , sw ) ; xml = sw . toString ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return xml ; } | Map a Token instance to its XML representation . |
6,670 | public OneTouchResponse sendApprovalRequest ( ApprovalRequestParams approvalRequestParams ) throws AuthyException { JSONObject params = new JSONObject ( ) ; params . put ( "message" , approvalRequestParams . getMessage ( ) ) ; if ( approvalRequestParams . getSecondsToExpire ( ) != null ) { params . put ( "seconds_to_expire" , approvalRequestParams . getSecondsToExpire ( ) ) ; } if ( approvalRequestParams . getDetails ( ) . size ( ) > 0 ) { params . put ( "details" , mapToJSONObject ( approvalRequestParams . getDetails ( ) ) ) ; } if ( approvalRequestParams . getHidden ( ) . size ( ) > 0 ) { params . put ( "hidden_details" , mapToJSONObject ( approvalRequestParams . getHidden ( ) ) ) ; } if ( ! approvalRequestParams . getLogos ( ) . isEmpty ( ) ) { JSONArray jSONArray = new JSONArray ( ) ; for ( Logo logo : approvalRequestParams . getLogos ( ) ) { logo . addToMap ( jSONArray ) ; } params . put ( "logos" , jSONArray ) ; } final Response response = this . post ( APPROVAL_REQUEST_PRE + approvalRequestParams . getAuthyId ( ) + APPROVAL_REQUEST_POS , new JSONBody ( params ) ) ; OneTouchResponse oneTouchResponse = new OneTouchResponse ( response . getStatus ( ) , response . getBody ( ) ) ; if ( ! oneTouchResponse . isOk ( ) ) { oneTouchResponse . setError ( errorFromJson ( response . getBody ( ) ) ) ; } return oneTouchResponse ; } | Sends the OneTouch s approval request to the Authy servers and returns the OneTouchResponse that comes back . |
6,671 | public UserStatus requestStatus ( int userId ) throws AuthyException { final Response response = this . get ( String . format ( USER_STATUS_PATH , userId ) , null ) ; UserStatus userStatus = userStatusFromJson ( response ) ; return userStatus ; } | Get user status . |
6,672 | protected void doExecute ( Task task , TermsByQueryRequest request , ActionListener < TermsByQueryResponse > listener ) { request . nowInMillis ( System . currentTimeMillis ( ) ) ; super . doExecute ( task , request , listener ) ; } | Executes the actions . |
6,673 | protected GroupShardsIterator shards ( ClusterState clusterState , TermsByQueryRequest request , String [ ] concreteIndices ) { Map < String , Set < String > > routingMap = indexNameExpressionResolver . resolveSearchRouting ( clusterState , request . routing ( ) , request . indices ( ) ) ; return clusterService . operationRouting ( ) . searchShards ( clusterState , concreteIndices , routingMap , request . preference ( ) ) ; } | The shards this request will execute against . |
6,674 | public ActionRequestValidationException validate ( ) { ActionRequestValidationException validationException = super . validate ( ) ; if ( termsEncoding != null && termsEncoding . equals ( TermsEncoding . BYTES ) ) { if ( maxTermsPerShard == null ) { validationException = ValidateActions . addValidationError ( "maxTermsPerShard not specified for terms encoding [bytes]" , validationException ) ; } } return validationException ; } | Validates the request |
6,675 | public long getVersion ( ) { long version = 1 ; ArrayList < String > indices = new ArrayList < > ( getIndices ( ) . keySet ( ) ) ; Collections . sort ( indices ) ; for ( String index : indices ) { version = 31 * version + getIndices ( ) . get ( index ) ; } return version ; } | Returns the version for the set of indices . |
6,676 | public Map < String , Long > getIndices ( ) { if ( indicesVersions != null ) { return indicesVersions ; } Map < String , Long > indicesVersions = Maps . newHashMap ( ) ; Set < String > indices = Sets . newHashSet ( ) ; for ( ShardIndexVersion shard : shards ) { indices . add ( shard . getShardRouting ( ) . getIndex ( ) ) ; } for ( String index : indices ) { List < ShardIndexVersion > shards = new ArrayList < > ( ) ; for ( ShardIndexVersion shard : this . shards ) { if ( shard . getShardRouting ( ) . index ( ) . equals ( index ) ) { shards . add ( shard ) ; } } indicesVersions . put ( index , this . getIndexVersion ( shards ) ) ; } this . indicesVersions = indicesVersions ; return indicesVersions ; } | Returns a map with the version of each index . |
6,677 | private long getIndexVersion ( List < ShardIndexVersion > shards ) { long version = 1 ; Collections . sort ( shards , new Comparator < ShardIndexVersion > ( ) { public int compare ( ShardIndexVersion o1 , ShardIndexVersion o2 ) { return o1 . getShardRouting ( ) . id ( ) - o2 . getShardRouting ( ) . id ( ) ; } } ) ; for ( ShardIndexVersion shard : shards ) { version = 31 * version + shard . getVersion ( ) ; } return version ; } | Computes a unique hash based on the version of the shards . |
6,678 | public void execute ( NodeTaskContext context ) { NodeTaskReporter taskReporter = new NodeTaskReporter ( this ) ; taskQueue = new ArrayDeque < > ( tasks ) ; if ( ! taskQueue . isEmpty ( ) ) { NodeTask task = taskQueue . poll ( ) ; task . execute ( context , taskReporter ) ; } else { listener . onSuccess ( ) ; } } | Starts the execution of the pipeline |
6,679 | public void put ( final long cacheKey , final FilterJoinTerms terms ) { logger . debug ( "{}: New cache entry {}" , Thread . currentThread ( ) . getName ( ) , cacheKey ) ; this . cache . put ( cacheKey , new CacheEntry ( terms . getEncodedTerms ( ) , terms . getSize ( ) , terms . isPruned ( ) ) ) ; } | Caches the provided list of encoded terms for the given filter join node . |
6,680 | public TransportRequestOptions transportOptions ( Settings settings ) { return TransportRequestOptions . builder ( ) . withType ( TransportRequestOptions . Type . REG ) . build ( ) ; } | Set transport options specific to a terms by query request . Enabling compression here does not really reduce data transfer even increase it on the contrary . |
6,681 | private void await ( ) { try { boolean nodeRemoved = this . removeConvertedNodes ( root ) ; if ( ! nodeRemoved && root . hasChildren ( ) ) { logger . debug ( "Visitor thread block - blocking queue size: {}" , blockingQueue . size ( ) ) ; this . blockingQueue . take ( ) ; this . blockingQueue . offer ( 0 ) ; logger . debug ( "Visitor thread unblock - blocking queue size: {}" , blockingQueue . size ( ) ) ; } } catch ( InterruptedException e ) { logger . warn ( "Filter join visitor thread interrupted while waiting" ) ; Thread . currentThread ( ) . interrupt ( ) ; } } | Await for the completion of an async action . |
6,682 | private boolean removeConvertedNodes ( AbstractNode node ) { boolean nodeRemoved = false ; Iterator < AbstractNode > it = node . getChildren ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { FilterJoinNode child = ( FilterJoinNode ) it . next ( ) ; if ( child . getState ( ) . equals ( FilterJoinNode . State . CONVERTED ) ) { it . remove ( ) ; nodeRemoved |= true ; } else { nodeRemoved |= this . removeConvertedNodes ( child ) ? true : false ; } } return nodeRemoved ; } | Removes all the filter join leaf nodes that were converted . Returns true if at least one node has been removed . |
6,683 | protected void executeAsyncOperation ( final FilterJoinNode node ) { logger . debug ( "Executing async actions" ) ; node . setState ( FilterJoinNode . State . RUNNING ) ; NodePipelineManager pipeline = new NodePipelineManager ( ) ; pipeline . addListener ( new NodePipelineListener ( ) { public void onSuccess ( ) { node . setState ( FilterJoinNode . State . COMPLETED ) ; FilterJoinVisitor . this . unblock ( ) ; } public void onFailure ( Throwable e ) { node . setFailure ( e ) ; node . setState ( FilterJoinNode . State . COMPLETED ) ; FilterJoinVisitor . this . unblock ( ) ; } } ) ; pipeline . addTask ( new IndicesVersionTask ( ) ) ; pipeline . addTask ( new CacheLookupTask ( ) ) ; pipeline . addTask ( new CardinalityEstimationTask ( ) ) ; pipeline . addTask ( new TermsByQueryTask ( ) ) ; pipeline . execute ( new NodeTaskContext ( client , node , this ) ) ; } | Executes the pipeline of async actions to compute the terms for this node . |
6,684 | private void checkForFailure ( FilterJoinNode node ) { if ( node . hasFailure ( ) ) { logger . error ( "Node processing failed: {}" , node . getFailure ( ) ) ; throw new ElasticsearchException ( "Unexpected failure while processing a node" , node . getFailure ( ) ) ; } } | Checks for an action failure |
6,685 | private void convertToTermsQuery ( FilterJoinNode node ) { Map < String , Object > parent = node . getParentSourceMap ( ) ; FilterJoinTerms terms = node . getTerms ( ) ; BytesRef bytes = terms . getEncodedTerms ( ) ; parent . remove ( FilterJoinBuilder . NAME ) ; Map < String , Object > queryParams = new HashMap < > ( ) ; queryParams . put ( "value" , bytes . bytes ) ; queryParams . put ( "_cache_key" , node . getCacheId ( ) ) ; Map < String , Object > field = new HashMap < > ( ) ; field . put ( node . getField ( ) , queryParams ) ; Map < String , Object > termsQuery = new HashMap < > ( ) ; if ( node . getTermsEncoding ( ) . equals ( TermsByQueryRequest . TermsEncoding . BYTES ) ) { termsQuery . put ( TermsEnumTermsQueryParser . NAME , field ) ; } else { termsQuery . put ( FieldDataTermsQueryParser . NAME , field ) ; } Map < String , Object > constantScoreQueryParams = new HashMap < > ( ) ; constantScoreQueryParams . put ( "filter" , termsQuery ) ; parent . put ( ConstantScoreQueryParser . NAME , constantScoreQueryParams ) ; node . setState ( FilterJoinNode . State . CONVERTED ) ; this . blockingQueue . poll ( ) ; } | Converts a filter join into a terms query . |
6,686 | protected synchronized NumericTermsSet getTermsSet ( ) { if ( encodedTerms != null ) { long start = System . nanoTime ( ) ; termsSet = ( NumericTermsSet ) TermsSet . readFrom ( new BytesRef ( encodedTerms ) ) ; logger . debug ( "{}: Deserialized {} terms - took {} ms" , new Object [ ] { Thread . currentThread ( ) . getName ( ) , termsSet . size ( ) , ( System . nanoTime ( ) - start ) / 1000000 } ) ; encodedTerms = null ; } return termsSet ; } | Returns the set of terms . This method will perform a late - decoding of the encoded terms and will release the byte array . This method needs to be synchronized as each segment thread will call it concurrently . |
6,687 | protected final int nullCheck ( int id , int s ) { int k = stk ; while ( true ) { k -- ; StackEntry e = stack [ k ] ; if ( e . type == NULL_CHECK_START ) { if ( e . getNullCheckNum ( ) == id ) { return e . getNullCheckPStr ( ) == s ? 1 : 0 ; } } } } | int for consistency with other null check routines |
6,688 | private final int fetchNameForNoNamedGroup ( int startCode , boolean ref ) { int src = p ; value = 0 ; int sign = 1 ; int endCode = nameEndCodePoint ( startCode ) ; int pnumHead = p ; int nameEnd = stop ; String err = null ; if ( ! left ( ) ) { newValueException ( EMPTY_GROUP_NAME ) ; } else { fetch ( ) ; if ( c == endCode ) newValueException ( EMPTY_GROUP_NAME ) ; if ( enc . isDigit ( c ) ) { } else if ( c == '-' ) { sign = - 1 ; pnumHead = p ; } else { err = INVALID_CHAR_IN_GROUP_NAME ; } } while ( left ( ) ) { nameEnd = p ; fetch ( ) ; if ( c == endCode || c == ')' ) break ; if ( ! enc . isDigit ( c ) ) err = INVALID_CHAR_IN_GROUP_NAME ; } if ( err == null && c != endCode ) { err = INVALID_GROUP_NAME ; nameEnd = stop ; } if ( err == null ) { mark ( ) ; p = pnumHead ; int backNum = scanUnsignedNumber ( ) ; restore ( ) ; if ( backNum < 0 ) { newValueException ( TOO_BIG_NUMBER ) ; } else if ( backNum == 0 ) { newValueException ( INVALID_GROUP_NAME , src , nameEnd ) ; } backNum *= sign ; value = nameEnd ; return backNum ; } else { newValueException ( err , src , nameEnd ) ; return 0 ; } } | make it return nameEnd! |
6,689 | public EthereumTransaction getEthereumTransactionFromObject ( Object row ) { EthereumTransaction result = null ; if ( row instanceof HiveEthereumTransaction ) { result = EthereumUDFUtil . convertToEthereumTransaction ( ( HiveEthereumTransaction ) row ) ; } else { StructField nonceSF = soi . getStructFieldRef ( "nonce" ) ; StructField valueSF = soi . getStructFieldRef ( "valueRaw" ) ; StructField receiveAddressSF = soi . getStructFieldRef ( "receiveAddress" ) ; StructField gasPriceSF = soi . getStructFieldRef ( "gasPriceRaw" ) ; StructField gasLimitSF = soi . getStructFieldRef ( "gasLimitRaw" ) ; StructField dataSF = soi . getStructFieldRef ( "data" ) ; StructField sigVSF = soi . getStructFieldRef ( "sig_v" ) ; StructField sigRSF = soi . getStructFieldRef ( "sig_r" ) ; StructField sigSSF = soi . getStructFieldRef ( "sig_s" ) ; boolean baseNull = ( nonceSF == null ) || ( valueSF == null ) || ( receiveAddressSF == null ) ; boolean gasDataNull = ( gasPriceSF == null ) || ( gasLimitSF == null ) || ( dataSF == null ) ; boolean sigNull = ( sigVSF == null ) || ( sigRSF == null ) || ( sigSSF == null ) ; if ( baseNull || gasDataNull || sigNull ) { LOG . error ( "Structure does not correspond to EthereumTransaction. You need the fields nonce, valueRaw, reciveAddress, gasPriceRaw, gasLimitRaw, data, sig_v, sig_r, sig_s" ) ; return null ; } byte [ ] nonce = ( byte [ ] ) soi . getStructFieldData ( row , nonceSF ) ; byte [ ] valueRaw = ( byte [ ] ) soi . getStructFieldData ( row , valueSF ) ; byte [ ] receiveAddress = ( byte [ ] ) soi . getStructFieldData ( row , receiveAddressSF ) ; byte [ ] gasPriceRaw = ( byte [ ] ) soi . getStructFieldData ( row , gasPriceSF ) ; byte [ ] gasLimitRaw = ( byte [ ] ) soi . getStructFieldData ( row , gasLimitSF ) ; byte [ ] data = ( byte [ ] ) soi . getStructFieldData ( row , dataSF ) ; byte [ ] sig_v = ( byte [ ] ) soi . getStructFieldData ( row , sigVSF ) ; byte [ ] sig_r = ( byte [ ] ) soi . getStructFieldData ( row , sigRSF ) ; byte [ ] sig_s = ( byte [ ] ) soi . getStructFieldData ( row , sigSSF ) ; result = new EthereumTransaction ( ) ; result . setNonce ( nonce ) ; result . setValueRaw ( valueRaw ) ; result . setReceiveAddress ( receiveAddress ) ; result . setGasPriceRaw ( gasPriceRaw ) ; result . setGasLimitRaw ( gasLimitRaw ) ; result . setData ( data ) ; result . setSig_v ( sig_v ) ; result . setSig_r ( sig_r ) ; result . setSig_s ( sig_s ) ; } return result ; } | Create an object of type EthereumTransaction from any HiveTable |
6,690 | public static EthereumTransaction convertToEthereumTransaction ( HiveEthereumTransaction transaction ) { EthereumTransaction result = new EthereumTransaction ( ) ; result . setNonce ( transaction . getNonce ( ) ) ; result . setValueRaw ( transaction . getValueRaw ( ) ) ; result . setReceiveAddress ( transaction . getReceiveAddress ( ) ) ; result . setGasPriceRaw ( transaction . getGasPriceRaw ( ) ) ; result . setGasLimitRaw ( transaction . getGasLimitRaw ( ) ) ; result . setData ( transaction . getData ( ) ) ; result . setSig_v ( transaction . getSig_v ( ) ) ; result . setSig_r ( transaction . getSig_r ( ) ) ; result . setSig_s ( transaction . getSig_s ( ) ) ; return result ; } | Convert HiveEthereumTransaction to Ethereum Transaction |
6,691 | public static long getSize ( byte [ ] byteSize ) { if ( byteSize . length != 4 ) { return 0 ; } ByteBuffer converterBuffer = ByteBuffer . wrap ( byteSize ) ; converterBuffer . order ( ByteOrder . LITTLE_ENDIAN ) ; return convertSignedIntToUnsigned ( converterBuffer . getInt ( ) ) ; } | Reads a size from a reversed byte order such as block size in the block header |
6,692 | public static byte [ ] reverseByteArray ( byte [ ] inputByteArray ) { byte [ ] result = new byte [ inputByteArray . length ] ; for ( int i = inputByteArray . length - 1 ; i >= 0 ; i -- ) { result [ result . length - 1 - i ] = inputByteArray [ i ] ; } return result ; } | Reverses the order of the byte array |
6,693 | public static boolean compareMagics ( byte [ ] magic1 , byte [ ] magic2 ) { if ( magic1 . length != magic2 . length ) { return false ; } for ( int i = 0 ; i < magic1 . length ; i ++ ) { if ( magic1 [ i ] != magic2 [ i ] ) { return false ; } } return true ; } | Compares two Bitcoin magics |
6,694 | public static byte [ ] getTransactionHash ( BitcoinTransaction transaction ) throws IOException { ByteArrayOutputStream transactionBAOS = new ByteArrayOutputStream ( ) ; byte [ ] version = reverseByteArray ( convertIntToByteArray ( transaction . getVersion ( ) ) ) ; transactionBAOS . write ( version ) ; byte [ ] inCounter = transaction . getInCounter ( ) ; transactionBAOS . write ( inCounter ) ; for ( int i = 0 ; i < transaction . getListOfInputs ( ) . size ( ) ; i ++ ) { transactionBAOS . write ( transaction . getListOfInputs ( ) . get ( i ) . getPrevTransactionHash ( ) ) ; transactionBAOS . write ( reverseByteArray ( convertIntToByteArray ( ( int ) ( transaction . getListOfInputs ( ) . get ( i ) . getPreviousTxOutIndex ( ) ) ) ) ) ; transactionBAOS . write ( transaction . getListOfInputs ( ) . get ( i ) . getTxInScriptLength ( ) ) ; transactionBAOS . write ( transaction . getListOfInputs ( ) . get ( i ) . getTxInScript ( ) ) ; transactionBAOS . write ( reverseByteArray ( convertIntToByteArray ( ( int ) ( transaction . getListOfInputs ( ) . get ( i ) . getSeqNo ( ) ) ) ) ) ; } byte [ ] outCounter = transaction . getOutCounter ( ) ; transactionBAOS . write ( outCounter ) ; for ( int j = 0 ; j < transaction . getListOfOutputs ( ) . size ( ) ; j ++ ) { transactionBAOS . write ( convertBigIntegerToByteArray ( transaction . getListOfOutputs ( ) . get ( j ) . getValue ( ) , 8 ) ) ; transactionBAOS . write ( transaction . getListOfOutputs ( ) . get ( j ) . getTxOutScriptLength ( ) ) ; transactionBAOS . write ( transaction . getListOfOutputs ( ) . get ( j ) . getTxOutScript ( ) ) ; } byte [ ] lockTime = reverseByteArray ( convertIntToByteArray ( transaction . getLockTime ( ) ) ) ; transactionBAOS . write ( lockTime ) ; byte [ ] transactionByteArray = transactionBAOS . toByteArray ( ) ; byte [ ] firstRoundHash ; byte [ ] secondRoundHash ; try { MessageDigest digest = MessageDigest . getInstance ( "SHA-256" ) ; firstRoundHash = digest . digest ( transactionByteArray ) ; secondRoundHash = digest . digest ( firstRoundHash ) ; } catch ( NoSuchAlgorithmException nsae ) { LOG . error ( nsae ) ; return new byte [ 0 ] ; } return secondRoundHash ; } | Calculates the double SHA256 - Hash of a transaction in little endian format . This could be used for certain analysis scenario where one want to investigate the referenced transaction used as an input for a Transaction . Furthermore it can be used as a unique identifier of the transaction |
6,695 | public static RLPObject rlpDecodeNextItem ( ByteBuffer bb ) { RLPObject result = null ; int objType = detectRLPObjectType ( bb ) ; switch ( objType ) { case EthereumUtil . RLP_OBJECTTYPE_ELEMENT : result = EthereumUtil . decodeRLPElement ( bb ) ; break ; case EthereumUtil . RLP_OBJECTTYPE_LIST : result = EthereumUtil . decodeRLPList ( bb ) ; break ; default : LOG . error ( "Unknown object type" ) ; } return result ; } | Read RLP data from a Byte Buffer . |
6,696 | public static int detectRLPObjectType ( ByteBuffer bb ) { bb . mark ( ) ; byte detector = bb . get ( ) ; int unsignedDetector = detector & 0xFF ; int result = EthereumUtil . RLP_OBJECTTYPE_INVALID ; if ( unsignedDetector <= 0x7f ) { result = EthereumUtil . RLP_OBJECTTYPE_ELEMENT ; } else if ( ( unsignedDetector >= 0x80 ) && ( unsignedDetector <= 0xb7 ) ) { result = EthereumUtil . RLP_OBJECTTYPE_ELEMENT ; } else if ( ( unsignedDetector >= 0xb8 ) && ( unsignedDetector <= 0xbf ) ) { result = EthereumUtil . RLP_OBJECTTYPE_ELEMENT ; } else if ( ( unsignedDetector >= 0xc0 ) && ( unsignedDetector <= 0xf7 ) ) { result = EthereumUtil . RLP_OBJECTTYPE_LIST ; } else if ( ( unsignedDetector >= 0xf8 ) && ( unsignedDetector <= 0xff ) ) { result = EthereumUtil . RLP_OBJECTTYPE_LIST ; } else { result = EthereumUtil . RLP_OBJECTTYPE_INVALID ; LOG . error ( "Invalid RLP object type. Internal error or not RLP Data" ) ; } bb . reset ( ) ; return result ; } | Detects the object type of an RLP encoded object . Note that it does not modify the read position in the ByteBuffer . |
6,697 | public static Long calculateChainId ( EthereumTransaction eTrans ) { Long result = null ; long rawResult = EthereumUtil . convertVarNumberToLong ( new RLPElement ( new byte [ 0 ] , eTrans . getSig_v ( ) ) ) ; if ( ! ( ( rawResult == EthereumUtil . LOWER_REAL_V ) || ( rawResult == ( LOWER_REAL_V + 1 ) ) ) ) { result = ( rawResult - EthereumUtil . CHAIN_ID_INC ) / 2 ; } return result ; } | Calculates the chain Id |
6,698 | public static Short convertToByte ( RLPElement rpe ) { Short result = 0 ; if ( ( rpe . getRawData ( ) != null ) || ( rpe . getRawData ( ) . length == 1 ) ) { result = ( short ) ( rpe . getRawData ( ) [ 0 ] & 0xFF ) ; } return result ; } | Converts a byte in a RLPElement to byte |
6,699 | public static Integer convertToShort ( RLPElement rpe ) { Integer result = 0 ; byte [ ] rawBytes = rpe . getRawData ( ) ; if ( ( rawBytes != null ) ) { if ( rawBytes . length < EthereumUtil . WORD_SIZE ) { byte [ ] fullBytes = new byte [ EthereumUtil . WORD_SIZE ] ; int dtDiff = EthereumUtil . WORD_SIZE - rawBytes . length ; for ( int i = 0 ; i < rawBytes . length ; i ++ ) { fullBytes [ dtDiff + i ] = rawBytes [ i ] ; result = ( int ) ByteBuffer . wrap ( fullBytes ) . getShort ( ) & 0xFFFF ; } } else { result = ( int ) ByteBuffer . wrap ( rawBytes ) . getShort ( ) & 0xFFFF ; } } return result ; } | Converts a short in a RLPElement to short |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.