idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
38,500
public void stop ( int restartableId ) { requested . remove ( ( Integer ) restartableId ) ; Subscription subscription = restartableSubscriptions . get ( restartableId ) ; if ( subscription != null ) subscription . unsubscribe ( ) ; }
Unsubscribes a restartable
53
7
38,501
public boolean isUnsubscribed ( int restartableId ) { Subscription subscription = restartableSubscriptions . get ( restartableId ) ; return subscription == null || subscription . isUnsubscribed ( ) ; }
Checks if a restartable is unsubscribed .
45
10
38,502
public Activity getActivity ( ) { Context context = getContext ( ) ; while ( ! ( context instanceof Activity ) && context instanceof ContextWrapper ) context = ( ( ContextWrapper ) context ) . getBaseContext ( ) ; if ( ! ( context instanceof Activity ) ) throw new IllegalStateException ( "Expected an activity context, ...
Returns the unwrapped activity of the view or throws an exception .
96
14
38,503
public void push ( Fragment fragment ) { Fragment top = peek ( ) ; if ( top != null ) { manager . beginTransaction ( ) . setCustomAnimations ( R . anim . enter_from_right , R . anim . exit_to_left , R . anim . enter_from_left , R . anim . exit_to_right ) . remove ( top ) . add ( containerId , fragment , indexToTag ( ma...
Pushes a fragment to the top of the stack .
160
11
38,504
public void replace ( Fragment fragment ) { manager . popBackStackImmediate ( null , FragmentManager . POP_BACK_STACK_INCLUSIVE ) ; manager . beginTransaction ( ) . replace ( containerId , fragment , indexToTag ( 0 ) ) . commit ( ) ; manager . executePendingTransactions ( ) ; }
Replaces stack contents with just one fragment .
72
9
38,505
@ SuppressWarnings ( "unchecked" ) public < T > T findCallback ( Fragment fragment , Class < T > callbackType ) { Fragment back = getBackFragment ( fragment ) ; if ( back != null && callbackType . isAssignableFrom ( back . getClass ( ) ) ) return ( T ) back ; if ( callbackType . isAssignableFrom ( activity . getClass (...
Returns a back fragment if the fragment is of given class . If such fragment does not exist and activity implements the given class then the activity will be returned .
102
31
38,506
public void setCoilStatus ( int index , boolean b ) { if ( index < 0 ) { throw new IllegalArgumentException ( index + " < 0" ) ; } if ( index > coils . size ( ) ) { throw new IndexOutOfBoundsException ( index + " > " + coils . size ( ) ) ; } coils . setBit ( index , b ) ; }
Sets the status of the given coil .
82
9
38,507
private boolean responseIsInValid ( ) { if ( response == null ) { return true ; } else if ( ! response . isHeadless ( ) && validityCheck ) { return request . getTransactionID ( ) != response . getTransactionID ( ) ; } else { return false ; } }
Returns true if the response is not valid This can be if the response is null or the transaction ID of the request doesn t match the reponse
61
29
38,508
ModbusResponse updateResponseWithHeader ( ModbusResponse response , boolean ignoreFunctionCode ) { // transfer header data response . setHeadless ( isHeadless ( ) ) ; if ( ! isHeadless ( ) ) { response . setTransactionID ( getTransactionID ( ) ) ; response . setProtocolID ( getProtocolID ( ) ) ; } else { response . set...
Updates the response with the header information to match the request
125
12
38,509
public synchronized byte [ ] getBufferBytes ( ) { byte [ ] dest = new byte [ count ] ; System . arraycopy ( buf , 0 , dest , 0 , dest . length ) ; return dest ; }
Returns the underlying data being read .
44
7
38,510
public void initPool ( String name ) { running = true ; for ( int i = size ; -- i >= 0 ; ) { PoolThread thread = new PoolThread ( ) ; threadPool . add ( thread ) ; thread . setName ( String . format ( "%s Handler" , name ) ) ; thread . start ( ) ; } }
Initializes the pool populating it with n started threads .
71
12
38,511
public void close ( ) { if ( running ) { taskPool . clear ( ) ; running = false ; for ( PoolThread thread : threadPool ) { thread . interrupt ( ) ; } } }
Shutdown the pool of threads
41
6
38,512
public synchronized void setReconnecting ( boolean b ) { reconnecting = b ; if ( transaction != null ) { ( ( ModbusTCPTransaction ) transaction ) . setReconnecting ( b ) ; } }
Sets the flag that specifies whether to maintain a constant connection or reconnect for every transaction .
47
18
38,513
public void readData ( DataInput din ) throws IOException { // skip all following bytes int length = getDataLength ( ) ; for ( int i = 0 ; i < length ; i ++ ) { din . readByte ( ) ; } }
Read all of the data that can be read . This is an unsupported function so it may not be possible to know exactly how much data needs to be read .
51
32
38,514
public void setEncoding ( String enc ) { if ( ! ModbusUtil . isBlank ( enc ) && ( enc . equalsIgnoreCase ( Modbus . SERIAL_ENCODING_ASCII ) || enc . equalsIgnoreCase ( Modbus . SERIAL_ENCODING_RTU ) ) ) { encoding = enc ; } else { encoding = Modbus . DEFAULT_SERIAL_ENCODING ; } }
Sets the encoding to be used .
94
8
38,515
void checkValidity ( ) throws ModbusException { if ( request != null && response != null ) { if ( request . getUnitID ( ) != response . getUnitID ( ) ) { throw new ModbusIOException ( "Unit ID mismatch - Request [%s] Response [%s]" , request . getHexMessage ( ) , response . getHexMessage ( ) ) ; } if ( request . getFun...
Checks the validity of the transaction by checking if the values of the response correspond to the values of the request .
148
23
38,516
public void toByteArray ( byte [ ] toBuf , int offset ) { int toLen = ( toBuf . length > count ) ? count : toBuf . length ; System . arraycopy ( buf , offset , toBuf , offset , toLen - offset ) ; }
Copy the buffered data to the given array .
61
10
38,517
public void makeSpace ( int sizeNeeded ) { int needed = count + sizeNeeded - buf . length ; if ( needed > 0 ) { bump ( needed ) ; } }
Ensure that at least the given number of bytes are available in the internal buffer .
38
17
38,518
private void readRequestData ( int byteCount , BytesOutputStream out ) throws IOException { byteCount += 2 ; byte inpBuf [ ] = new byte [ byteCount ] ; readBytes ( inpBuf , byteCount ) ; out . write ( inpBuf , 0 , byteCount ) ; }
Read the data for a request of a given fixed size
68
11
38,519
private void getRequest ( int function , BytesOutputStream out ) throws IOException { int byteCount ; byte inpBuf [ ] = new byte [ 256 ] ; try { if ( ( function & 0x80 ) == 0 ) { switch ( function ) { case Modbus . READ_EXCEPTION_STATUS : case Modbus . READ_COMM_EVENT_COUNTER : case Modbus . READ_COMM_EVENT_LOG : case ...
getRequest - Read a request after the unit and function code
511
12
38,520
protected void writeMessageOut ( ModbusMessage msg ) throws ModbusIOException { try { int len ; synchronized ( byteOutputStream ) { // first clear any input from the receive buffer to prepare // for the reply since RTU doesn't have message delimiters clearInput ( ) ; // write message to byte out byteOutputStream . rese...
Writes the Modbus message to the comms port
320
11
38,521
protected ModbusResponse readResponseIn ( ) throws ModbusIOException { boolean done ; ModbusResponse response ; int dlength ; try { do { // 1. read to function code, create request and read function // specific bytes synchronized ( byteInputStream ) { int uid = readByte ( ) ; if ( uid != - 1 ) { int fc = readByte ( ) ;...
readResponse - Read the bytes for the response from the slave .
598
13
38,522
public static synchronized ModbusSlave createUDPSlave ( InetAddress address , int port ) throws ModbusException { String key = ModbusSlaveType . UDP . getKey ( port ) ; if ( slaves . containsKey ( key ) ) { return slaves . get ( key ) ; } else { ModbusSlave slave = new ModbusSlave ( address , port , false ) ; slaves . ...
Creates a UDP modbus slave or returns the one already allocated to this port
98
16
38,523
public static synchronized ModbusSlave createSerialSlave ( SerialParameters serialParams ) throws ModbusException { ModbusSlave slave = null ; if ( serialParams == null ) { throw new ModbusException ( "Serial parameters are null" ) ; } else if ( ModbusUtil . isBlank ( serialParams . getPortName ( ) ) ) { throw new Modb...
Creates a serial modbus slave or returns the one already allocated to this port
249
16
38,524
public static void close ( ModbusSlave slave ) { if ( slave != null ) { slave . closeListener ( ) ; slaves . remove ( slave . getType ( ) . getKey ( slave . getPort ( ) ) ) ; } }
Closes this slave and removes it from the running list
51
11
38,525
public static ModbusSlave getSlave ( String port ) { return ModbusUtil . isBlank ( port ) ? null : slaves . get ( port ) ; }
Returns the running slave listening on the given serial port
37
10
38,526
public static synchronized ModbusSlave getSlave ( AbstractModbusListener listener ) { for ( ModbusSlave slave : slaves . values ( ) ) { if ( slave . getListener ( ) . equals ( listener ) ) { return slave ; } } return null ; }
Returns the running slave that utilises the give listener
57
10
38,527
public synchronized byte [ ] getBuffer ( ) { byte [ ] dest = new byte [ buf . length ] ; System . arraycopy ( buf , 0 , dest , 0 , dest . length ) ; return dest ; }
Returns the reference to the output buffer .
45
8
38,528
public void setBitCount ( int count ) { bitCount = count ; discretes = new BitVector ( count ) ; //set correct length, without counting unitid and fc setDataLength ( discretes . byteSize ( ) + 1 ) ; }
Sets the number of bits in this response .
55
10
38,529
public synchronized String [ ] getFields ( ) { String [ ] dest = new String [ fields . length ] ; System . arraycopy ( fields , 0 , dest , 0 , dest . length ) ; return dest ; }
Returns the array of strings that were read
46
8
38,530
public synchronized InputRegister [ ] getRegisters ( ) { InputRegister [ ] dest = new InputRegister [ registers . length ] ; System . arraycopy ( registers , 0 , dest , 0 , dest . length ) ; return dest ; }
Returns a reference to the array of input registers read .
49
11
38,531
public void setRegisters ( InputRegister [ ] registers ) { byteCount = registers . length * 2 ; setDataLength ( byteCount + 1 ) ; this . registers = Arrays . copyOf ( registers , registers . length ) ; }
Sets the entire block of registers for this response
50
10
38,532
private void open ( ) throws ModbusIOException { if ( commPort != null && ! commPort . isOpen ( ) ) { setTimeout ( timeout ) ; try { commPort . open ( ) ; } catch ( IOException e ) { throw new ModbusIOException ( String . format ( "Cannot open port %s - %s" , commPort . getDescriptivePortName ( ) , e . getMessage ( ) )...
Opens the port if it isn t already open
98
10
38,533
protected void readEcho ( int len ) throws IOException { byte echoBuf [ ] = new byte [ len ] ; int echoLen = commPort . readBytes ( echoBuf , len ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Echo: {}" , ModbusUtil . toHex ( echoBuf , 0 , echoLen ) ) ; } if ( echoLen != len ) { logger . debug ( "Error: Tra...
Reads the own message echo produced in RS485 Echo Mode within the given time frame .
124
18
38,534
protected int readByte ( ) throws IOException { if ( commPort != null && commPort . isOpen ( ) ) { byte [ ] buffer = new byte [ 1 ] ; int cnt = commPort . readBytes ( buffer , 1 ) ; if ( cnt != 1 ) { throw new IOException ( "Cannot read from serial port" ) ; } else { return buffer [ 0 ] & 0xff ; } } else { throw new IO...
Reads a byte from the comms port
110
9
38,535
void readBytes ( byte [ ] buffer , long bytesToRead ) throws IOException { if ( commPort != null && commPort . isOpen ( ) ) { int cnt = commPort . readBytes ( buffer , bytesToRead ) ; if ( cnt != bytesToRead ) { throw new IOException ( "Cannot read from serial port - truncated" ) ; } } else { throw new IOException ( "C...
Reads the specified number of bytes from the input stream
102
11
38,536
final int writeBytes ( byte [ ] buffer , long bytesToWrite ) throws IOException { if ( commPort != null && commPort . isOpen ( ) ) { return commPort . writeBytes ( buffer , bytesToWrite ) ; } else { throw new IOException ( "Comm port is not valid or not open" ) ; } }
Writes the bytes to the output stream
71
8
38,537
int readAsciiByte ( ) throws IOException { if ( commPort != null && commPort . isOpen ( ) ) { byte [ ] buffer = new byte [ 1 ] ; int cnt = commPort . readBytes ( buffer , 1 ) ; if ( cnt != 1 ) { throw new IOException ( "Cannot read from serial port" ) ; } else if ( buffer [ 0 ] == ' ' ) { return ModbusASCIITransport . ...
Reads an ascii byte from the input stream It handles the special start and end frame markers
353
20
38,538
int writeAsciiBytes ( byte [ ] buffer , long bytesToWrite ) throws IOException { if ( commPort != null && commPort . isOpen ( ) ) { int cnt = 0 ; for ( int i = 0 ; i < bytesToWrite ; i ++ ) { if ( writeAsciiByte ( buffer [ i ] ) != 2 ) { return cnt ; } cnt ++ ; } return cnt ; } else { throw new IOException ( "Comm port...
Writes an array of bytes out as a stream of ascii characters
113
15
38,539
void clearInput ( ) throws IOException { if ( commPort . bytesAvailable ( ) > 0 ) { int len = commPort . bytesAvailable ( ) ; byte buf [ ] = new byte [ len ] ; readBytes ( buf , len ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Clear input: {}" , ModbusUtil . toHex ( buf , 0 , len ) ) ; } } }
clearInput - Clear the input if characters are found in the input stream .
94
15
38,540
void waitBetweenFrames ( int transDelayMS , long lastTransactionTimestamp ) { // If a fixed delay has been set if ( transDelayMS > 0 ) { ModbusUtil . sleep ( transDelayMS ) ; } else { // Make use we have a gap of 3.5 characters between adjacent requests // We have to do the calculations here because it is possible that...
Injects a delay dependent on the last time we received a response or if a fixed delay has been specified
210
22
38,541
long getCharIntervalMicro ( double chars ) { // Make use we have a gap of 3.5 characters between adjacent requests // We have to do the calculations here because it is possible that the caller may have changed // the connection characteristics if they provided the connection instance return ( long ) chars * NS_IN_A_MS ...
Calculates an interval based on a set number of characters . Used for message timings .
129
19
38,542
boolean spinUntilBytesAvailable ( long waitTimeMicroSec ) { long start = System . nanoTime ( ) ; while ( availableBytes ( ) < 1 ) { long delta = System . nanoTime ( ) - start ; if ( delta > waitTimeMicroSec * 1000 ) { return false ; } } return true ; }
Spins until the timeout or the condition is met . This method will repeatedly poll the available bytes so it should not have any side effects .
67
28
38,543
public void open ( ) throws ModbusException { // Start the listener if it isn' already running if ( ! isRunning ) { try { listenerThread = new Thread ( listener ) ; listenerThread . start ( ) ; isRunning = true ; } catch ( Exception x ) { closeListener ( ) ; throw new ModbusException ( x . getMessage ( ) ) ; } } }
Opens the listener to service requests
79
7
38,544
@ SuppressWarnings ( "deprecation" ) void closeListener ( ) { if ( listener != null && listener . isListening ( ) ) { listener . stop ( ) ; // Wait until the listener says it has stopped, but don't wait forever int count = 0 ; while ( listenerThread != null && listenerThread . isAlive ( ) && count < 50 ) { ModbusUtil ....
Closes the listener of this slave
144
7
38,545
void handleRequest ( AbstractModbusTransport transport , AbstractModbusListener listener ) throws ModbusIOException { // Get the request from the transport. It will be processed // using an associated process image if ( transport == null ) { throw new ModbusIOException ( "No transport specified" ) ; } ModbusRequest req...
Reads the request checks it is valid and that the unit ID is ok and sends back a response
348
20
38,546
public ProcessImage getProcessImage ( int unitId ) { ModbusSlave slave = ModbusSlaveFactory . getSlave ( this ) ; if ( slave != null ) { return slave . getProcessImage ( unitId ) ; } return null ; }
Returns the related process image for this listener and Unit Id
54
11
38,547
private static byte calculateLRC ( byte [ ] data , int off , int length , int tailskip ) { int lrc = 0 ; for ( int i = off ; i < length - tailskip ; i ++ ) { lrc += ( ( int ) data [ i ] ) & 0xFF ; } return ( byte ) ( ( - lrc ) & 0xff ) ; }
Calculates a LRC checksum
83
8
38,548
public BitVector readCoils ( int unitId , int ref , int count ) throws ModbusException { checkTransaction ( ) ; if ( readCoilsRequest == null ) { readCoilsRequest = new ReadCoilsRequest ( ) ; } readCoilsRequest . setUnitID ( unitId ) ; readCoilsRequest . setReference ( ref ) ; readCoilsRequest . setBitCount ( count ) ;...
Reads a given number of coil states from the slave .
144
12
38,549
public boolean writeCoil ( int unitId , int ref , boolean state ) throws ModbusException { checkTransaction ( ) ; if ( writeCoilRequest == null ) { writeCoilRequest = new WriteCoilRequest ( ) ; } writeCoilRequest . setUnitID ( unitId ) ; writeCoilRequest . setReference ( ref ) ; writeCoilRequest . setCoil ( state ) ; t...
Writes a coil state to the slave .
126
9
38,550
public void writeMultipleCoils ( int unitId , int ref , BitVector coils ) throws ModbusException { checkTransaction ( ) ; if ( writeMultipleCoilsRequest == null ) { writeMultipleCoilsRequest = new WriteMultipleCoilsRequest ( ) ; } writeMultipleCoilsRequest . setUnitID ( unitId ) ; writeMultipleCoilsRequest . setReferen...
Writes a given number of coil states to the slave .
113
12
38,551
public BitVector readInputDiscretes ( int unitId , int ref , int count ) throws ModbusException { checkTransaction ( ) ; if ( readInputDiscretesRequest == null ) { readInputDiscretesRequest = new ReadInputDiscretesRequest ( ) ; } readInputDiscretesRequest . setUnitID ( unitId ) ; readInputDiscretesRequest . setReferenc...
Reads a given number of input discrete states from the slave .
163
13
38,552
public InputRegister [ ] readInputRegisters ( int unitId , int ref , int count ) throws ModbusException { checkTransaction ( ) ; if ( readInputRegistersRequest == null ) { readInputRegistersRequest = new ReadInputRegistersRequest ( ) ; } readInputRegistersRequest . setUnitID ( unitId ) ; readInputRegistersRequest . set...
Reads a given number of input registers from the slave .
138
12
38,553
public Register [ ] readMultipleRegisters ( int unitId , int ref , int count ) throws ModbusException { checkTransaction ( ) ; if ( readMultipleRegistersRequest == null ) { readMultipleRegistersRequest = new ReadMultipleRegistersRequest ( ) ; } readMultipleRegistersRequest . setUnitID ( unitId ) ; readMultipleRegisters...
Reads a given number of registers from the slave .
137
11
38,554
public int writeSingleRegister ( int unitId , int ref , Register register ) throws ModbusException { checkTransaction ( ) ; if ( writeSingleRegisterRequest == null ) { writeSingleRegisterRequest = new WriteSingleRegisterRequest ( ) ; } writeSingleRegisterRequest . setUnitID ( unitId ) ; writeSingleRegisterRequest . set...
Writes a single register to the slave .
125
9
38,555
public int writeMultipleRegisters ( int unitId , int ref , Register [ ] registers ) throws ModbusException { checkTransaction ( ) ; if ( writeMultipleRegistersRequest == null ) { writeMultipleRegistersRequest = new WriteMultipleRegistersRequest ( ) ; } writeMultipleRegistersRequest . setUnitID ( unitId ) ; writeMultipl...
Writes a number of registers to the slave .
137
10
38,556
private ModbusResponse getAndCheckResponse ( ) throws ModbusException { ModbusResponse res = transaction . getResponse ( ) ; if ( res == null ) { throw new ModbusException ( "No response" ) ; } return res ; }
Reads the response from the transaction If there is no response then it throws an error
51
17
38,557
public static AbstractSerialConnection getCommPort ( String commPort ) { SerialConnection jSerialCommPort = new SerialConnection ( ) ; jSerialCommPort . serialPort = SerialPort . getCommPort ( commPort ) ; return jSerialCommPort ; }
Returns a JSerialComm implementation for the given comms port
53
12
38,558
public void attachNettyPromise ( Promise < T > promise ) { promise . addListener ( promiseHandler ) ; Promise < T > oldPromise = this . promise ; this . promise = promise ; if ( oldPromise != null ) { oldPromise . removeListener ( promiseHandler ) ; oldPromise . cancel ( true ) ; } }
Attach Netty Promise
73
4
38,559
public void addListener ( IsSimplePromiseResponseHandler < T > listener ) { if ( handlers == null ) { handlers = new LinkedList <> ( ) ; } handlers . add ( listener ) ; if ( response != null || exception != null ) { listener . onResponse ( this ) ; } }
Add a promise to do when Response comes in
64
9
38,560
protected void handlePromise ( Promise < T > promise ) { if ( ! promise . isSuccess ( ) ) { this . setException ( promise . cause ( ) ) ; } else { this . response = promise . getNow ( ) ; if ( handlers != null ) { for ( IsSimplePromiseResponseHandler < T > h : handlers ) { h . onResponse ( this ) ; } } } }
Handle the promise
85
3
38,561
protected void waitForPromiseSuccess ( ) throws IOException , TimeoutException { while ( ! promise . isDone ( ) && ! promise . isCancelled ( ) ) { Promise < T > listeningPromise = this . promise ; listeningPromise . awaitUninterruptibly ( ) ; if ( listeningPromise == this . promise ) { this . handlePromise ( promise ) ...
Wait for promise to be done
87
6
38,562
public void handleRetry ( Throwable cause ) { try { this . retryPolicy . retry ( connectionState , retryHandler , connectionFailHandler ) ; } catch ( RetryPolicy . RetryCancelled retryCancelled ) { this . getNettyPromise ( ) . setFailure ( cause ) ; } }
Handles a retry
71
5
38,563
public EtcdSelfStatsResponse getSelfStats ( ) { try { return new EtcdSelfStatsRequest ( this . client , retryHandler ) . send ( ) . get ( ) ; } catch ( IOException | EtcdException | EtcdAuthenticationException | TimeoutException e ) { return null ; } }
Get the Self Statistics of Etcd
66
7
38,564
public EtcdLeaderStatsResponse getLeaderStats ( ) { try { return new EtcdLeaderStatsRequest ( this . client , retryHandler ) . send ( ) . get ( ) ; } catch ( IOException | EtcdException | EtcdAuthenticationException | TimeoutException e ) { return null ; } }
Get the Leader Statistics of Etcd
66
7
38,565
public EtcdStoreStatsResponse getStoreStats ( ) { try { return new EtcdStoreStatsRequest ( this . client , retryHandler ) . send ( ) . get ( ) ; } catch ( IOException | EtcdException | EtcdAuthenticationException | TimeoutException e ) { return null ; } }
Get the Store Statistics of Etcd
66
7
38,566
public EtcdKeyPutRequest put ( String key , String value ) { return new EtcdKeyPutRequest ( client , key , retryHandler ) . value ( value ) ; }
Put a key with a value
38
6
38,567
public EtcdKeyPostRequest post ( String key , String value ) { return new EtcdKeyPostRequest ( client , key , retryHandler ) . value ( value ) ; }
Post a value to a key for in - order keys .
38
12
38,568
public static SslContext forKeystore ( String keystorePath , String keystorePassword ) throws SecurityContextException { return forKeystore ( keystorePath , keystorePassword , "SunX509" ) ; }
Builds SslContext using a protected keystore file . Adequate for non - mutual TLS connections .
45
22
38,569
public static SslContext forKeystoreAndTruststore ( InputStream keystore , String keystorePassword , InputStream truststore , String truststorePassword , String keyManagerAlgorithm ) throws SecurityContextException { try { final KeyStore ks = KeyStore . getInstance ( KEYSTORE_JKS ) ; final KeyStore ts = KeyStore . getI...
Builds SslContext using protected keystore and truststores overriding default key manger algorithm . Adequate for mutual TLS connections .
269
27
38,570
public < R > EtcdResponsePromise < R > send ( final EtcdRequest < R > etcdRequest ) throws IOException { ConnectionState connectionState = new ConnectionState ( uris , lastWorkingUriIndex ) ; if ( etcdRequest . getPromise ( ) == null ) { etcdRequest . setPromise ( new EtcdResponsePromise < R > ( etcdRequest . getRetryP...
Send a request and get a future .
158
8
38,571
private < R > void modifyPipeLine ( final EtcdRequest < R > req , final ChannelPipeline pipeline ) { final EtcdResponseHandler < R > handler = new EtcdResponseHandler <> ( this , req ) ; if ( req . hasTimeout ( ) ) { pipeline . addFirst ( new ReadTimeoutHandler ( req . getTimeout ( ) , req . getTimeoutUnit ( ) ) ) ; } ...
Modify the pipeline for the request
158
7
38,572
private < R > ChannelFuture createAndSendHttpRequest ( URI server , String uri , EtcdRequest < R > etcdRequest , Channel channel ) throws Exception { HttpRequest httpRequest = new DefaultHttpRequest ( HttpVersion . HTTP_1_1 , etcdRequest . getMethod ( ) , uri ) ; httpRequest . headers ( ) . add ( HttpHeaderNames . CONN...
Get HttpRequest belonging to etcdRequest
508
9
38,573
public EtcdKeyPutRequest refresh ( Integer ttl ) { this . requestParams . put ( "refresh" , "true" ) ; this . prevExist ( true ) ; return ttl ( ttl ) ; }
Set Time to live on a refresh request . Requires previous value to exist
49
14
38,574
public final void retry ( final ConnectionState state , final RetryHandler retryHandler , final ConnectionFailHandler failHandler ) throws RetryCancelled { if ( state . retryCount == 0 ) { state . msBeforeRetry = this . startRetryTime ; } state . retryCount ++ ; state . uriIndex = state . retryCount % state . uris . le...
Does the retry . Will always try all URIs before throwing an exception .
304
16
38,575
public EtcdNettyConfig setEventLoopGroup ( EventLoopGroup eventLoopGroup , boolean managed ) { if ( this . eventLoopGroup != null && this . managedEventLoopGroup ) { // if i manage it, close the old when new one come this . eventLoopGroup . shutdownGracefully ( ) ; } this . eventLoopGroup = eventLoopGroup ; this . mana...
Set a custom event loop group . For use within existing netty architectures
90
14
38,576
public static URI [ ] fromDNSName ( String srvName ) throws NamingException { List < URI > uris = new ArrayList <> ( ) ; Hashtable < String , String > env = new Hashtable <> ( ) ; env . put ( "java.naming.factory.initial" , "com.sun.jndi.dns.DnsContextFactory" ) ; env . put ( "java.naming.provider.url" , "dns:" ) ; Dir...
Convert given DNS SRV address to array of URIs
359
12
38,577
public void setSlf4jLogname ( String logName ) { // use length() == 0 instead of isEmpty() for Java 5 compatibility if ( logName . length ( ) == 0 ) { m_log = null ; } else { m_log = LoggerFactory . getLogger ( logName ) ; } }
Set the name of the logger that this logger should log to . If you set it to an empty string will shut up completely .
70
26
38,578
@ Override public void log ( StopWatch sw ) { // // This avoids calling the possibly expensive sw.toString() method if logging is disabled. // if ( m_log != null && m_log . isInfoEnabled ( ) ) { m_log . info ( sw . toString ( ) ) ; } }
Logs using the INFO priority .
67
7
38,579
@ Override public void log ( StopWatch sw ) { if ( ! m_queue . offer ( sw . freeze ( ) ) ) m_rejectedStopWatches . getAndIncrement ( ) ; if ( m_collectorThread == null ) { synchronized ( this ) { // // Ensure that there is no race condition starting the thread. // Note that under the JVM5 memory model this also require...
This method also starts the collector thread lazily .
178
10
38,580
private void rebuildJmx ( ) { m_mbeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; try { buildMBeanInfo ( ) ; // // Remove and reinstall from the MBean registry if it already exists. Also // remove previous instances. // ObjectName newName = getJMXName ( ) ; if ( m_mbeanServer . isRegistered ( newName ) ) {...
Rebuild the JMX bean .
316
7
38,581
private boolean emptyQueue ( long finalMoment ) { StopWatch sw ; try { while ( null != ( sw = m_queue . poll ( 100 , TimeUnit . MILLISECONDS ) ) ) { // Ignore faulty StopWatches if ( sw . getTag ( ) == null ) continue ; if ( sw . getCreationTime ( ) > finalMoment ) { // Return this one back in the queue; as it belongs ...
Empties the StopWatch queue and builds the statistics on the go . This is run in the Collector Thread context . Leaves the queue when the items in it start later than what we need .
411
39
38,582
private static void configure ( ) { String propertyFile = System . getProperty ( SYSTEM_PROPERTY , PROPERTYFILENAME ) ; InputStream in = findConfigFile ( propertyFile , "/com/ecyrd/speed4j/default_speed4j.properties" ) ; configure ( in ) ; }
Does the default configuration by trying to locate the default config file as defined in the System properties .
68
19
38,583
@ SuppressWarnings ( "unchecked" ) private static synchronized void configure ( InputStream in ) throws ConfigurationException { if ( c_factories == null ) c_factories = new HashMap < String , StopWatchFactory > ( ) ; try { c_config . load ( in ) ; } catch ( IOException e2 ) { throw new ConfigurationException ( e2 ) ; ...
Load configuration file try to parse it and do something useful .
406
12
38,584
public StopWatch getStopWatch ( String tag , String message ) { return new LoggingStopWatch ( m_log , tag , message ) ; }
Returns a StopWatch for the given tag and given message .
31
12
38,585
public static synchronized void shutdown ( ) { if ( c_factories == null ) return ; // Nothing to do for ( Iterator < Entry < String , StopWatchFactory > > i = c_factories . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry < String , StopWatchFactory > e = i . next ( ) ; StopWatchFactory swf = e . getValu...
Shut down all StopWatchFactories . This method is useful to call to clean up any resources which might be usable .
117
24
38,586
public static StopWatchFactory getInstance ( String loggerName ) throws ConfigurationException { StopWatchFactory swf = getFactories ( ) . get ( loggerName ) ; if ( swf == null ) throw new ConfigurationException ( "No logger by the name " + loggerName + " found." ) ; return swf ; }
Returns a StopWatchFactory that has been configured previously . May return null if the factory has not been configured .
67
22
38,587
public StopWatch stop ( String tag , String message ) { m_tag = tag ; m_message = message ; stop ( ) ; return this ; }
Stops the StopWatch assigns the tag and a free - form message .
32
15
38,588
private String getReadableTime ( ) { long ns = getTimeNanos ( ) ; if ( ns < 50L * 1000 ) return ns + " ns" ; if ( ns < 50L * 1000 * 1000 ) return ( ns / 1000 ) + " us" ; if ( ns < 50L * 1000 * 1000 * 1000 ) return ( ns / ( 1000 * 1000 ) ) + " ms" ; return ns / NANOS_IN_SECOND + " s" ; }
Returns a the time in something that is human - readable .
102
12
38,589
public synchronized void add ( StopWatch sw ) { double timeInMs = sw . getTimeMicros ( ) / MICROS_IN_MILLIS ; // let fake the array for ( int i = 0 ; i < sw . getCount ( ) ; i ++ ) m_times . ( timeInMs / sw . getCount ( ) ) ; if ( timeInMs < m_min ) m_min = timeInMs ; if ( timeInMs > m_max ) m_max = timeInMs ; }
Add a StopWatch to the statistics .
112
8
38,590
public PostBuilder withCategories ( Term ... terms ) { return withCategories ( Arrays . stream ( terms ) . map ( Term :: getId ) . collect ( toList ( ) ) ) ; }
Add existing Category term items when building a post .
43
10
38,591
public PostBuilder withTags ( Term ... tags ) { return withTags ( Arrays . stream ( tags ) . map ( Term :: getId ) . collect ( toList ( ) ) ) ; }
Add existing Tag term items when building a post .
41
10
38,592
public static E164PhoneNumberWithExtension ofPhoneNumberStringAndExtension ( String phoneNumber , String extension , CountryCode defaultCountryCode ) { return new E164PhoneNumberWithExtension ( phoneNumber , extension , defaultCountryCode ) ; }
Creates a new E164 Phone Number with the given extension .
52
13
38,593
@ SuppressWarnings ( "unchecked" ) public static final < C > FieldModel < C > get ( Field f , FieldAccess < C > fieldAccess ) { String fieldModelKey = ( fieldAccess . getClass ( ) . getSimpleName ( ) + ":" + f . getClass ( ) . getName ( ) + "#" + f . getName ( ) ) ; FieldModel < C > fieldModel = ( FieldModel < C > ) fi...
Returns a field model for the given Field and FieldAccess instance . If a FieldModel already exists it will be reused .
205
24
38,594
public boolean isImmutable ( Class < ? > clazz ) { if ( clazz . isPrimitive ( ) || clazz . isEnum ( ) ) { return false ; } if ( clazz . isArray ( ) ) { return false ; } final IsImmutable isImmutable ; if ( DETECTED_IMMUTABLE_CLASSES . containsKey ( clazz ) ) { isImmutable = DETECTED_IMMUTABLE_CLASSES . get ( clazz ) ; ...
Return true if immutable or effectively immutable
227
7
38,595
public static < E > Iterable < E > wrapEnumeration ( Enumeration < E > enumeration ) { return new IterableEnumeration < E > ( enumeration ) ; }
Typesafe factory method for construction convenience
41
7
38,596
public static BindingConfiguration load ( URL location ) throws IllegalStateException { Document doc ; try { doc = loadDocument ( location ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Cannot load " + location . toExternalForm ( ) , e ) ; } catch ( ParserConfigurationException e ) { throw new Illeg...
Given a configuration URL produce the corresponding configuration
141
8
38,597
private static Document loadDocument ( URL location ) throws IOException , ParserConfigurationException , SAXException { InputStream inputStream = null ; if ( location != null ) { URLConnection urlConnection = location . openConnection ( ) ; urlConnection . setUseCaches ( false ) ; inputStream = urlConnection . getInpu...
Helper method to load a DOM Document from the given configuration URL
283
12
38,598
private static DocumentBuilder constructDocumentBuilder ( List < SAXParseException > errors ) throws ParserConfigurationException { DocumentBuilderFactory documentBuilderFactory = constructDocumentBuilderFactory ( ) ; DocumentBuilder docBuilder = documentBuilderFactory . newDocumentBuilder ( ) ; docBuilder . setEntityR...
Helper used to construct a document builder
95
7
38,599
private static Provider parseProviderElement ( Element element ) { Class < ? > providerClass = lookupClass ( element . getAttribute ( "class" ) ) ; if ( providerClass == null ) { throw new IllegalStateException ( "Referenced class {" + element . getAttribute ( "class" ) + "} could not be found" ) ; } if ( ! ConverterPr...
Parse the provider element and its children
179
8