idx
int64 0
41.2k
| question
stringlengths 74
4.04k
| target
stringlengths 7
750
|
|---|---|---|
38,600
|
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
|
38,601
|
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: Transmit echo not received" ) ; throw new IOException ( "Echo not received" ) ; } }
|
Reads the own message echo produced in RS485 Echo Mode within the given time frame .
|
38,602
|
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 IOException ( "Comm port is not valid or not open" ) ; } }
|
Reads a byte from the comms port
|
38,603
|
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 ( "Comm port is not valid or not open" ) ; } }
|
Reads the specified number of bytes from the input stream
|
38,604
|
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
|
38,605
|
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 . FRAME_START ; } else if ( buffer [ 0 ] == '\r' || buffer [ 0 ] == '\n' ) { return ModbusASCIITransport . FRAME_END ; } else { logger . debug ( "Read From buffer: " + buffer [ 0 ] + " (" + String . format ( "%02X" , buffer [ 0 ] ) + ")" ) ; byte firstValue = buffer [ 0 ] ; cnt = commPort . readBytes ( buffer , 1 ) ; if ( cnt != 1 ) { throw new IOException ( "Cannot read from serial port" ) ; } else { logger . debug ( "Read From buffer: " + buffer [ 0 ] + " (" + String . format ( "%02X" , buffer [ 0 ] ) + ")" ) ; int combinedValue = ( Character . digit ( firstValue , 16 ) << 4 ) + Character . digit ( buffer [ 0 ] , 16 ) ; logger . debug ( "Returning combined value of: " + String . format ( "%02X" , combinedValue ) ) ; return combinedValue ; } } } else { throw new IOException ( "Comm port is not valid or not open" ) ; } }
|
Reads an ascii byte from the input stream It handles the special start and end frame markers
|
38,606
|
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 is not valid or not open" ) ; } }
|
Writes an array of bytes out as a stream of ascii characters
|
38,607
|
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 .
|
38,608
|
void waitBetweenFrames ( int transDelayMS , long lastTransactionTimestamp ) { if ( transDelayMS > 0 ) { ModbusUtil . sleep ( transDelayMS ) ; } else { int delay = getInterFrameDelay ( ) / 1000 ; long gapSinceLastMessage = ( System . nanoTime ( ) - lastTransactionTimestamp ) / NS_IN_A_MS ; if ( delay > gapSinceLastMessage ) { long sleepTime = delay - gapSinceLastMessage ; ModbusUtil . sleep ( sleepTime ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Waited between frames for {} ms" , sleepTime ) ; } } } }
|
Injects a delay dependent on the last time we received a response or if a fixed delay has been specified
|
38,609
|
long getCharIntervalMicro ( double chars ) { return ( long ) chars * NS_IN_A_MS * ( 1 + commPort . getNumDataBits ( ) + commPort . getNumStopBits ( ) + ( commPort . getParity ( ) == AbstractSerialConnection . NO_PARITY ? 0 : 1 ) ) / commPort . getBaudRate ( ) ; }
|
Calculates an interval based on a set number of characters . Used for message timings .
|
38,610
|
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 .
|
38,611
|
public void open ( ) throws ModbusException { 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
|
38,612
|
@ SuppressWarnings ( "deprecation" ) void closeListener ( ) { if ( listener != null && listener . isListening ( ) ) { listener . stop ( ) ; int count = 0 ; while ( listenerThread != null && listenerThread . isAlive ( ) && count < 50 ) { ModbusUtil . sleep ( 100 ) ; count ++ ; } if ( listenerThread != null && listenerThread . isAlive ( ) ) { listenerThread . stop ( ) ; } listenerThread = null ; } isRunning = false ; }
|
Closes the listener of this slave
|
38,613
|
void handleRequest ( AbstractModbusTransport transport , AbstractModbusListener listener ) throws ModbusIOException { if ( transport == null ) { throw new ModbusIOException ( "No transport specified" ) ; } ModbusRequest request = transport . readRequest ( listener ) ; if ( request == null ) { throw new ModbusIOException ( "Request for transport %s is invalid (null)" , transport . getClass ( ) . getSimpleName ( ) ) ; } ModbusResponse response ; ProcessImage spi = getProcessImage ( request . getUnitID ( ) ) ; if ( spi == null ) { response = request . createExceptionResponse ( Modbus . ILLEGAL_ADDRESS_EXCEPTION ) ; response . setAuxiliaryType ( ModbusResponse . AuxiliaryMessageTypes . UNIT_ID_MISSMATCH ) ; } else { response = request . createResponse ( this ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Request:{}" , request . getHexMessage ( ) ) ; if ( transport instanceof ModbusRTUTransport && response . getAuxiliaryType ( ) == AuxiliaryMessageTypes . UNIT_ID_MISSMATCH ) { logger . debug ( "Not sending response because it was not meant for us." ) ; } else { logger . debug ( "Response:{}" , response . getHexMessage ( ) ) ; } } transport . writeResponse ( response ) ; }
|
Reads the request checks it is valid and that the unit ID is ok and sends back a response
|
38,614
|
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
|
38,615
|
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
|
38,616
|
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 ) ; transaction . setRequest ( readCoilsRequest ) ; transaction . execute ( ) ; BitVector bv = ( ( ReadCoilsResponse ) getAndCheckResponse ( ) ) . getCoils ( ) ; bv . forceSize ( count ) ; return bv ; }
|
Reads a given number of coil states from the slave .
|
38,617
|
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 ) ; transaction . setRequest ( writeCoilRequest ) ; transaction . execute ( ) ; return ( ( WriteCoilResponse ) getAndCheckResponse ( ) ) . getCoil ( ) ; }
|
Writes a coil state to the slave .
|
38,618
|
public void writeMultipleCoils ( int unitId , int ref , BitVector coils ) throws ModbusException { checkTransaction ( ) ; if ( writeMultipleCoilsRequest == null ) { writeMultipleCoilsRequest = new WriteMultipleCoilsRequest ( ) ; } writeMultipleCoilsRequest . setUnitID ( unitId ) ; writeMultipleCoilsRequest . setReference ( ref ) ; writeMultipleCoilsRequest . setCoils ( coils ) ; transaction . setRequest ( writeMultipleCoilsRequest ) ; transaction . execute ( ) ; }
|
Writes a given number of coil states to the slave .
|
38,619
|
public BitVector readInputDiscretes ( int unitId , int ref , int count ) throws ModbusException { checkTransaction ( ) ; if ( readInputDiscretesRequest == null ) { readInputDiscretesRequest = new ReadInputDiscretesRequest ( ) ; } readInputDiscretesRequest . setUnitID ( unitId ) ; readInputDiscretesRequest . setReference ( ref ) ; readInputDiscretesRequest . setBitCount ( count ) ; transaction . setRequest ( readInputDiscretesRequest ) ; transaction . execute ( ) ; BitVector bv = ( ( ReadInputDiscretesResponse ) getAndCheckResponse ( ) ) . getDiscretes ( ) ; bv . forceSize ( count ) ; return bv ; }
|
Reads a given number of input discrete states from the slave .
|
38,620
|
public InputRegister [ ] readInputRegisters ( int unitId , int ref , int count ) throws ModbusException { checkTransaction ( ) ; if ( readInputRegistersRequest == null ) { readInputRegistersRequest = new ReadInputRegistersRequest ( ) ; } readInputRegistersRequest . setUnitID ( unitId ) ; readInputRegistersRequest . setReference ( ref ) ; readInputRegistersRequest . setWordCount ( count ) ; transaction . setRequest ( readInputRegistersRequest ) ; transaction . execute ( ) ; return ( ( ReadInputRegistersResponse ) getAndCheckResponse ( ) ) . getRegisters ( ) ; }
|
Reads a given number of input registers from the slave .
|
38,621
|
public Register [ ] readMultipleRegisters ( int unitId , int ref , int count ) throws ModbusException { checkTransaction ( ) ; if ( readMultipleRegistersRequest == null ) { readMultipleRegistersRequest = new ReadMultipleRegistersRequest ( ) ; } readMultipleRegistersRequest . setUnitID ( unitId ) ; readMultipleRegistersRequest . setReference ( ref ) ; readMultipleRegistersRequest . setWordCount ( count ) ; transaction . setRequest ( readMultipleRegistersRequest ) ; transaction . execute ( ) ; return ( ( ReadMultipleRegistersResponse ) getAndCheckResponse ( ) ) . getRegisters ( ) ; }
|
Reads a given number of registers from the slave .
|
38,622
|
public int writeSingleRegister ( int unitId , int ref , Register register ) throws ModbusException { checkTransaction ( ) ; if ( writeSingleRegisterRequest == null ) { writeSingleRegisterRequest = new WriteSingleRegisterRequest ( ) ; } writeSingleRegisterRequest . setUnitID ( unitId ) ; writeSingleRegisterRequest . setReference ( ref ) ; writeSingleRegisterRequest . setRegister ( register ) ; transaction . setRequest ( writeSingleRegisterRequest ) ; transaction . execute ( ) ; return ( ( WriteSingleRegisterResponse ) getAndCheckResponse ( ) ) . getRegisterValue ( ) ; }
|
Writes a single register to the slave .
|
38,623
|
public int writeMultipleRegisters ( int unitId , int ref , Register [ ] registers ) throws ModbusException { checkTransaction ( ) ; if ( writeMultipleRegistersRequest == null ) { writeMultipleRegistersRequest = new WriteMultipleRegistersRequest ( ) ; } writeMultipleRegistersRequest . setUnitID ( unitId ) ; writeMultipleRegistersRequest . setReference ( ref ) ; writeMultipleRegistersRequest . setRegisters ( registers ) ; transaction . setRequest ( writeMultipleRegistersRequest ) ; transaction . execute ( ) ; return ( ( WriteMultipleRegistersResponse ) transaction . getResponse ( ) ) . getWordCount ( ) ; }
|
Writes a number of registers to the slave .
|
38,624
|
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
|
38,625
|
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
|
38,626
|
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
|
38,627
|
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
|
38,628
|
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
|
38,629
|
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 ) ; break ; } } }
|
Wait for promise to be done
|
38,630
|
public void handleRetry ( Throwable cause ) { try { this . retryPolicy . retry ( connectionState , retryHandler , connectionFailHandler ) ; } catch ( RetryPolicy . RetryCancelled retryCancelled ) { this . getNettyPromise ( ) . setFailure ( cause ) ; } }
|
Handles a retry
|
38,631
|
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
|
38,632
|
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
|
38,633
|
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
|
38,634
|
public EtcdKeyPutRequest put ( String key , String value ) { return new EtcdKeyPutRequest ( client , key , retryHandler ) . value ( value ) ; }
|
Put a key with a value
|
38,635
|
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,636
|
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 .
|
38,637
|
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 . getInstance ( KEYSTORE_JKS ) ; final KeyManagerFactory keystoreKmf = KeyManagerFactory . getInstance ( keyManagerAlgorithm ) ; final TrustManagerFactory truststoreKmf = TrustManagerFactory . getInstance ( keyManagerAlgorithm ) ; ks . load ( keystore , keystorePassword . toCharArray ( ) ) ; ts . load ( truststore , truststorePassword . toCharArray ( ) ) ; keystoreKmf . init ( ks , keystorePassword . toCharArray ( ) ) ; truststoreKmf . init ( ts ) ; SslContextBuilder ctxBuilder = SslContextBuilder . forClient ( ) . keyManager ( keystoreKmf ) ; ctxBuilder . trustManager ( truststoreKmf ) ; return ctxBuilder . build ( ) ; } catch ( Exception e ) { throw new SecurityContextException ( e ) ; } }
|
Builds SslContext using protected keystore and truststores overriding default key manger algorithm . Adequate for mutual TLS connections .
|
38,638
|
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 . getRetryPolicy ( ) , connectionState , new RetryHandler ( ) { public void doRetry ( ConnectionState connectionState ) throws IOException { connect ( etcdRequest , connectionState ) ; } } ) ) ; } connect ( etcdRequest , connectionState ) ; return etcdRequest . getPromise ( ) ; }
|
Send a request and get a future .
|
38,639
|
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 ( ) ) ) ; } pipeline . addLast ( handler ) ; pipeline . addLast ( new ChannelHandlerAdapter ( ) { public void exceptionCaught ( ChannelHandlerContext ctx , Throwable cause ) throws Exception { handler . retried ( true ) ; req . getPromise ( ) . handleRetry ( cause ) ; } } ) ; }
|
Modify the pipeline for the request
|
38,640
|
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 . CONNECTION , "keep-alive" ) ; if ( ! this . config . hasHostName ( ) ) { httpRequest . headers ( ) . add ( HttpHeaderNames . HOST , server . getHost ( ) + ":" + server . getPort ( ) ) ; } else { httpRequest . headers ( ) . add ( HttpHeaderNames . HOST , this . config . getHostName ( ) ) ; } HttpPostRequestEncoder bodyRequestEncoder = null ; Map < String , String > keyValuePairs = etcdRequest . getRequestParams ( ) ; if ( keyValuePairs != null && ! keyValuePairs . isEmpty ( ) ) { HttpMethod etcdRequestMethod = etcdRequest . getMethod ( ) ; if ( etcdRequestMethod == HttpMethod . POST || etcdRequestMethod == HttpMethod . PUT ) { bodyRequestEncoder = new HttpPostRequestEncoder ( httpRequest , false ) ; for ( Map . Entry < String , String > entry : keyValuePairs . entrySet ( ) ) { bodyRequestEncoder . addBodyAttribute ( entry . getKey ( ) , entry . getValue ( ) ) ; } httpRequest = bodyRequestEncoder . finalizeRequest ( ) ; } else { QueryStringEncoder encoder = new QueryStringEncoder ( uri ) ; for ( Map . Entry < String , String > entry : keyValuePairs . entrySet ( ) ) { encoder . addParam ( entry . getKey ( ) , entry . getValue ( ) ) ; } httpRequest . setUri ( encoder . toString ( ) ) ; } } etcdRequest . setHttpRequest ( httpRequest ) ; ChannelFuture future = channel . write ( httpRequest ) ; if ( bodyRequestEncoder != null && bodyRequestEncoder . isChunked ( ) ) { future = channel . write ( bodyRequestEncoder ) ; } channel . flush ( ) ; return future ; }
|
Get HttpRequest belonging to etcdRequest
|
38,641
|
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
|
38,642
|
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 . length ; if ( this . shouldRetry ( state ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Retry {} to send command" , state . retryCount ) ; } if ( state . msBeforeRetry > 0 ) { try { state . loop . schedule ( new Runnable ( ) { public void run ( ) { try { retryHandler . doRetry ( state ) ; } catch ( IOException e ) { failHandler . catchException ( e ) ; } } } , state . msBeforeRetry , TimeUnit . MILLISECONDS ) ; } catch ( IllegalStateException e ) { failHandler . catchException ( new IOException ( new CancellationException ( "Etcd client was closed" ) ) ) ; } } else { try { retryHandler . doRetry ( state ) ; } catch ( IOException e ) { failHandler . catchException ( e ) ; } } } else { throw new RetryCancelled ( ) ; } }
|
Does the retry . Will always try all URIs before throwing an exception .
|
38,643
|
public EtcdNettyConfig setEventLoopGroup ( EventLoopGroup eventLoopGroup , boolean managed ) { if ( this . eventLoopGroup != null && this . managedEventLoopGroup ) { this . eventLoopGroup . shutdownGracefully ( ) ; } this . eventLoopGroup = eventLoopGroup ; this . managedEventLoopGroup = managed ; return this ; }
|
Set a custom event loop group . For use within existing netty architectures
|
38,644
|
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:" ) ; DirContext ctx = new InitialDirContext ( env ) ; Attributes attributes = ctx . getAttributes ( srvName , new String [ ] { "SRV" } ) ; NamingEnumeration < ? extends Attribute > records = attributes . getAll ( ) ; while ( records . hasMore ( ) ) { Attribute next = records . next ( ) ; @ SuppressWarnings ( "unchecked" ) NamingEnumeration < String > values = ( NamingEnumeration < String > ) next . getAll ( ) ; while ( values . hasMore ( ) ) { String dns = values . next ( ) ; String [ ] split = dns . split ( " " ) ; String port = split [ 2 ] ; String host = split [ 3 ] ; if ( host . endsWith ( "." ) ) { host = host . substring ( 0 , host . length ( ) - 1 ) ; } URI uri = URI . create ( "http://" + host + ":" + port ) ; uris . add ( uri ) ; } } return uris . toArray ( new URI [ uris . size ( ) ] ) ; }
|
Convert given DNS SRV address to array of URIs
|
38,645
|
public void setSlf4jLogname ( String logName ) { 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 .
|
38,646
|
public void log ( StopWatch sw ) { if ( m_log != null && m_log . isInfoEnabled ( ) ) { m_log . info ( sw . toString ( ) ) ; } }
|
Logs using the INFO priority .
|
38,647
|
public void log ( StopWatch sw ) { if ( ! m_queue . offer ( sw . freeze ( ) ) ) m_rejectedStopWatches . getAndIncrement ( ) ; if ( m_collectorThread == null ) { synchronized ( this ) { if ( m_collectorThread == null ) { m_collectorThread = new CollectorThread ( ) ; m_collectorThread . setName ( "Speed4J PeriodicalLog Collector Thread" ) ; m_collectorThread . setDaemon ( true ) ; m_collectorThread . start ( ) ; } } } }
|
This method also starts the collector thread lazily .
|
38,648
|
private void rebuildJmx ( ) { m_mbeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; try { buildMBeanInfo ( ) ; ObjectName newName = getJMXName ( ) ; if ( m_mbeanServer . isRegistered ( newName ) ) { log . debug ( "Removing already registered bean {}" , newName ) ; m_mbeanServer . unregisterMBean ( newName ) ; } if ( m_jmxName != null && ! newName . equals ( m_jmxName ) && m_mbeanServer . isRegistered ( m_jmxName ) ) { log . debug ( "Removing the old bean {}" , m_jmxName ) ; m_mbeanServer . unregisterMBean ( m_jmxName ) ; } m_jmxName = getJMXName ( ) ; if ( m_beanInfo != null ) { m_mbeanServer . registerMBean ( this , m_jmxName ) ; log . debug ( "Registered new JMX bean '{}'" , m_jmxName ) ; } } catch ( InstanceAlreadyExistsException e ) { log . debug ( "JMX bean '{}' already registered, continuing..." ) ; } catch ( Exception e ) { throw new ConfigurationException ( e ) ; } }
|
Rebuild the JMX bean .
|
38,649
|
private boolean emptyQueue ( long finalMoment ) { StopWatch sw ; try { while ( null != ( sw = m_queue . poll ( 100 , TimeUnit . MILLISECONDS ) ) ) { if ( sw . getTag ( ) == null ) continue ; if ( sw . getCreationTime ( ) > finalMoment ) { m_queue . addFirst ( sw ) ; return true ; } CollectedStatistics cs = m_stats . get ( sw . getTag ( ) ) ; if ( cs == null ) { cs = new CollectedStatistics ( ) ; m_stats . put ( sw . getTag ( ) , cs ) ; } cs . add ( sw ) ; if ( m_slowLogOn && m_slowLog != null ) { Long threshold = m_slowThresholdMicros . get ( sw . getTag ( ) ) ; if ( threshold != null && sw . getTimeMicros ( ) > threshold ) { m_slowLog . info ( "{} {} \"{}\" \"{}\" {}" , new Object [ ] { String . format ( "%tFT%<tT.%<tL%<tz" , new Date ( sw . getCreationTime ( ) ) ) , saneDoubleToString ( m_slowLogPercentile ) , sw . getTag ( ) , sw . getMessage ( ) != null ? sw . getMessage ( ) : "" , sw . getTimeMicros ( ) / 1000F } ) ; } } } } catch ( InterruptedException e ) { } return false ; }
|
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 .
|
38,650
|
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 .
|
38,651
|
@ 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 ) ; } for ( Enumeration < String > e = ( Enumeration < String > ) c_config . propertyNames ( ) ; e . hasMoreElements ( ) ; ) { String key = e . nextElement ( ) ; String [ ] components = key . split ( "\\." ) ; if ( components . length < 2 || ! components [ 0 ] . equals ( PROPERTY_PREFIX ) ) continue ; String logger = components [ 1 ] ; StopWatchFactory swf = c_factories . get ( logger ) ; if ( swf == null ) { swf = new StopWatchFactory ( instantiateLog ( logger ) ) ; } if ( components . length > 2 ) { String setting = components [ 2 ] ; String method = "set" + Character . toUpperCase ( setting . charAt ( 0 ) ) + setting . substring ( 1 ) ; try { SetterUtil . set ( swf . getLog ( ) , method , ( String ) c_config . get ( key ) ) ; } catch ( NoSuchMethodException e1 ) { log . warn ( "An unknown setting {} for logger {}, wasn't able to find {}.{}. Continuing nevertheless." , new Object [ ] { setting , logger , logger , method } ) ; } catch ( Exception e1 ) { throw new ConfigurationException ( e1 ) ; } } c_factories . put ( logger , swf ) ; } }
|
Load configuration file try to parse it and do something useful .
|
38,652
|
public StopWatch getStopWatch ( String tag , String message ) { return new LoggingStopWatch ( m_log , tag , message ) ; }
|
Returns a StopWatch for the given tag and given message .
|
38,653
|
public static synchronized void shutdown ( ) { if ( c_factories == null ) return ; for ( Iterator < Entry < String , StopWatchFactory > > i = c_factories . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry < String , StopWatchFactory > e = i . next ( ) ; StopWatchFactory swf = e . getValue ( ) ; swf . internalShutdown ( ) ; i . remove ( ) ; } c_factories = null ; }
|
Shut down all StopWatchFactories . This method is useful to call to clean up any resources which might be usable .
|
38,654
|
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 .
|
38,655
|
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 .
|
38,656
|
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 .
|
38,657
|
public synchronized void add ( StopWatch sw ) { double timeInMs = sw . getTimeMicros ( ) / MICROS_IN_MILLIS ; for ( int i = 0 ; i < sw . getCount ( ) ; i ++ ) m_times . add ( timeInMs / sw . getCount ( ) ) ; if ( timeInMs < m_min ) m_min = timeInMs ; if ( timeInMs > m_max ) m_max = timeInMs ; }
|
Add a StopWatch to the statistics .
|
38,658
|
public PostBuilder withCategories ( Term ... terms ) { return withCategories ( Arrays . stream ( terms ) . map ( Term :: getId ) . collect ( toList ( ) ) ) ; }
|
Add existing Category term items when building a post .
|
38,659
|
public PostBuilder withTags ( Term ... tags ) { return withTags ( Arrays . stream ( tags ) . map ( Term :: getId ) . collect ( toList ( ) ) ) ; }
|
Add existing Tag term items when building a post .
|
38,660
|
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 .
|
38,661
|
@ 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 > ) fieldModels . get ( fieldModelKey ) ; if ( fieldModel != null ) { return fieldModel ; } synchronized ( MONITOR ) { fieldModel = ( FieldModel < C > ) fieldModels . get ( fieldModelKey ) ; if ( fieldModel != null ) { return fieldModel ; } else { fieldModel = new FieldModel < C > ( f , fieldAccess ) ; fieldModels . putIfAbsent ( fieldModelKey , fieldModel ) ; return fieldModel ; } } }
|
Returns a field model for the given Field and FieldAccess instance . If a FieldModel already exists it will be reused .
|
38,662
|
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 ) ; } else { Dotted dottedClassName = Dotted . fromClass ( clazz ) ; isImmutable = ANALYSIS_SESSION . get ( ) . resultFor ( dottedClassName ) . isImmutable ; DETECTED_IMMUTABLE_CLASSES . put ( clazz , isImmutable ) ; } if ( isImmutable . equals ( IsImmutable . IMMUTABLE ) || isImmutable . equals ( IsImmutable . EFFECTIVELY_IMMUTABLE ) ) { return true ; } else { return false ; } }
|
Return true if immutable or effectively immutable
|
38,663
|
public static < E > Iterable < E > wrapEnumeration ( Enumeration < E > enumeration ) { return new IterableEnumeration < E > ( enumeration ) ; }
|
Typesafe factory method for construction convenience
|
38,664
|
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 IllegalStateException ( "Cannot initialise parser for " + location . toExternalForm ( ) , e ) ; } catch ( SAXException e ) { throw new IllegalStateException ( "Cannot parse " + location . toExternalForm ( ) , e ) ; } BindingConfiguration configuration = parseDocument ( doc ) ; return configuration ; }
|
Given a configuration URL produce the corresponding configuration
|
38,665
|
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 . getInputStream ( ) ; } if ( inputStream == null ) { if ( location == null ) { throw new IOException ( "Failed to obtain InputStream for named location: null" ) ; } else { throw new IOException ( "Failed to obtain InputStream for named location: " + location . toExternalForm ( ) ) ; } } InputSource inputSource = new InputSource ( inputStream ) ; List < SAXParseException > errors = new ArrayList < SAXParseException > ( ) ; DocumentBuilder docBuilder = constructDocumentBuilder ( errors ) ; Document document = docBuilder . parse ( inputSource ) ; if ( ! errors . isEmpty ( ) ) { if ( location == null ) { throw new IllegalStateException ( "Invalid File: null" , ( Throwable ) errors . get ( 0 ) ) ; } else { throw new IllegalStateException ( "Invalid file: " + location . toExternalForm ( ) , ( Throwable ) errors . get ( 0 ) ) ; } } return document ; }
|
Helper method to load a DOM Document from the given configuration URL
|
38,666
|
private static DocumentBuilder constructDocumentBuilder ( List < SAXParseException > errors ) throws ParserConfigurationException { DocumentBuilderFactory documentBuilderFactory = constructDocumentBuilderFactory ( ) ; DocumentBuilder docBuilder = documentBuilderFactory . newDocumentBuilder ( ) ; docBuilder . setEntityResolver ( new BindingXmlEntityResolver ( ) ) ; docBuilder . setErrorHandler ( new BindingXmlErrorHandler ( errors ) ) ; return docBuilder ; }
|
Helper used to construct a document builder
|
38,667
|
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 ( ! ConverterProvider . class . isAssignableFrom ( providerClass ) ) { throw new IllegalStateException ( "Referenced class {" + element . getAttribute ( "class" ) + "} did not implement BindingProvider" ) ; } @ SuppressWarnings ( "unchecked" ) final Class < ConverterProvider > typedProviderClass = ( Class < ConverterProvider > ) providerClass ; return new Provider ( ( Class < ConverterProvider > ) typedProviderClass ) ; }
|
Parse the provider element and its children
|
38,668
|
private static < T > Extension < T > parseBinderExtensionElement ( Element element ) { @ SuppressWarnings ( "unchecked" ) Class < T > providerClass = ( Class < T > ) lookupClass ( element . getAttribute ( "class" ) ) ; Class < ? > implementationClass = lookupClass ( element . getAttribute ( "implementationClass" ) ) ; if ( providerClass == null ) { throw new IllegalStateException ( "Referenced class {" + element . getAttribute ( "class" ) + "} could not be found" ) ; } if ( implementationClass == null ) { throw new IllegalStateException ( "Referenced implementation class {" + element . getAttribute ( "implementationClass" ) + "} could not be found" ) ; } if ( providerClass . isAssignableFrom ( implementationClass ) ) { throw new IllegalStateException ( "Referenced class {" + element . getAttribute ( "class" ) + "} did not implement BindingProvider" ) ; } try { @ SuppressWarnings ( "unchecked" ) final Class < ? extends T > myImplementationClass = ( Class < T > ) implementationClass . newInstance ( ) ; return new Extension < T > ( providerClass , myImplementationClass ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( "Referenced implementation class {" + element . getAttribute ( "implementationClass" ) + "} could not be instantiated" ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( "Referenced implementation class {" + element . getAttribute ( "implementationClass" ) + "} could not be accessed" ) ; } }
|
Parse the extension element
|
38,669
|
private static Class < ? > lookupClass ( String elementName ) { Class < ? > clazz = null ; try { clazz = ClassLoaderUtils . getClassLoader ( ) . loadClass ( elementName ) ; } catch ( ClassNotFoundException e ) { return null ; } return clazz ; }
|
Helper method that given a class - name will create the appropriate Class instance
|
38,670
|
private < T > Class < ? extends Annotation > matchAnnotationToScope ( Annotation [ ] annotations ) { for ( Annotation next : annotations ) { Class < ? extends Annotation > nextType = next . annotationType ( ) ; if ( nextType . getAnnotation ( BindingScope . class ) != null ) { return nextType ; } } return DefaultBinding . class ; }
|
Helper method for matching and returning a scope annotation
|
38,671
|
protected String constructMessage ( String message , Throwable cause ) { if ( cause != null ) { StringBuilder strBuilder = new StringBuilder ( ) ; if ( message != null ) { strBuilder . append ( message ) . append ( ": " ) ; } strBuilder . append ( "Wrapped exception is {" ) . append ( cause ) ; strBuilder . append ( "}" ) ; return strBuilder . toString ( ) ; } else { return message ; } }
|
Constructs an exception String with the given message and incorporating the causing exception
|
38,672
|
public Throwable getRootCause ( ) { Throwable rootCause = null ; Throwable nextCause = getCause ( ) ; while ( nextCause != null && ! nextCause . equals ( rootCause ) ) { rootCause = nextCause ; nextCause = nextCause . getCause ( ) ; } return rootCause ; }
|
Retrieves the ultimate root cause for this exception or null
|
38,673
|
public < E extends Exception > E findWrapped ( Class < E > exceptionType ) { if ( exceptionType == null ) { return null ; } Throwable cause = getCause ( ) ; while ( true ) { if ( cause == null ) { return null ; } if ( exceptionType . isInstance ( cause ) ) { @ SuppressWarnings ( "unchecked" ) E matchedCause = ( E ) cause ; return matchedCause ; } if ( cause . getCause ( ) == cause ) { return null ; } if ( cause instanceof WrappedRuntimeException ) { return ( ( WrappedRuntimeException ) cause ) . findWrapped ( exceptionType ) ; } if ( cause instanceof WrappedCheckedException ) { return ( ( WrappedCheckedException ) cause ) . findWrapped ( exceptionType ) ; } cause = cause . getCause ( ) ; } }
|
Returns the next parent exception of the given type or null
|
38,674
|
public void beforeNullSafeOperation ( SharedSessionContractImplementor session ) { ConfigurationHelper . setCurrentSessionFactory ( session . getFactory ( ) ) ; if ( this instanceof IntegratorConfiguredType ) { ( ( IntegratorConfiguredType ) this ) . applyConfiguration ( session . getFactory ( ) ) ; } }
|
Included to allow session state to be applied to the user type
|
38,675
|
private void initJdkBindings ( ) { registerBinding ( AtomicBoolean . class , String . class , new AtomicBooleanStringBinding ( ) ) ; registerBinding ( AtomicInteger . class , String . class , new AtomicIntegerStringBinding ( ) ) ; registerBinding ( AtomicLong . class , String . class , new AtomicLongStringBinding ( ) ) ; registerBinding ( BigDecimal . class , String . class , new BigDecimalStringBinding ( ) ) ; registerBinding ( BigInteger . class , String . class , new BigIntegerStringBinding ( ) ) ; registerBinding ( Boolean . class , String . class , new BooleanStringBinding ( ) ) ; registerBinding ( Byte . class , String . class , new ByteStringBinding ( ) ) ; registerBinding ( Calendar . class , String . class , new CalendarStringBinding ( ) ) ; registerBinding ( Character . class , String . class , new CharacterStringBinding ( ) ) ; registerBinding ( CharSequence . class , String . class , new CharSequenceStringBinding ( ) ) ; registerBinding ( Class . class , String . class , new ClassStringBinding ( ) ) ; registerBinding ( Currency . class , String . class , new CurrencyStringBinding ( ) ) ; registerBinding ( Date . class , String . class , new DateStringBinding ( ) ) ; registerBinding ( Double . class , String . class , new DoubleStringBinding ( ) ) ; registerBinding ( File . class , String . class , new FileStringBinding ( ) ) ; registerBinding ( Float . class , String . class , new FloatStringBinding ( ) ) ; registerBinding ( InetAddress . class , String . class , new InetAddressStringBinding ( ) ) ; registerBinding ( Integer . class , String . class , new IntegerStringBinding ( ) ) ; registerBinding ( Locale . class , String . class , new LocaleStringBinding ( ) ) ; registerBinding ( Long . class , String . class , new LongStringBinding ( ) ) ; registerBinding ( Package . class , String . class , new PackageStringBinding ( ) ) ; registerBinding ( Short . class , String . class , new ShortStringBinding ( ) ) ; registerBinding ( StringBuffer . class , String . class , new StringBufferStringBinding ( ) ) ; registerBinding ( StringBuilder . class , String . class , new StringBuilderStringBinding ( ) ) ; registerBinding ( String . class , String . class , new StringStringBinding ( ) ) ; registerBinding ( TimeZone . class , String . class , new TimeZoneStringBinding ( ) ) ; registerBinding ( URI . class , String . class , new URIStringBinding ( ) ) ; registerBinding ( URL . class , String . class , new URLStringBinding ( ) ) ; registerBinding ( UUID . class , String . class , new UUIDStringBinding ( ) ) ; }
|
Initialises standard bindings for Java built in types
|
38,676
|
protected < X > void registerConfigurations ( Enumeration < URL > bindingsConfiguration ) { List < BindingConfiguration > configs = new ArrayList < BindingConfiguration > ( ) ; for ( URL nextLocation : IterableEnumeration . wrapEnumeration ( bindingsConfiguration ) ) { URL builtIn = getBuiltInBindingsURL ( ) ; if ( ! builtIn . toString ( ) . equals ( nextLocation . toString ( ) ) ) { configs . add ( BindingXmlLoader . load ( nextLocation ) ) ; } } for ( BindingConfiguration nextConfig : configs ) { for ( Provider nextProvider : nextConfig . getProviders ( ) ) { try { registerConverterProvider ( nextProvider . getProviderClass ( ) . newInstance ( ) ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( "Cannot instantiate binding provider class: " + nextProvider . getProviderClass ( ) . getName ( ) ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( "Cannot access binding provider class: " + nextProvider . getProviderClass ( ) . getName ( ) ) ; } } for ( Extension < ? > nextExtension : nextConfig . getExtensions ( ) ) { try { @ SuppressWarnings ( "unchecked" ) Extension < X > myExtension = ( Extension < X > ) nextExtension ; @ SuppressWarnings ( "unchecked" ) X myImplementation = ( X ) nextExtension . getImplementationClass ( ) . newInstance ( ) ; registerExtendedBinder ( myExtension . getExtensionClass ( ) , myImplementation ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( "Cannot instantiate binder extension class: " + nextExtension . getExtensionClass ( ) . getName ( ) ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( "Cannot access binder extension class: " + nextExtension . getExtensionClass ( ) . getName ( ) ) ; } } registerBindingConfigurationEntries ( nextConfig . getBindingEntries ( ) ) ; } }
|
Registers a set of configurations for the given list of URLs . This is typically used to process all the various bindings . xml files discovered in jars on the classpath . It is given protected scope to allow subclasses to register additional configurations
|
38,677
|
protected void registerBindingConfigurationEntries ( Iterable < BindingConfigurationEntry > bindings ) { for ( BindingConfigurationEntry nextBinding : bindings ) { try { registerBindingConfigurationEntry ( nextBinding ) ; } catch ( IllegalStateException e ) { } } }
|
Registers a list of binding configuration entries . A binding configuration entry described in a section of a bindings . xml file and describes the use of a particular method for databinding .
|
38,678
|
public void registerAnnotatedClasses ( Class < ? > ... classesToInspect ) { for ( Class < ? > nextClass : classesToInspect ) { Class < ? > loopClass = nextClass ; while ( ( loopClass != Object . class ) && ( ! inspectedClasses . contains ( loopClass ) ) ) { attachForAnnotations ( loopClass ) ; loopClass = loopClass . getSuperclass ( ) ; } } }
|
Inspect each of the supplied classes processing any of the annotated methods found
|
38,679
|
protected < I , T extends I > void registerExtendedBinder ( Class < I > iface , T provider ) { extendedBinders . put ( iface , provider ) ; }
|
Register a custom typesafe binder implementation which can be retrieved later
|
38,680
|
@ SuppressWarnings ( "unchecked" ) protected < I > I getExtendedBinder ( Class < I > cls ) { return ( I ) extendedBinders . get ( cls ) ; }
|
Retrieves an extended binder
|
38,681
|
public static boolean isJdkImmutable ( Class < ? > type ) { if ( Class . class == type ) { return true ; } if ( String . class == type ) { return true ; } if ( BigInteger . class == type ) { return true ; } if ( BigDecimal . class == type ) { return true ; } if ( URL . class == type ) { return true ; } if ( UUID . class == type ) { return true ; } if ( URI . class == type ) { return true ; } if ( Pattern . class == type ) { return true ; } return false ; }
|
Indicate if the class is a known non - primitive JDK immutable type
|
38,682
|
public static boolean isWrapper ( Class < ? > type ) { if ( Boolean . class == type ) { return true ; } if ( Byte . class == type ) { return true ; } if ( Character . class == type ) { return true ; } if ( Short . class == type ) { return true ; } if ( Integer . class == type ) { return true ; } if ( Long . class == type ) { return true ; } if ( Float . class == type ) { return true ; } if ( Double . class == type ) { return true ; } return false ; }
|
Indicate if the class is a known primitive wrapper type
|
38,683
|
public static Field [ ] collectInstanceFields ( Class < ? > c , Class < ? > limitExclusive ) { return collectFields ( c , 0 , Modifier . STATIC , limitExclusive ) ; }
|
Produces an array with all the instance fields of the specified class
|
38,684
|
protected final Class < T > getEntityClass ( ) { @ SuppressWarnings ( "unchecked" ) final Class < T > result = ( Class < T > ) TypeHelper . getTypeArguments ( JpaSearchRepository . class , this . getClass ( ) ) . get ( 0 ) ; return result ; }
|
Returns the class for the entity type associated with this repository .
|
38,685
|
protected final Class < ID > getIdClass ( ) { @ SuppressWarnings ( "unchecked" ) final Class < ID > result = ( Class < ID > ) TypeHelper . getTypeArguments ( JpaSearchRepository . class , this . getClass ( ) ) . get ( 1 ) ; return result ; }
|
Returns the class for the ID field for the entity type associated with this repository .
|
38,686
|
protected T getSingleResult ( Query q ) { try { @ SuppressWarnings ( "unchecked" ) T retVal = ( T ) q . getSingleResult ( ) ; return retVal ; } catch ( NoResultException e ) { return null ; } }
|
Executes a query that returns a single record . In the case of no result rather than throwing an exception null is returned .
|
38,687
|
public static Class < ? > classForName ( String name ) throws ClassNotFoundException { ClassLoader cl = getClassLoader ( ) ; try { if ( cl != null ) { return cl . loadClass ( name ) ; } } catch ( ClassNotFoundException e ) { } return Class . forName ( name ) ; }
|
Attempts to instantiate the named class using the context ClassLoader for the current thread or Class . forName if this does not work
|
38,688
|
public static Class < ? > classForName ( String name , ClassLoader ... classLoaders ) throws ClassNotFoundException { ClassLoader [ ] cls = getClassLoaders ( classLoaders ) ; for ( ClassLoader cl : cls ) { try { if ( cl != null ) { return cl . loadClass ( name ) ; } } catch ( ClassNotFoundException e ) { } } return Class . forName ( name ) ; }
|
Attempts to instantiate the named class using each of the specified ClassLoaders in turn or Class . forName if these do not work
|
38,689
|
protected < T > T performCloneForCloneableMethod ( T object , CloneDriver context ) { Class < ? > clazz = object . getClass ( ) ; final T result ; try { MethodHandle handle = context . getCloneMethod ( clazz ) ; result = ( T ) handle . invoke ( object ) ; } catch ( Throwable e ) { throw new IllegalStateException ( "Could not invoke clone() for instance of: " + clazz . getName ( ) , e ) ; } return result ; }
|
Helper method for performing cloning for objects of classes implementing java . lang . Cloneable
|
38,690
|
protected < T > void handleCloneField ( T obj , T copy , CloneDriver driver , FieldModel < T > f , IdentityHashMap < Object , Object > referencesToReuse , long stackDepth ) { final Class < ? > clazz = f . getFieldClass ( ) ; if ( clazz . isPrimitive ( ) ) { handleClonePrimitiveField ( obj , copy , driver , f , referencesToReuse ) ; } else if ( ! driver . isCloneSyntheticFields ( ) && f . isSynthetic ( ) ) { putFieldValue ( copy , f , getFieldValue ( obj , f ) ) ; } else { final Object fieldObject = getFieldValue ( obj , f ) ; final Object fieldObjectClone = clone ( fieldObject , driver , referencesToReuse , stackDepth ) ; putFieldValue ( copy , f , fieldObjectClone ) ; } }
|
Clone a Field
|
38,691
|
@ SuppressWarnings ( "unchecked" ) public static final < C > ClassModel < C > get ( ClassAccess < C > classAccess ) { Class < ? > clazz = classAccess . getType ( ) ; String classModelKey = ( classAccess . getClass ( ) . getName ( ) + ":" + clazz . getName ( ) ) ; ClassModel < C > classModel = ( ClassModel < C > ) classModels . get ( classModelKey ) ; if ( classModel != null ) { return classModel ; } synchronized ( MONITOR ) { classModel = ( ClassModel < C > ) classModels . get ( classModelKey ) ; if ( classModel != null ) { return classModel ; } else { classModel = new ClassModel < C > ( classAccess ) ; classModels . put ( classModelKey , classModel ) ; return classModel ; } } }
|
Returns a class model for the given ClassAccess instance . If a ClassModel already exists it will be reused .
|
38,692
|
private void initializeBuiltInImplementors ( ) { builtInImplementors . put ( ArrayList . class , new ArrayListImplementor ( ) ) ; builtInImplementors . put ( ConcurrentHashMap . class , new ConcurrentHashMapImplementor ( ) ) ; builtInImplementors . put ( GregorianCalendar . class , new GregorianCalendarImplementor ( ) ) ; builtInImplementors . put ( HashMap . class , new HashMapImplementor ( ) ) ; builtInImplementors . put ( HashSet . class , new HashSetImplementor ( ) ) ; builtInImplementors . put ( LinkedList . class , new LinkedListImplementor ( ) ) ; builtInImplementors . put ( TreeMap . class , new TreeMapImplementor ( ) ) ; allImplementors . putAll ( builtInImplementors ) ; }
|
Initialise a set of built in CloneImplementors for commonly used JDK types
|
38,693
|
public void setImplementors ( Map < Class < ? > , CloneImplementor > implementors ) { this . allImplementors = new HashMap < Class < ? > , CloneImplementor > ( ) ; allImplementors . putAll ( builtInImplementors ) ; allImplementors . putAll ( implementors ) ; }
|
Sets CloneImplementors to be used .
|
38,694
|
public static String removeWhitespace ( String string ) { if ( string == null || string . length ( ) == 0 ) { return string ; } else { int codePoints = string . codePointCount ( 0 , string . length ( ) ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < codePoints ; i ++ ) { int offset = string . offsetByCodePoints ( 0 , i ) ; int nextCodePoint = string . codePointAt ( offset ) ; if ( ! Character . isWhitespace ( nextCodePoint ) ) { sb . appendCodePoint ( nextCodePoint ) ; } } if ( string . length ( ) == sb . length ( ) ) { return string ; } else { return sb . toString ( ) ; } } }
|
Removes any whitespace from a String correctly handling surrogate characters
|
38,695
|
public static final AccessClassLoader get ( Class < ? > typeToBeExtended ) { ClassLoader loader = typeToBeExtended . getClassLoader ( ) ; return get ( loader == null ? ClassLoader . getSystemClassLoader ( ) : loader ) ; }
|
Creates a new instance using a suitable ClassLoader for the specified class
|
38,696
|
public synchronized static final AccessClassLoader get ( ClassLoader parent ) { AccessClassLoader loader = ( AccessClassLoader ) ASM_CLASS_LOADERS . get ( parent ) ; if ( loader == null ) { loader = new AccessClassLoader ( parent ) ; ASM_CLASS_LOADERS . put ( parent , loader ) ; } return loader ; }
|
Creates an AccessClassLoader for the given parent
|
38,697
|
public void registerClass ( String name , byte [ ] bytes ) { if ( registeredClasses . containsKey ( name ) ) { throw new IllegalStateException ( "Attempted to register a class that has been registered already: " + name ) ; } registeredClasses . put ( name , bytes ) ; }
|
Registers a class by its name
|
38,698
|
public boolean isPatterned ( ) { final boolean result ; if ( pattern . indexOf ( '*' ) != - 1 || pattern . indexOf ( '?' ) != - 1 ) { result = true ; } else { result = false ; } return result ; }
|
Returns true if the given path resolves a pattern as opposed to a literal path
|
38,699
|
public static < C > InvokeDynamicClassAccess < C > get ( Class < C > clazz ) { @ SuppressWarnings ( "unchecked" ) InvokeDynamicClassAccess < C > access = ( InvokeDynamicClassAccess < C > ) CLASS_ACCESSES . get ( clazz ) ; if ( access != null ) { return access ; } Class < ? > enclosingType = clazz . getEnclosingClass ( ) ; final boolean isNonStaticMemberClass = determineNonStaticMemberClass ( clazz , enclosingType ) ; String clazzName = clazz . getName ( ) ; String accessClassName = constructAccessClassName ( clazzName ) ; Class < ? > accessClass = null ; AccessClassLoader loader = AccessClassLoader . get ( clazz ) ; synchronized ( loader ) { try { accessClass = loader . loadClass ( accessClassName ) ; } catch ( ClassNotFoundException ignored ) { String accessClassNm = accessClassName . replace ( '.' , '/' ) ; String clazzNm = clazzName . replace ( '.' , '/' ) ; String enclosingClassNm = determineEnclosingClassNm ( clazz , enclosingType , isNonStaticMemberClass ) ; String signatureString = "L" + INVOKEDYNAMIC_CLASS_ACCESS_NM + "<L" + clazzNm + ";>;L" + CLASS_ACCESS_NM + "<L" + clazzNm + ";>;" ; ClassWriter cw = new ClassWriter ( 0 ) ; cw . visit ( V1_7 , ACC_PUBLIC + ACC_SUPER , accessClassNm , signatureString , INVOKEDYNAMIC_CLASS_ACCESS_NM , null ) ; enhanceForConstructor ( cw , accessClassNm , clazzNm ) ; if ( isNonStaticMemberClass ) { enhanceForNewInstanceInner ( cw , clazzNm , enclosingClassNm ) ; } else { enhanceForNewInstance ( cw , clazzNm ) ; } cw . visitEnd ( ) ; loader . registerClass ( accessClassName , cw . toByteArray ( ) ) ; try { accessClass = loader . findClass ( accessClassName ) ; } catch ( ClassNotFoundException e ) { throw new IllegalStateException ( "AccessClass unexpectedly could not be found" , e ) ; } } } try { @ SuppressWarnings ( "unchecked" ) Constructor < InvokeDynamicClassAccess < C > > c = ( Constructor < InvokeDynamicClassAccess < C > > ) accessClass . getConstructor ( new Class [ ] { Class . class } ) ; access = c . newInstance ( clazz ) ; access . isNonStaticMemberClass = isNonStaticMemberClass ; CLASS_ACCESSES . putIfAbsent ( clazz , access ) ; return access ; } catch ( Exception ex ) { throw new RuntimeException ( "Error constructing constructor access class: " + accessClassName + "{ " + ex . getMessage ( ) + " }" , ex ) ; } }
|
Get a new instance that can access the given Class . If the ClassAccess for this class has not been obtained before then the specific InvokeDynamicClassAccess is created by generating a specialised subclass of this class and returning it .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.