idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
31,100
public static void writeHttp2Promise ( Http2PushPromise pushPromise , ChannelHandlerContext ctx , Http2Connection conn , Http2ConnectionEncoder encoder , HttpCarbonMessage inboundRequestMsg , HttpResponseFuture outboundRespStatusFuture , int originalStreamId ) throws Http2Exception { int promisedStreamId = getNextStreamId ( conn ) ; pushPromise . setPromisedStreamId ( promisedStreamId ) ; pushPromise . setStreamId ( originalStreamId ) ; HttpRequest httpRequest = pushPromise . getHttpRequest ( ) ; httpRequest . headers ( ) . add ( HttpConversionUtil . ExtensionHeaderNames . SCHEME . text ( ) , HTTP_SCHEME ) ; Http2Headers http2Headers = HttpConversionUtil . toHttp2Headers ( httpRequest , true ) ; ChannelFuture channelFuture = encoder . writePushPromise ( ctx , originalStreamId , promisedStreamId , http2Headers , 0 , ctx . newPromise ( ) ) ; encoder . flowController ( ) . writePendingBytes ( ) ; ctx . flush ( ) ; Util . checkForResponseWriteStatus ( inboundRequestMsg , outboundRespStatusFuture , channelFuture ) ; }
Writes an HTTP2 promise .
31,101
public static void validatePromisedStreamState ( int originalStreamId , int streamId , Http2Connection conn , HttpCarbonMessage inboundRequestMsg ) throws Http2Exception { if ( streamId == originalStreamId ) { return ; } if ( ! isValidStreamId ( streamId , conn ) ) { inboundRequestMsg . getHttpOutboundRespStatusFuture ( ) . notifyHttpListener ( new ServerConnectorException ( PROMISED_STREAM_REJECTED_ERROR ) ) ; throw new Http2Exception ( Http2Error . REFUSED_STREAM , PROMISED_STREAM_REJECTED_ERROR ) ; } }
Validates the state of promised stream with the original stream id and given stream id .
31,102
public static void writeHttp2Headers ( ChannelHandlerContext ctx , OutboundMsgHolder outboundMsgHolder , Http2ClientChannel http2ClientChannel , Http2ConnectionEncoder encoder , int streamId , HttpHeaders headers , Http2Headers http2Headers , boolean endStream ) throws Http2Exception { int dependencyId = headers . getInt ( HttpConversionUtil . ExtensionHeaderNames . STREAM_DEPENDENCY_ID . text ( ) , 0 ) ; short weight = headers . getShort ( HttpConversionUtil . ExtensionHeaderNames . STREAM_WEIGHT . text ( ) , Http2CodecUtil . DEFAULT_PRIORITY_WEIGHT ) ; for ( Http2DataEventListener dataEventListener : http2ClientChannel . getDataEventListeners ( ) ) { if ( ! dataEventListener . onHeadersWrite ( ctx , streamId , http2Headers , endStream ) ) { return ; } } encoder . writeHeaders ( ctx , streamId , http2Headers , dependencyId , weight , false , 0 , endStream , ctx . newPromise ( ) ) ; encoder . flowController ( ) . writePendingBytes ( ) ; ctx . flush ( ) ; if ( endStream ) { outboundMsgHolder . setRequestWritten ( true ) ; } }
Writes HTTP2 headers .
31,103
public static int initiateStream ( ChannelHandlerContext ctx , Http2Connection connection , Http2ClientChannel http2ClientChannel , OutboundMsgHolder outboundMsgHolder ) throws Http2Exception { int streamId = getNextStreamId ( connection ) ; createStream ( connection , streamId ) ; http2ClientChannel . putInFlightMessage ( streamId , outboundMsgHolder ) ; http2ClientChannel . getDataEventListeners ( ) . forEach ( dataEventListener -> dataEventListener . onStreamInit ( ctx , streamId ) ) ; return streamId ; }
Initiates a HTTP2 stream .
31,104
private static synchronized void createStream ( Http2Connection conn , int streamId ) throws Http2Exception { conn . local ( ) . createStream ( streamId , false ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Stream created streamId: {}" , streamId ) ; } }
Creates a stream with given stream id .
31,105
public static void onPushPromiseRead ( Http2PushPromise http2PushPromise , Http2ClientChannel http2ClientChannel , OutboundMsgHolder outboundMsgHolder ) { int streamId = http2PushPromise . getStreamId ( ) ; int promisedStreamId = http2PushPromise . getPromisedStreamId ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Received a push promise on channel: {} over stream id: {}, promisedStreamId: {}" , http2ClientChannel , streamId , promisedStreamId ) ; } if ( outboundMsgHolder == null ) { LOG . warn ( "Push promise received in channel: {} over invalid stream id : {}" , http2ClientChannel , streamId ) ; return ; } http2ClientChannel . putPromisedMessage ( promisedStreamId , outboundMsgHolder ) ; http2PushPromise . setOutboundMsgHolder ( outboundMsgHolder ) ; outboundMsgHolder . addPromise ( http2PushPromise ) ; }
Adds a push promise message .
31,106
private EventLoopPool getOrCreateEventLoopPool ( EventLoop eventLoop ) { final EventLoopPool pool = eventLoopPools . get ( eventLoop ) ; if ( pool != null ) { return pool ; } return eventLoopPools . computeIfAbsent ( eventLoop , e -> new EventLoopPool ( ) ) ; }
Get or create the pool that is bound to the given eventloop .
31,107
private EventLoopPool . PerRouteConnectionPool getOrCreatePerRoutePool ( EventLoopPool eventLoopPool , String key ) { final EventLoopPool . PerRouteConnectionPool perRouteConnectionPool = eventLoopPool . fetchPerRoutePool ( key ) ; if ( perRouteConnectionPool != null ) { return perRouteConnectionPool ; } return eventLoopPool . getPerRouteConnectionPools ( ) . computeIfAbsent ( key , p -> new EventLoopPool . PerRouteConnectionPool ( poolConfiguration . getHttp2MaxActiveStreamsPerConnection ( ) ) ) ; }
Get or creat the per route pool .
31,108
private static void overrideExceptionValue ( ) { Field exceptionField = null ; Field modifiersField = null ; int originalModifiers = 0 ; boolean setModifiers = false ; try { exceptionField = OpenSsl . class . getDeclaredField ( "UNAVAILABILITY_CAUSE" ) ; exceptionField . setAccessible ( true ) ; modifiersField = exceptionField . getClass ( ) . getDeclaredField ( "modifiers" ) ; modifiersField . setAccessible ( true ) ; originalModifiers = modifiersField . getInt ( exceptionField ) ; modifiersField . setInt ( exceptionField , originalModifiers & ~ Modifier . FINAL ) ; setModifiers = true ; exceptionField . set ( null , null ) ; } catch ( Throwable t ) { throw Throwables . propagate ( t ) ; } finally { if ( exceptionField != null && modifiersField != null & setModifiers ) { try { modifiersField . setInt ( exceptionField , originalModifiers ) ; } catch ( IllegalAccessException e ) { return ; } } } }
the library .
31,109
public ChannelPipelineFactory getPipelineFactory ( ) { return new ChannelPipelineFactory ( ) { public ChannelPipeline getPipeline ( ) throws Exception { final ChannelPipeline cp = Channels . pipeline ( ) ; cp . addLast ( FRAME_DECODER , new FixedLengthFrameDecoder ( 8 ) ) ; cp . addLast ( HANDSHAKE , new Socks4HandshakeHandler ( Socks4ClientBootstrap . super . getPipelineFactory ( ) ) ) ; return cp ; } } ; }
Hijack super class s pipelineFactory and return our own that does the connect to SOCKS proxy and does the handshake .
31,110
public ChannelFuture connect ( final SocketAddress remoteAddress ) { if ( ! ( remoteAddress instanceof InetSocketAddress ) ) { throw new IllegalArgumentException ( "expecting InetSocketAddress" ) ; } final SettableChannelFuture settableChannelFuture = new SettableChannelFuture ( ) ; super . connect ( socksProxyAddr ) . addListener ( new ChannelFutureListener ( ) { public void operationComplete ( ChannelFuture future ) throws Exception { settableChannelFuture . setChannel ( future . getChannel ( ) ) ; if ( future . isSuccess ( ) ) { socksConnect ( future . getChannel ( ) , ( InetSocketAddress ) remoteAddress ) . addListener ( new ChannelFutureListener ( ) { public void operationComplete ( ChannelFuture innerFuture ) throws Exception { if ( innerFuture . isSuccess ( ) ) { settableChannelFuture . setSuccess ( ) ; } else { settableChannelFuture . setFailure ( innerFuture . getCause ( ) ) ; } } } ) ; } else { settableChannelFuture . setFailure ( future . getCause ( ) ) ; } } } ) ; return settableChannelFuture ; }
Hijack the connect method to connect to socks proxy and then send the connection handshake once connection to proxy is established .
31,111
private static ChannelFuture socksConnect ( Channel channel , InetSocketAddress remoteAddress ) { channel . write ( createHandshake ( remoteAddress ) ) ; return ( ( Socks4HandshakeHandler ) channel . getPipeline ( ) . get ( "handshake" ) ) . getChannelFuture ( ) ; }
try to look at the remoteAddress and decide to use SOCKS4 or SOCKS4a handshake packet .
31,112
protected T setNiftyName ( String niftyName ) { Preconditions . checkNotNull ( niftyName , "niftyName cannot be null" ) ; this . niftyName = niftyName ; return ( T ) this ; }
Sets an identifier which will be added to all thread created by the boss and worker executors .
31,113
public T withProcessor ( final NiftyProcessor processor ) { this . niftyProcessorFactory = new NiftyProcessorFactory ( ) { public NiftyProcessor getProcessor ( TTransport transport ) { return processor ; } } ; return ( T ) this ; }
Specify the TProcessor .
31,114
public ThriftServerDef build ( ) { checkState ( niftyProcessorFactory != null || thriftProcessorFactory != null , "Processor not defined!" ) ; checkState ( niftyProcessorFactory == null || thriftProcessorFactory == null , "TProcessors will be automatically adapted to NiftyProcessors, don't specify both" ) ; checkState ( maxConnections >= 0 , "maxConnections should be 0 (for unlimited) or positive" ) ; if ( niftyProcessorFactory == null ) { niftyProcessorFactory = factoryFromTProcessorFactory ( thriftProcessorFactory ) ; } return new ThriftServerDef ( name , serverPort , maxFrameSize , queuedResponseLimit , maxConnections , niftyProcessorFactory , duplexProtocolFactory , clientIdleTimeout , taskTimeout , queueTimeout , thriftFrameCodecFactory , executor , securityFactory , sslConfiguration , transportAttachObserver ) ; }
Build the ThriftServerDef
31,115
public void start ( Set < File > files , Consumer < Set < File > > callback ) { if ( isStarted ( ) ) { throw new IllegalStateException ( "start() should not be called more than once" ) ; } Set < File > filesCopy = ImmutableSet . copyOf ( files ) ; Preconditions . checkArgument ( filesCopy . size ( ) > 0 , "must specify at least 1 file to watch for changes" ) ; this . callback = requireNonNull ( callback ) ; watchedFiles = filesCopy ; executorService = MoreExecutors . listeningDecorator ( Executors . newScheduledThreadPool ( 1 ) ) ; future = executorService . scheduleAtFixedRate ( this :: scanFilesForChanges , initialDelay , interval , timeUnit ) ; }
Starts polling the watched files for changes .
31,116
public void shutdown ( ) { if ( isStarted ( ) ) { future . cancel ( true ) ; executorService . shutdown ( ) ; future = null ; executorService = null ; watchedFiles = ImmutableSet . of ( ) ; callback = null ; metadataCacheRef . set ( ImmutableMap . of ( ) ) ; stats . clear ( ) ; } }
Stops polling the files for changes . Should be called during server shutdown or when this watcher is no longer needed to make sure the background thread is stopped .
31,117
private void scanFilesForChanges ( ) { MessageDigest digest ; try { digest = MessageDigest . getInstance ( "SHA-256" ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e ) ; } ImmutableSet . Builder < File > modifiedFilesBuilder = ImmutableSet . builder ( ) ; Map < File , FileMetadata > metadataCache = Maps . newHashMap ( metadataCacheRef . get ( ) ) ; for ( File file : watchedFiles ) { try { FileMetadata meta = new FileMetadata ( file , digest ) ; if ( ! meta . equals ( metadataCache . get ( file ) ) ) { metadataCache . put ( file , meta ) ; modifiedFilesBuilder . add ( file ) ; } } catch ( IOException | SecurityException e ) { log . warn ( "Error trying to stat or read file %s: %s: %s" , file . toString ( ) , e . getClass ( ) . getName ( ) , e . getMessage ( ) ) ; metadataCache . remove ( file ) ; } } Set < File > modifiedFiles = modifiedFilesBuilder . build ( ) ; boolean callbackCalled = false ; boolean callbackSucceeded = false ; try { if ( ! modifiedFiles . isEmpty ( ) ) { callbackCalled = true ; callback . accept ( modifiedFiles ) ; callbackSucceeded = true ; } metadataCacheRef . set ( ImmutableMap . copyOf ( metadataCache ) ) ; } catch ( Exception e ) { log . warn ( "Error from user callback: %s: %s" , e . getClass ( ) . toString ( ) , e . getMessage ( ) ) ; } if ( ! modifiedFiles . isEmpty ( ) ) { stats . fileChangesDetected . getAndAdd ( modifiedFiles . size ( ) ) ; } if ( callbackCalled ) { stats . callbacksInvoked . getAndIncrement ( ) ; if ( callbackSucceeded ) { stats . callbacksSucceeded . getAndIncrement ( ) ; } else { stats . callbacksFailed . getAndIncrement ( ) ; } } stats . pollCycles . getAndIncrement ( ) ; }
Scans the watched files for changes . If any changes are detected calls the user callback with the set of all files that were modified since the last successful update attempt . Note that when a watched file is deleted it will not be considered modified .
31,118
private static String computeFileHash ( File file , MessageDigest md ) throws IOException { md . reset ( ) ; return BaseEncoding . base16 ( ) . encode ( md . digest ( Files . toByteArray ( file ) ) ) ; }
Computes a hash of the given file s contents using the provided MessageDigest .
31,119
private static byte [ ] extract ( byte [ ] salt , byte [ ] inputKeyingMaterial ) { return initHmacSha256 ( salt == null ? NULL_SALT : salt ) . doFinal ( inputKeyingMaterial ) ; }
The extract stage of the extract - then - expand HKDF algorithm .
31,120
private int read ( byte [ ] bytes , int offset , int length , Duration receiveTimeout ) throws InterruptedException , TTransportException { long timeRemaining = receiveTimeout . roundTo ( TimeUnit . NANOSECONDS ) ; lock . lock ( ) ; try { while ( ! closed ) { int bytesAvailable = readBuffer . readableBytes ( ) ; if ( bytesAvailable > 0 ) { int begin = readBuffer . readerIndex ( ) ; readBuffer . readBytes ( bytes , offset , Math . min ( bytesAvailable , length ) ) ; int end = readBuffer . readerIndex ( ) ; return end - begin ; } if ( timeRemaining <= 0 ) { break ; } timeRemaining = condition . awaitNanos ( timeRemaining ) ; if ( exception != null ) { try { throw new TTransportException ( exception ) ; } finally { exception = null ; closed = true ; close ( ) ; } } } if ( closed ) { throw new TTransportException ( "channel closed !" ) ; } } finally { lock . unlock ( ) ; } throw new TTransportException ( String . format ( "receive timeout, %d ms has elapsed" , receiveTimeout . toMillis ( ) ) ) ; }
yeah mimicking sync with async is just horrible
31,121
public void resetOutputBuffer ( ) { int shrunkenSize = shrinkBufferSize ( ) ; if ( outputBuffer . writerIndex ( ) < shrunkenSize ) { ++ bufferUnderUsedCounter ; } else { bufferUnderUsedCounter = 0 ; } if ( shouldShrinkBuffer ( ) ) { outputBuffer = ChannelBuffers . dynamicBuffer ( shrunkenSize ) ; bufferUnderUsedCounter = 0 ; } else { outputBuffer . clear ( ) ; } }
Resets the state of this transport so it can be used to write more messages
31,122
public List < SessionTicketKey > parse ( File file ) throws IOException { return parseBytes ( Files . toByteArray ( file ) ) ; }
Returns a list of tickets parsed from the ticket file . The keys are returned in a format suitable for use with netty . The first keys are the current keys following that are the new keys and old keys .
31,123
public List < SessionTicketKey > parseBytes ( byte [ ] json ) throws IOException { List < String > allSeeds = TicketSeeds . parseFromJSONBytes ( json , objectMapper ) . getAllSeeds ( ) ; return allSeeds . stream ( ) . map ( this :: deriveKeyFromSeed ) . collect ( Collectors . toList ( ) ) ; }
Returns a list of tickets parsed from the given JSON bytes . The keys are returned in a format suitable for use with netty . The first keys are the current keys following that are the new keys and old keys .
31,124
private static boolean looksLikeTLS ( ChannelBuffer buffer ) { if ( buffer . getByte ( 0 ) != 0x16 || buffer . getByte ( 1 ) != 0x03 || buffer . getByte ( 5 ) != 0x01 ) { return false ; } if ( buffer . getByte ( 4 ) == 0x80 && buffer . getByte ( 8 ) != 0x7c ) { return false ; } return true ; }
Requires 9 bytes of input .
31,125
public int read ( byte [ ] buf , int off , int len ) throws TTransportException { return inputTransport . read ( buf , off , len ) ; }
Delegate input methods
31,126
public void putArrayValues ( String name , Set < String > values ) { arrayValues . put ( name , values ) ; }
Adds the content of an array value property .
31,127
public < T > Tuple < T > giveTuple ( TypeTag tag ) { realizeCacheFor ( tag , emptyStack ( ) ) ; return cache . getTuple ( tag ) ; }
Returns a tuple of two different prefabricated values of the specified type .
31,128
public < T > T giveOther ( TypeTag tag , T value ) { Class < T > type = tag . getType ( ) ; if ( value != null && ! type . isAssignableFrom ( value . getClass ( ) ) && ! wraps ( type , value . getClass ( ) ) ) { throw new ReflectionException ( "TypeTag does not match value." ) ; } Tuple < T > tuple = giveTuple ( tag ) ; if ( tuple . getRed ( ) == null ) { return null ; } if ( type . isArray ( ) && arraysAreDeeplyEqual ( tuple . getRed ( ) , value ) ) { return tuple . getBlack ( ) ; } if ( ! type . isArray ( ) && tuple . getRed ( ) . equals ( value ) ) { return tuple . getBlack ( ) ; } return tuple . getRed ( ) ; }
Returns a prefabricated value of the specified type that is different from the specified value .
31,129
public < T > void realizeCacheFor ( TypeTag tag , LinkedHashSet < TypeTag > typeStack ) { if ( ! cache . contains ( tag ) ) { Tuple < T > tuple = createTuple ( tag , typeStack ) ; addToCache ( tag , tuple ) ; } }
Makes sure that values for the specified type are present in the cache but doesn t return them .
31,130
public < T > void put ( Class < ? > type , PrefabValueFactory < T > factory ) { if ( type != null ) { cache . put ( type . getName ( ) , factory ) ; } }
Adds the given factory to the cache and associates it with the given type .
31,131
public < T > void put ( String typeName , PrefabValueFactory < T > factory ) { if ( typeName != null ) { cache . put ( typeName , factory ) ; } }
Adds the given factory to the cache and associates it with the given type name .
31,132
@ SuppressWarnings ( "unchecked" ) public < T > PrefabValueFactory < T > get ( Class < T > type ) { if ( type == null ) { return null ; } return ( PrefabValueFactory < T > ) cache . get ( type . getName ( ) ) ; }
Retrieves the factory from the cache for the given type .
31,133
public Iterator < Map . Entry < String , PrefabValueFactory < ? > > > iterator ( ) { return cache . entrySet ( ) . iterator ( ) ; }
Provides an iterator over all available factories .
31,134
public static < T > List < T > buildListOfAtLeastOne ( T first , T ... more ) { if ( first == null ) { throw new IllegalArgumentException ( "First example is null." ) ; } List < T > result = new ArrayList < > ( ) ; result . add ( first ) ; addArrayElementsToList ( result , more ) ; return result ; }
Builds a list with at least one example .
31,135
public static < T > List < T > buildListOfAtLeastTwo ( T first , T second , T ... more ) { if ( first == null ) { throw new IllegalArgumentException ( "First example is null." ) ; } if ( second == null ) { throw new IllegalArgumentException ( "Second example is null." ) ; } List < T > result = new ArrayList < > ( ) ; result . add ( first ) ; result . add ( second ) ; addArrayElementsToList ( result , more ) ; return result ; }
Builds a list with at least two examples .
31,136
public static < T > boolean listContainsDuplicates ( List < T > list ) { return list . size ( ) != new HashSet < > ( list ) . size ( ) ; }
Determines whether a list contains the same example more than once .
31,137
public static void assertEquals ( Formatter message , Object expected , Object actual ) { if ( ! expected . equals ( actual ) ) { throw new AssertionException ( message ) ; } }
Asserts that two Objects are equal to one another . Does nothing if they are ; throws an AssertionException if they re not .
31,138
public T instantiateAnonymousSubclass ( ) { Class < T > proxyClass = giveDynamicSubclass ( type ) ; return objenesis . newInstance ( proxyClass ) ; }
Instantiates an anonymous subclass of T . The subclass is generated dynamically .
31,139
@ SuppressWarnings ( "unchecked" ) public static < T > Class < T > classForName ( String className ) { try { return ( Class < T > ) Class . forName ( className ) ; } catch ( ClassNotFoundException | VerifyError e ) { return null ; } }
Helper method to resolve a Class of a given name .
31,140
public static Object [ ] objects ( Object first , Object second , Object third ) { return new Object [ ] { first , second , third } ; }
Helper method to create an array of Objects .
31,141
public static < T > Set < T > setOf ( T ... ts ) { return new HashSet < > ( Arrays . asList ( ts ) ) ; }
Helper method to create a set of object .
31,142
public < T > void put ( TypeTag tag , T red , T black , T redCopy ) { cache . put ( tag , new Tuple < > ( red , black , redCopy ) ) ; }
Adds a prefabricated value to the cache for the given type .
31,143
public < T > EqualsVerifierApi < T > forClass ( Class < T > type ) { return new EqualsVerifierApi < > ( type , EnumSet . copyOf ( warningsToSuppress ) , factoryCache , usingGetClass ) ; }
Factory method . For general use .
31,144
public T copy ( ) { T copy = Instantiator . of ( type ) . instantiate ( ) ; return copyInto ( copy ) ; }
Creates a copy of the wrapped object .
31,145
public < S extends T > S copyIntoSubclass ( Class < S > subclass ) { S copy = Instantiator . of ( subclass ) . instantiate ( ) ; return copyInto ( copy ) ; }
Creates a copy of the wrapped object where the copy s type is a specified subclass of the wrapped object s class .
31,146
public T copyIntoAnonymousSubclass ( ) { T copy = Instantiator . of ( type ) . instantiateAnonymousSubclass ( ) ; return copyInto ( copy ) ; }
Creates a copy of the wrapped object where the copy type is an anonymous subclass of the wrapped object s class .
31,147
public void scramble ( PrefabValues prefabValues , TypeTag enclosingType ) { for ( Field field : FieldIterable . of ( type ) ) { FieldAccessor accessor = new FieldAccessor ( object , field ) ; accessor . changeField ( prefabValues , enclosingType ) ; } }
Modifies all fields of the wrapped object that are declared in T and in its superclasses .
31,148
public void shallowScramble ( PrefabValues prefabValues , TypeTag enclosingType ) { for ( Field field : FieldIterable . ofIgnoringSuper ( type ) ) { FieldAccessor accessor = new FieldAccessor ( object , field ) ; accessor . changeField ( prefabValues , enclosingType ) ; } }
Modifies all fields of the wrapped object that are declared in T but not those inherited from superclasses .
31,149
public static boolean fieldIsNonnull ( Field field , AnnotationCache annotationCache ) { Class < ? > type = field . getDeclaringClass ( ) ; if ( annotationCache . hasFieldAnnotation ( type , field . getName ( ) , NONNULL ) ) { return true ; } if ( annotationCache . hasFieldAnnotation ( type , field . getName ( ) , NULLABLE ) ) { return false ; } return annotationCache . hasClassAnnotation ( type , FINDBUGS1X_DEFAULT_ANNOTATION_NONNULL ) || annotationCache . hasClassAnnotation ( type , JSR305_DEFAULT_ANNOTATION_NONNULL ) || annotationCache . hasClassAnnotation ( type , ECLIPSE_DEFAULT_ANNOTATION_NONNULL ) ; }
Checks whether the given field is marked with an Nonnull annotation whether directly or through some default annotation mechanism .
31,150
public boolean declaresField ( Field field ) { try { type . getDeclaredField ( field . getName ( ) ) ; return true ; } catch ( NoSuchFieldException e ) { return false ; } }
Determines whether T declares a field . This does not include inherited fields .
31,151
@ SuppressFBWarnings ( value = "DP_DO_INSIDE_DO_PRIVILEGED" , justification = "EV is run only from within unit tests" ) public < T > T instantiate ( Class < ? > [ ] paramTypes , Object [ ] paramValues ) { try { Class < T > type = resolve ( ) ; if ( type == null ) { return null ; } Constructor < T > c = type . getConstructor ( paramTypes ) ; c . setAccessible ( true ) ; return c . newInstance ( paramValues ) ; } catch ( Exception e ) { return handleException ( e ) ; } }
Attempts to instantiate the type .
31,152
public < T > T callFactory ( String factoryMethod , Class < ? > [ ] paramTypes , Object [ ] paramValues ) { return callFactory ( fullyQualifiedClassName , factoryMethod , paramTypes , paramValues ) ; }
Attempts to call a static factory method on the type .
31,153
@ SuppressFBWarnings ( value = "DP_DO_INSIDE_DO_PRIVILEGED" , justification = "EV is run only from within unit tests" ) @ SuppressWarnings ( "unchecked" ) public < T > T callFactory ( String factoryTypeName , String factoryMethod , Class < ? > [ ] paramTypes , Object [ ] paramValues ) { try { Class < T > type = resolve ( ) ; if ( type == null ) { return null ; } Class < ? > factoryType = Class . forName ( factoryTypeName ) ; Method factory = factoryType . getMethod ( factoryMethod , paramTypes ) ; factory . setAccessible ( true ) ; return ( T ) factory . invoke ( null , paramValues ) ; } catch ( Exception e ) { return handleException ( e ) ; } }
Attempts to call a static factory method on a type .
31,154
@ SuppressFBWarnings ( value = "DP_DO_INSIDE_DO_PRIVILEGED" , justification = "EV is run only from within unit tests" ) @ SuppressWarnings ( "unchecked" ) public < T > T returnConstant ( String constantName ) { try { Class < T > type = resolve ( ) ; if ( type == null ) { return null ; } Field field = type . getField ( constantName ) ; field . setAccessible ( true ) ; return ( T ) field . get ( null ) ; } catch ( Exception e ) { return handleException ( e ) ; } }
Attempts to resolve a static constant on the type .
31,155
@ SuppressWarnings ( "unchecked" ) public static < U > Tuple < U > of ( Object red , Object black , Object redCopy ) { return new Tuple < > ( ( U ) red , ( U ) black , ( U ) redCopy ) ; }
Factory method that turns three untyped values into a typed tuple .
31,156
public static < T > SuperclassIterable < T > of ( Class < T > type ) { return new SuperclassIterable < > ( type , false ) ; }
Factory method for a SuperlcassIterator that iterates over type s superclasses excluding itself and excluding Object .
31,157
public static < T > SuperclassIterable < T > ofIncludeSelf ( Class < T > type ) { return new SuperclassIterable < > ( type , true ) ; }
Factory method for a SuperlcassIterator that iterates over type s superclasses including itself but excluding Object .
31,158
public static < T > RelaxedEqualsVerifierApi < T > forRelaxedEqualExamples ( T first , T second , T ... more ) { List < T > examples = ListBuilders . buildListOfAtLeastTwo ( first , second , more ) ; @ SuppressWarnings ( "unchecked" ) Class < T > type = ( Class < T > ) first . getClass ( ) ; return new RelaxedEqualsVerifierApi < > ( type , examples ) ; }
Factory method . Asks for a list of equal but not identical instances of T .
31,159
@ SuppressFBWarnings ( value = "DP_DO_INSIDE_DO_PRIVILEGED" , justification = "Only called in test code, not production." ) public Object get ( ) { field . setAccessible ( true ) ; try { return field . get ( object ) ; } catch ( IllegalAccessException e ) { throw new ReflectionException ( e ) ; } }
Tries to get the field s value .
31,160
public void copyTo ( Object to ) { modify ( ( ) -> field . set ( to , field . get ( object ) ) , false ) ; }
Copies field s value to the corresponding field in the specified object .
31,161
public void changeField ( PrefabValues prefabValues , TypeTag enclosingType ) { modify ( ( ) -> { Object newValue = prefabValues . giveOther ( TypeTag . of ( field , enclosingType ) , field . get ( object ) ) ; field . set ( object , newValue ) ; } , false ) ; }
Changes the field s value to something else . The new value will never be null . Other than that the precise value is undefined .
31,162
public boolean canBeModifiedReflectively ( ) { if ( field . isSynthetic ( ) ) { return false ; } int modifiers = field . getModifiers ( ) ; if ( Modifier . isFinal ( modifiers ) && Modifier . isStatic ( modifiers ) ) { return false ; } return true ; }
Determines whether the field can be modified using reflection .
31,163
public EqualsVerifierApi < T > withIgnoredAnnotations ( Class < ? > ... annotations ) { Validations . validateGivenAnnotations ( annotations ) ; for ( Class < ? > ignoredAnnotation : annotations ) { ignoredAnnotationClassNames . add ( ignoredAnnotation . getCanonicalName ( ) ) ; } return this ; }
Signals that all given annotations are to be ignored by EqualsVerifier .
31,164
public String format ( ) { String result = message ; for ( Object object : objects ) { String s = result . replaceFirst ( "%%" , Matcher . quoteReplacement ( stringify ( object ) ) ) ; if ( result . equals ( s ) ) { throw new IllegalStateException ( "Too many parameters" ) ; } result = s ; } if ( result . contains ( "%%" ) ) { throw new IllegalStateException ( "Not enough parameters" ) ; } return result ; }
Formats the message with the given objects .
31,165
public static < T > T callConstructor ( Class < T > targetClass , Class [ ] argClasses , Object [ ] args ) { T output ; try { Constructor classConstructor = targetClass . getDeclaredConstructor ( argClasses ) ; output = AccessController . doPrivileged ( new SetConstructorPrivilegedAction < T > ( classConstructor , args ) ) ; } catch ( NoSuchMethodException e ) { throw new ParcelerRuntimeException ( "Exception during method injection: NoSuchMethodException" , e ) ; } catch ( PrivilegedActionException e ) { throw new ParcelerRuntimeException ( "PrivilegedActionException Exception during field injection" , e ) ; } catch ( Exception e ) { throw new ParcelerRuntimeException ( "Exception during field injection" , e ) ; } return output ; }
Instantiates a class by calling the constructor .
31,166
public static int initialHashMapCapacity ( int expectedSize ) { if ( expectedSize < 0 ) { throw new ParcelerRuntimeException ( "Expected size must be non-negative" ) ; } if ( expectedSize < 3 ) { return expectedSize + 1 ; } if ( expectedSize < MAX_POWER_OF_TWO ) { return ( int ) ( ( float ) expectedSize / 0.75F + 1.0F ) ; } return Integer . MAX_VALUE ; }
Copy of capacity method from Guava Maps utility .
31,167
public RestHandlerExceptionResolverBuilder defaultContentType ( String mediaType ) { defaultContentType ( hasText ( mediaType ) ? MediaType . parseMediaType ( mediaType ) : null ) ; return this ; }
The default content type that will be used as a fallback when the requested content type is not supported .
31,168
public < E extends Exception > RestHandlerExceptionResolverBuilder addHandler ( Class < ? extends E > exceptionClass , RestExceptionHandler < E , ? > exceptionHandler ) { exceptionHandlers . put ( exceptionClass , exceptionHandler ) ; return this ; }
Registers the given exception handler for the specified exception type . This handler will be also used for all the exception subtypes when no more specific mapping is found .
31,169
public Set < String > getSkipBuildPhrases ( ) { return new HashSet < String > ( Arrays . asList ( getTrigger ( ) . getSkipBuildPhrase ( ) . split ( "[\\r\\n]+" ) ) ) ; }
Returns skip build phrases from Jenkins global configuration
31,170
public String checkBlackListCommitAuthor ( String author ) { Set < String > authors = getBlacklistedCommitAuthors ( ) ; authors . remove ( "" ) ; Map < Pattern , String > skipPatterns = new HashMap < Pattern , String > ( ) ; for ( String s : authors ) { s = s . trim ( ) ; if ( compilePattern ( s ) . matcher ( author ) . matches ( ) ) { return s ; } } return null ; }
Checks for skip build commit author .
31,171
public String checkSkipBuildPhrase ( GHIssue issue ) { Set < String > skipBuildPhrases = getSkipBuildPhrases ( ) ; skipBuildPhrases . remove ( "" ) ; Map < Pattern , String > skipPatterns = new HashMap < Pattern , String > ( ) ; for ( String skipBuildPhrase : skipBuildPhrases ) { skipBuildPhrase = skipBuildPhrase . trim ( ) ; skipPatterns . put ( compilePattern ( skipBuildPhrase ) , skipBuildPhrase ) ; } String pullRequestTitle = issue . getTitle ( ) ; String skipBuildPhrase = checkSkipBuildInString ( skipPatterns , pullRequestTitle ) ; if ( StringUtils . isNotBlank ( skipBuildPhrase ) ) { return skipBuildPhrase ; } String pullRequestBody = issue . getBody ( ) ; skipBuildPhrase = checkSkipBuildInString ( skipPatterns , pullRequestBody ) ; if ( StringUtils . isNotBlank ( skipBuildPhrase ) ) { return skipBuildPhrase ; } return null ; }
Checks for skip build phrase in pull request title and body . If present it updates shouldRun as false .
31,172
private String checkSkipBuildInString ( Map < Pattern , String > patterns , String string ) { if ( ! patterns . isEmpty ( ) && StringUtils . isNotBlank ( string ) ) { for ( Map . Entry < Pattern , String > e : patterns . entrySet ( ) ) { if ( e . getKey ( ) . matcher ( string ) . matches ( ) ) { return e . getValue ( ) ; } } } return null ; }
Checks for skip pattern in the passed string
31,173
private Map < String , String > returnEnvironmentVars ( AbstractBuild < ? , ? > build , TaskListener listener ) { Map < String , String > envVars = Ghprb . getEnvVars ( build , listener ) ; if ( ! envVars . containsKey ( "ghprbUpstreamStatus" ) ) { return null ; } GhprbGitHubAuth auth = GhprbTrigger . getDscp ( ) . getGitHubAuth ( envVars . get ( "ghprbCredentialsId" ) ) ; try { GitHub gh = auth . getConnection ( build . getProject ( ) ) ; repo = gh . getRepository ( envVars . get ( "ghprbGhRepository" ) ) ; return envVars ; } catch ( Exception e ) { LOGGER . log ( Level . SEVERE , "Unable to connect to GitHub repo" , e ) ; return null ; } }
Gets all the custom env vars needed to send information to GitHub
31,174
public Environment setUpEnvironment ( @ SuppressWarnings ( "rawtypes" ) AbstractBuild build , Launcher launcher , BuildListener listener ) { Map < String , String > envVars = returnEnvironmentVars ( build , listener ) ; if ( envVars != null ) { LOGGER . log ( Level . FINE , "Job: " + build . getFullDisplayName ( ) + " Attempting to send GitHub commit status" ) ; try { returnGhprbSimpleStatus ( envVars ) . onEnvironmentSetup ( build , listener , repo ) ; } catch ( GhprbCommitStatusException e ) { e . printStackTrace ( ) ; } } return new Environment ( ) { } ; }
Sets the status as pending when the job starts and then calls the createCommitStatus method to send it to GitHub
31,175
public void onCompleted ( AbstractBuild < ? , ? > build , TaskListener listener ) { Map < String , String > envVars = returnEnvironmentVars ( build , listener ) ; if ( envVars == null ) { return ; } try { returnGhprbSimpleStatus ( envVars ) . onBuildComplete ( build , listener , repo ) ; } catch ( GhprbCommitStatusException e ) { e . printStackTrace ( ) ; } }
Sets the status to the build result when the job is done and then calls the createCommitStatus method to send it to GitHub
31,176
@ SuppressWarnings ( "unchecked" ) public String calculateBuildUrl ( String publishedURL ) { Iterator < JobInvocation > iterator = ( Iterator < JobInvocation > ) downstreamProjects ( ) ; StringBuilder sb = new StringBuilder ( ) ; while ( iterator . hasNext ( ) ) { JobInvocation jobInvocation = iterator . next ( ) ; sb . append ( "\n" ) ; sb . append ( "<a href='" ) ; sb . append ( jobInvocation . getBuildUrl ( ) ) ; sb . append ( "'>" ) ; sb . append ( jobInvocation . getBuildUrl ( ) ) ; sb . append ( "</a>" ) ; } return sb . toString ( ) ; }
Calculate the build URL of a build of BuildFlow type traversing its downstream builds graph
31,177
public Iterator < ? > downstreamProjects ( ) { FlowRun flowRun = ( FlowRun ) build ; DirectedGraph < JobInvocation , FlowRun . JobEdge > directedGraph = flowRun . getJobsGraph ( ) ; return directedGraph . vertexSet ( ) . iterator ( ) ; }
Return a downstream iterator of a build of default type . This will be overriden by specific build types .
31,178
void commitStatus ( Runnable closure ) { GhprbSimpleStatusContext context = new GhprbSimpleStatusContext ( ) ; ContextExtensionPoint . executeInContext ( closure , context ) ; extensions . add ( new GhprbSimpleStatus ( context . showMatrixStatus , context . context , context . statusUrl , context . triggeredStatus , context . startedStatus , context . addTestResults , context . completedStatus ) ) ; }
Updates the commit status during the build .
31,179
void buildStatus ( Runnable closure ) { GhprbBuildStatusContext context = new GhprbBuildStatusContext ( ) ; ContextExtensionPoint . executeInContext ( closure , context ) ; extensions . add ( new GhprbBuildStatus ( context . getCompletedStatus ( ) ) ) ; }
Adds build result messages
31,180
void commentFilePath ( Runnable closure ) { GhprbCommentFilePathContext context = new GhprbCommentFilePathContext ( ) ; ContextExtensionPoint . executeInContext ( closure , context ) ; extensions . add ( new GhprbCommentFile ( context . getCommentFilePath ( ) ) ) ; }
Adds comment file path handling
31,181
void cancelBuildsOnUpdate ( Runnable closure ) { GhprbCancelBuildsOnUpdateContext context = new GhprbCancelBuildsOnUpdateContext ( ) ; ContextExtensionPoint . executeInContext ( closure , context ) ; extensions . add ( new GhprbCancelBuildsOnUpdate ( context . getOverrideGlobal ( ) ) ) ; }
Overrides global settings for cancelling builds when a PR was updated
31,182
public void makeBuildVariables ( @ SuppressWarnings ( "rawtypes" ) AbstractBuild build , Map < String , String > variables ) { variables . put ( "ghprbShowMatrixStatus" , Boolean . toString ( getShowMatrixStatus ( ) ) ) ; variables . put ( "ghprbUpstreamStatus" , "true" ) ; variables . put ( "ghprbCommitStatusContext" , getCommitStatusContext ( ) ) ; variables . put ( "ghprbTriggeredStatus" , getTriggeredStatus ( ) ) ; variables . put ( "ghprbStartedStatus" , getStartedStatus ( ) ) ; variables . put ( "ghprbStatusUrl" , getStatusUrl ( ) ) ; variables . put ( "ghprbAddTestResults" , Boolean . toString ( getAddTestResults ( ) ) ) ; Map < GHCommitState , StringBuilder > statusMessages = new HashMap < GHCommitState , StringBuilder > ( INITIAL_CAPACITY ) ; for ( GhprbBuildResultMessage message : getCompletedStatus ( ) ) { GHCommitState state = message . getResult ( ) ; StringBuilder sb ; if ( ! statusMessages . containsKey ( state ) ) { sb = new StringBuilder ( ) ; statusMessages . put ( state , sb ) ; } else { sb = statusMessages . get ( state ) ; sb . append ( "\n" ) ; } sb . append ( message . getMessage ( ) ) ; } for ( Entry < GHCommitState , StringBuilder > next : statusMessages . entrySet ( ) ) { String key = String . format ( "ghprb%sMessage" , next . getKey ( ) . name ( ) ) ; variables . put ( key , next . getValue ( ) . toString ( ) ) ; } }
sets the context and message as env vars so that they are available in the Listener class
31,183
private static List < GhprbExtensionDescriptor > getExtensions ( ) { List < GhprbExtensionDescriptor > list = new ArrayList < GhprbExtensionDescriptor > ( ) ; list . addAll ( getExtensionList ( ) ) ; return list ; }
Don t mutate the list from Jenkins they will persist ;
31,184
public void whiteListTargetBranches ( Iterable < String > branches ) { for ( String branch : branches ) { whiteListTargetBranches . add ( new GhprbBranch ( branch ) ) ; } }
Add branch names whose they are considered whitelisted for this specific job
31,185
public void blackListTargetBranches ( Iterable < String > branches ) { for ( String branch : branches ) { blackListTargetBranches . add ( new GhprbBranch ( branch ) ) ; } }
Add branch names whose they are considered blacklisted for this specific job
31,186
private boolean setUpdated ( Date lastUpdateTime ) { if ( updated == null || updated . compareTo ( lastUpdateTime ) < 0 ) { updated = lastUpdateTime ; return true ; } return false ; }
return true false otherwise .
31,187
private boolean containsComment ( GHPullRequest ghPullRequest , String expectedBody ) { List < GHIssueComment > prComments ; try { prComments = ghPullRequest . getComments ( ) ; } catch ( IOException e ) { LOGGER . log ( Level . WARNING , "Failed to get comments for PR " + ghPullRequest , e ) ; return false ; } for ( GHIssueComment comment : prComments ) { if ( comment . getBody ( ) != null && comment . getBody ( ) . equals ( expectedBody ) ) { return true ; } } return false ; }
Checks whether the specific PR contains a comment with the expected body .
31,188
public void check ( GHPullRequest ghpr , boolean isWebhook ) { if ( helper . isProjectDisabled ( ) ) { LOGGER . log ( Level . FINE , "Project is disabled, ignoring pull request" ) ; return ; } updatePR ( ghpr , null , isWebhook ) ; commitAuthor = getPRCommitAuthor ( ) ; checkSkipBuild ( ) ; checkBlackListLabels ( ) ; checkWhiteListLabels ( ) ; tryBuild ( ) ; }
Checks this Pull Request representation against a GitHub version of the Pull Request and triggers a build if necessary .
31,189
public boolean isAllowedTargetBranch ( ) { List < GhprbBranch > whiteListBranches = helper . getWhiteListTargetBranches ( ) ; List < GhprbBranch > blackListBranches = helper . getBlackListTargetBranches ( ) ; String target = getTarget ( ) ; if ( ! whiteListBranches . isEmpty ( ) ) { if ( ! matchesAnyBranch ( target , whiteListBranches ) ) { LOGGER . log ( Level . FINEST , "PR #{0} target branch: {1} isn''t in our whitelist of target branches: {2}" , new Object [ ] { id , target , Joiner . on ( ',' ) . skipNulls ( ) . join ( whiteListBranches ) } ) ; return false ; } } if ( ! blackListBranches . isEmpty ( ) ) { if ( matchesAnyBranch ( target , blackListBranches ) ) { LOGGER . log ( Level . FINEST , "PR #{0} target branch: {1} is in our blacklist of target branches: {2}" , new Object [ ] { id , target , Joiner . on ( ',' ) . skipNulls ( ) . join ( blackListBranches ) } ) ; return false ; } } return true ; }
but NOT any branches in the blacklist .
31,190
private boolean checkCommit ( GHPullRequest pr ) { GHCommitPointer head = pr . getHead ( ) ; GHCommitPointer base = pr . getBase ( ) ; String headSha = head . getSha ( ) ; String baseSha = base . getSha ( ) ; if ( StringUtils . equals ( headSha , this . head ) && StringUtils . equals ( baseSha , this . base ) ) { return false ; } LOGGER . log ( Level . FINE , "New commit. Sha: Head[{0} => {1}] Base[{2} => {3}]" , new Object [ ] { this . head , headSha , this . base , baseSha } ) ; setHead ( headSha ) ; setBase ( baseSha ) ; if ( accepted ) { shouldRun = true ; } return true ; }
returns false if no new commit
31,191
public GHPullRequest getPullRequest ( boolean force ) throws IOException { if ( this . pr == null || force ) { setPullRequest ( repo . getActualPullRequest ( this . id ) ) ; } return pr ; }
Get the PullRequest object for this PR
31,192
public String getAuthorEmail ( ) { if ( StringUtils . isEmpty ( authorEmail ) ) { try { GHUser user = getPullRequestAuthor ( ) ; authorEmail = user . getEmail ( ) ; } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , "Unable to fetch author info for " + id ) ; } } authorEmail = StringUtils . isEmpty ( authorEmail ) ? "" : authorEmail ; return authorEmail ; }
Email address is collected from GitHub as extra information so lets cache it .
31,193
private void initHandlers ( ) { registerHandler ( Boolean . class , BooleanOptionHandler . class ) ; registerHandler ( boolean . class , BooleanOptionHandler . class ) ; registerHandler ( File . class , FileOptionHandler . class ) ; registerHandler ( URL . class , URLOptionHandler . class ) ; registerHandler ( URI . class , URIOptionHandler . class ) ; registerHandler ( Integer . class , IntOptionHandler . class ) ; registerHandler ( int . class , IntOptionHandler . class ) ; registerHandler ( Double . class , DoubleOptionHandler . class ) ; registerHandler ( double . class , DoubleOptionHandler . class ) ; registerHandler ( String . class , StringOptionHandler . class ) ; registerHandler ( Byte . class , ByteOptionHandler . class ) ; registerHandler ( byte . class , ByteOptionHandler . class ) ; registerHandler ( Character . class , CharOptionHandler . class ) ; registerHandler ( char . class , CharOptionHandler . class ) ; registerHandler ( Float . class , FloatOptionHandler . class ) ; registerHandler ( float . class , FloatOptionHandler . class ) ; registerHandler ( Long . class , LongOptionHandler . class ) ; registerHandler ( long . class , LongOptionHandler . class ) ; registerHandler ( Short . class , ShortOptionHandler . class ) ; registerHandler ( short . class , ShortOptionHandler . class ) ; registerHandler ( InetAddress . class , InetAddressOptionHandler . class ) ; registerHandler ( Pattern . class , PatternOptionHandler . class ) ; registerHandler ( Map . class , MapOptionHandler . class ) ; try { Class p = Class . forName ( "java.nio.file.Path" ) ; registerHandler ( p , PathOptionHandler . class ) ; } catch ( ClassNotFoundException e ) { } }
Registers the default handlers .
31,194
private static Constructor < ? extends OptionHandler > getConstructor ( Class < ? extends OptionHandler > handlerClass ) { try { return handlerClass . getConstructor ( CmdLineParser . class , OptionDef . class , Setter . class ) ; } catch ( NoSuchMethodException e ) { throw new IllegalArgumentException ( Messages . NO_CONSTRUCTOR_ON_HANDLER . format ( handlerClass ) ) ; } }
Finds the constructor for an option handler .
31,195
protected void addToMap ( String argument , Map m ) throws CmdLineException { if ( String . valueOf ( argument ) . indexOf ( '=' ) == - 1 ) { throw new CmdLineException ( owner , Messages . FORMAT_ERROR_FOR_MAP ) ; } String mapKey ; String mapValue ; int idx = argument . indexOf ( '=' ) ; if ( idx >= 0 ) { mapKey = argument . substring ( 0 , idx ) ; mapValue = argument . substring ( idx + 1 ) ; if ( mapValue . length ( ) == 0 ) mapValue = null ; } else { mapKey = argument ; mapValue = null ; } if ( mapKey . length ( ) == 0 ) { throw new CmdLineException ( owner , Messages . MAP_HAS_NO_KEY ) ; } addToMap ( m , mapKey , mapValue ) ; }
Encapsulates how a single string argument gets converted into key and value .
31,196
protected void addToMap ( Map m , String key , String value ) { m . put ( key , value ) ; }
This is the opportunity to convert values to some typed objects .
31,197
private void trySetDefault ( Object bean1 ) throws IllegalAccessError { try { doSetDefault ( bean1 ) ; } catch ( IllegalAccessException ex ) { try { f . setAccessible ( true ) ; doSetDefault ( bean1 ) ; } catch ( IllegalAccessException ex1 ) { throw new IllegalAccessError ( ex1 . getMessage ( ) ) ; } } }
Remember default so we throw away the default when adding user values .
31,198
public String printExample ( OptionHandlerFilter mode , ResourceBundle rb ) { StringBuilder buf = new StringBuilder ( ) ; checkNonNull ( mode , "mode" ) ; for ( OptionHandler h : options ) { OptionDef option = h . option ; if ( option . usage ( ) . length ( ) == 0 ) continue ; if ( ! mode . select ( h ) ) continue ; buf . append ( ' ' ) ; buf . append ( h . getNameAndMeta ( rb , parserProperties ) ) ; } return buf . toString ( ) ; }
Formats a command line example into a string .
31,199
protected void printOption ( PrintWriter out , OptionHandler handler , int len , ResourceBundle rb , OptionHandlerFilter filter ) { if ( handler . option . usage ( ) == null || handler . option . usage ( ) . length ( ) == 0 || ! filter . select ( handler ) ) { return ; } int totalUsageWidth = parserProperties . getUsageWidth ( ) ; int widthMetadata = Math . min ( len , ( totalUsageWidth - 4 ) / 2 ) ; int widthUsage = totalUsageWidth - 4 - widthMetadata ; String defaultValuePart = createDefaultValuePart ( handler ) ; List < String > namesAndMetas = wrapLines ( handler . getNameAndMeta ( rb , parserProperties ) , widthMetadata ) ; List < String > usages = wrapLines ( localize ( handler . option . usage ( ) , rb ) + defaultValuePart , widthUsage ) ; for ( int i = 0 ; i < Math . max ( namesAndMetas . size ( ) , usages . size ( ) ) ; i ++ ) { String nameAndMeta = ( i >= namesAndMetas . size ( ) ) ? "" : namesAndMetas . get ( i ) ; String usage = ( i >= usages . size ( ) ) ? "" : usages . get ( i ) ; String format = ( ( nameAndMeta . length ( ) > 0 ) && ( i == 0 ) ) ? " %1$-" + widthMetadata + "s : %2$-1s" : " %1$-" + widthMetadata + "s %2$-1s" ; String output = String . format ( format , nameAndMeta , usage ) ; out . println ( output ) ; } }
Prints usage information for a given option .