idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
23,600
public static boolean unregister ( String name ) { Iterator < IpCamDevice > di = DEVICES . iterator ( ) ; while ( di . hasNext ( ) ) { IpCamDevice d = di . next ( ) ; if ( d . getName ( ) . equals ( name ) ) { di . remove ( ) ; rescan ( ) ; return true ; } } return false ; }
Unregister IP camera with given name .
23,601
protected static void store ( Webcam [ ] webcams ) { if ( HANDLER . get ( ) == null ) { HANDLER . set ( new WebcamDeallocator ( webcams ) ) ; } else { throw new IllegalStateException ( "Deallocator is already set!" ) ; } }
Store devices to be deallocated when TERM signal has been received .
23,602
public void motionDetected ( WebcamMotionEvent wme ) { for ( Point p : wme . getPoints ( ) ) { motionPoints . put ( p , 0 ) ; } }
Gets the motion points from the motion detector and adds it to the HashMap
23,603
public JobReport execute ( Job job ) { try { return executorService . submit ( job ) . get ( ) ; } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException ( "Unable to execute job " + job . getName ( ) , e ) ; } }
Execute a job synchronously .
23,604
public void awaitTermination ( long timeout , TimeUnit unit ) { try { executorService . awaitTermination ( timeout , unit ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( "Job executor was interrupted while waiting" ) ; } }
Wait for jobs to terminate .
23,605
public T mapObject ( final Map < String , String > values ) throws Exception { T result = createInstance ( ) ; for ( Map . Entry < String , String > entry : values . entrySet ( ) ) { String field = entry . getKey ( ) ; String value = values . get ( field ) ; Method setter = setters . get ( field ) ; if ( setter == null ) { LOGGER . warn ( "No public setter found for field {}, this field will be set to null (if object type) or default value (if primitive type)" , field ) ; continue ; } Class < ? > type = setter . getParameterTypes ( ) [ 0 ] ; TypeConverter < String , ? > typeConverter = typeConverters . get ( type ) ; if ( typeConverter == null ) { LOGGER . warn ( "Type conversion not supported for type {}, field {} will be set to null (if object type) or default value (if primitive type)" , type , field ) ; continue ; } if ( value == null ) { LOGGER . warn ( "Attempting to convert null to type {} for field {}, this field will be set to null (if object type) or default value (if primitive type)" , type , field ) ; continue ; } if ( value . isEmpty ( ) ) { LOGGER . debug ( "Attempting to convert an empty string to type {} for field {}, this field will be ignored" , type , field ) ; continue ; } convertValue ( result , field , value , setter , type , typeConverter ) ; } return result ; }
Map values to fields of the target object type .
23,606
public void scheduleAtWithInterval ( final org . easybatch . core . job . Job job , final Date startTime , final int interval ) throws JobSchedulerException { checkNotNull ( job , "job" ) ; checkNotNull ( startTime , "startTime" ) ; String name = job . getName ( ) ; String jobName = JOB_NAME_PREFIX + name ; String triggerName = TRIGGER_NAME_PREFIX + name ; SimpleScheduleBuilder scheduleBuilder = simpleSchedule ( ) . withIntervalInSeconds ( interval ) . repeatForever ( ) ; Trigger trigger = newTrigger ( ) . withIdentity ( triggerName ) . startAt ( startTime ) . withSchedule ( scheduleBuilder ) . forJob ( jobName ) . build ( ) ; JobDetail jobDetail = getJobDetail ( job , jobName ) ; try { LOGGER . info ( "Scheduling job ''{}'' to start at {} and every {} second(s)" , name , startTime , interval ) ; scheduler . scheduleJob ( jobDetail , trigger ) ; } catch ( SchedulerException e ) { throw new JobSchedulerException ( format ( "Unable to schedule job '%s'" , name ) , e ) ; } }
Schedule a job to start at a fixed point of time and repeat with interval period .
23,607
public void unschedule ( final org . easybatch . core . job . Job job ) throws JobSchedulerException { String jobName = job . getName ( ) ; LOGGER . info ( "Unscheduling job ''{}'' " , jobName ) ; try { scheduler . unscheduleJob ( TriggerKey . triggerKey ( TRIGGER_NAME_PREFIX + jobName ) ) ; } catch ( SchedulerException e ) { throw new JobSchedulerException ( format ( "Unable to unschedule job '%s'" , jobName ) , e ) ; } }
Unschedule the given job .
23,608
public boolean isScheduled ( final org . easybatch . core . job . Job job ) throws JobSchedulerException { String jobName = job . getName ( ) ; try { return scheduler . checkExists ( TriggerKey . triggerKey ( TRIGGER_NAME_PREFIX + jobName ) ) ; } catch ( SchedulerException e ) { throw new JobSchedulerException ( format ( "Unable to check if the job '%s' is scheduled" , jobName ) , e ) ; } }
Check if the given job is scheduled .
23,609
public JobReport mergerReports ( JobReport ... jobReports ) { List < Long > startTimes = new ArrayList < > ( ) ; List < Long > endTimes = new ArrayList < > ( ) ; List < String > jobNames = new ArrayList < > ( ) ; JobParameters parameters = new JobParameters ( ) ; JobMetrics metrics = new JobMetrics ( ) ; JobReport finalJobReport = new JobReport ( ) ; finalJobReport . setParameters ( parameters ) ; finalJobReport . setMetrics ( metrics ) ; finalJobReport . setStatus ( JobStatus . COMPLETED ) ; for ( JobReport jobReport : jobReports ) { startTimes . add ( jobReport . getMetrics ( ) . getStartTime ( ) ) ; endTimes . add ( jobReport . getMetrics ( ) . getEndTime ( ) ) ; calculateReadRecords ( finalJobReport , jobReport ) ; calculateWrittenRecords ( finalJobReport , jobReport ) ; calculateFilteredRecords ( finalJobReport , jobReport ) ; calculateErrorRecords ( finalJobReport , jobReport ) ; setStatus ( finalJobReport , jobReport ) ; jobNames . add ( jobReport . getJobName ( ) ) ; finalJobReport . setSystemProperties ( jobReport . getSystemProperties ( ) ) ; } finalJobReport . getMetrics ( ) . setStartTime ( Collections . min ( startTimes ) ) ; finalJobReport . getMetrics ( ) . setEndTime ( Collections . max ( endTimes ) ) ; finalJobReport . setJobName ( concatenate ( jobNames ) ) ; return finalJobReport ; }
Merge multiple reports into a consolidated one .
23,610
public < T > T execute ( final Callable < T > callable ) throws Exception { int attempts = 0 ; int maxAttempts = retryPolicy . getMaxAttempts ( ) ; long delay = retryPolicy . getDelay ( ) ; TimeUnit timeUnit = retryPolicy . getTimeUnit ( ) ; while ( attempts < maxAttempts ) { try { attempts ++ ; beforeCall ( ) ; T result = callable . call ( ) ; afterCall ( result ) ; return result ; } catch ( Exception e ) { onException ( e ) ; if ( attempts >= maxAttempts ) { onMaxAttempts ( e ) ; throw e ; } beforeWait ( ) ; sleep ( timeUnit . toMillis ( delay ) ) ; afterWait ( ) ; } } return null ; }
Execute the callable with retries .
23,611
public static < P > List < P > extractPayloads ( final List < ? extends Record < P > > records ) { List < P > payloads = new ArrayList < > ( ) ; for ( Record < P > record : records ) { payloads . add ( record . getPayload ( ) ) ; } return payloads ; }
Extract the payload form each record .
23,612
private int [ ] calculateOffsets ( final int [ ] lengths ) { int [ ] offsets = new int [ lengths . length + 1 ] ; offsets [ 0 ] = 0 ; for ( int i = 0 ; i < lengths . length ; i ++ ) { offsets [ i + 1 ] = offsets [ i ] + lengths [ i ] ; } return offsets ; }
utility method to calculate field offsets used to extract fields from record .
23,613
public void setDelimiter ( final String delimiter ) { String prefix = "" ; if ( "|" . equals ( delimiter ) ) { prefix = "\\" ; } this . delimiter = prefix + delimiter ; }
Set the delimiter to use .
23,614
@ SuppressWarnings ( "unchecked" ) public void queue ( Consumer < ? super T > success , Consumer < ? super Throwable > failure ) { Route . CompiledRoute route = finalizeRoute ( ) ; Checks . notNull ( route , "Route" ) ; RequestBody data = finalizeData ( ) ; CaseInsensitiveMap < String , String > headers = finalizeHeaders ( ) ; BooleanSupplier finisher = getFinisher ( ) ; if ( success == null ) success = DEFAULT_SUCCESS == null ? FALLBACK_CONSUMER : DEFAULT_SUCCESS ; if ( failure == null ) failure = DEFAULT_FAILURE == null ? FALLBACK_CONSUMER : DEFAULT_FAILURE ; api . get ( ) . getRequester ( ) . request ( new Request < > ( this , success , failure , finisher , true , data , rawData , route , headers ) ) ; }
Submits a Request for execution .
23,615
public void reconnect ( boolean callFromQueue ) throws InterruptedException { Set < MDC . MDCCloseable > contextEntries = null ; Map < String , String > previousContext = null ; { ConcurrentMap < String , String > contextMap = api . getContextMap ( ) ; if ( callFromQueue && contextMap != null ) { previousContext = MDC . getCopyOfContextMap ( ) ; contextEntries = contextMap . entrySet ( ) . stream ( ) . map ( ( entry ) -> MDC . putCloseable ( entry . getKey ( ) , entry . getValue ( ) ) ) . collect ( Collectors . toSet ( ) ) ; } } if ( shutdown ) { api . setStatus ( JDA . Status . SHUTDOWN ) ; api . getEventManager ( ) . handle ( new ShutdownEvent ( api , OffsetDateTime . now ( ) , 1000 ) ) ; return ; } String message = "" ; if ( callFromQueue ) message = String . format ( "Queue is attempting to reconnect a shard...%s " , shardInfo != null ? " Shard: " + shardInfo . getShardString ( ) : "" ) ; LOG . debug ( "{}Attempting to reconnect in {}s" , message , reconnectTimeoutS ) ; while ( shouldReconnect ) { api . setStatus ( JDA . Status . WAITING_TO_RECONNECT ) ; int delay = reconnectTimeoutS ; Thread . sleep ( delay * 1000 ) ; handleIdentifyRateLimit = false ; api . setStatus ( JDA . Status . ATTEMPTING_TO_RECONNECT ) ; LOG . debug ( "Attempting to reconnect!" ) ; try { connect ( ) ; break ; } catch ( RejectedExecutionException ex ) { api . setStatus ( JDA . Status . SHUTDOWN ) ; api . getEventManager ( ) . handle ( new ShutdownEvent ( api , OffsetDateTime . now ( ) , 1000 ) ) ; return ; } catch ( RuntimeException ex ) { reconnectTimeoutS = Math . min ( reconnectTimeoutS << 1 , api . getMaxReconnectDelay ( ) ) ; LOG . warn ( "Reconnect failed! Next attempt in {}s" , reconnectTimeoutS ) ; } } if ( contextEntries != null ) contextEntries . forEach ( MDC . MDCCloseable :: close ) ; if ( previousContext != null ) previousContext . forEach ( MDC :: put ) ; }
This method is used to start the reconnect of the JDA instance . It is public for access from SessionReconnectQueue extensions .
23,616
public AuditableRestAction < Void > setNickname ( Member member , String nickname ) { Checks . notNull ( member , "Member" ) ; checkGuild ( member . getGuild ( ) , "Member" ) ; if ( member . equals ( getGuild ( ) . getSelfMember ( ) ) ) { if ( ! member . hasPermission ( Permission . NICKNAME_CHANGE ) && ! member . hasPermission ( Permission . NICKNAME_MANAGE ) ) throw new InsufficientPermissionException ( Permission . NICKNAME_CHANGE , "You neither have NICKNAME_CHANGE nor NICKNAME_MANAGE permission!" ) ; } else { checkPermission ( Permission . NICKNAME_MANAGE ) ; checkPosition ( member ) ; } if ( Objects . equals ( nickname , member . getNickname ( ) ) ) return new AuditableRestAction . EmptyRestAction < > ( getJDA ( ) , null ) ; if ( nickname == null ) nickname = "" ; JSONObject body = new JSONObject ( ) . put ( "nick" , nickname ) ; Route . CompiledRoute route ; if ( member . equals ( getGuild ( ) . getSelfMember ( ) ) ) route = Route . Guilds . MODIFY_SELF_NICK . compile ( getGuild ( ) . getId ( ) ) ; else route = Route . Guilds . MODIFY_MEMBER . compile ( getGuild ( ) . getId ( ) , member . getUser ( ) . getId ( ) ) ; return new AuditableRestAction < Void > ( getGuild ( ) . getJDA ( ) , route , body ) { protected void handleResponse ( Response response , Request < Void > request ) { if ( response . isOk ( ) ) request . onSuccess ( null ) ; else request . onFailure ( response ) ; } } ; }
Changes a Member s nickname in this guild . The nickname is visible to all members of this guild .
23,617
public AuditableRestAction < Void > unban ( String userId ) { Checks . isSnowflake ( userId , "User ID" ) ; checkPermission ( Permission . BAN_MEMBERS ) ; Route . CompiledRoute route = Route . Guilds . UNBAN . compile ( getGuild ( ) . getId ( ) , userId ) ; return new AuditableRestAction < Void > ( getGuild ( ) . getJDA ( ) , route ) { protected void handleResponse ( Response response , Request < Void > request ) { if ( response . isOk ( ) ) request . onSuccess ( null ) ; else if ( response . code == 404 ) request . onFailure ( new IllegalArgumentException ( "User with provided id \"" + userId + "\" is not banned! Cannot unban a user who is not currently banned!" ) ) ; else request . onFailure ( response ) ; } } ; }
Unbans the a user specified by the userId from this Guild .
23,618
public static void main ( String [ ] args ) { try { JDA jda = new JDABuilder ( "Your-Token-Goes-Here" ) . addEventListener ( new MessageListenerExample ( ) ) . build ( ) ; jda . awaitReady ( ) ; System . out . println ( "Finished Building JDA!" ) ; } catch ( LoginException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } }
This is the method where the program starts .
23,619
public List < AuditLogChange > getChangesForKeys ( AuditLogKey ... keys ) { Checks . notNull ( keys , "Keys" ) ; List < AuditLogChange > changes = new ArrayList < > ( keys . length ) ; for ( AuditLogKey key : keys ) { AuditLogChange change = getChangeByKey ( key ) ; if ( change != null ) changes . add ( change ) ; } return Collections . unmodifiableList ( changes ) ; }
Filters all changes by the specified keys
23,620
public DefaultShardManagerBuilder removeEventListenerProviders ( final Collection < IntFunction < Object > > listenerProviders ) { Checks . noneNull ( listenerProviders , "listener providers" ) ; this . listenerProviders . removeAll ( listenerProviders ) ; return this ; }
Removes all provided listener providers from the list of listener providers .
23,621
public MessageAction clearFiles ( BiConsumer < String , InputStream > finalizer ) { Checks . notNull ( finalizer , "Finalizer" ) ; for ( Iterator < Map . Entry < String , InputStream > > it = files . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Map . Entry < String , InputStream > entry = it . next ( ) ; finalizer . accept ( entry . getKey ( ) , entry . getValue ( ) ) ; it . remove ( ) ; } clearResources ( ) ; return this ; }
Clears all previously added files
23,622
public String getOldAvatarUrl ( ) { return previous == null ? null : String . format ( AVATAR_URL , getSelfUser ( ) . getId ( ) , previous , previous . startsWith ( "a_" ) ? ".gif" : ".png" ) ; }
The old avatar url
23,623
public String getNewAvatarUrl ( ) { return next == null ? null : String . format ( AVATAR_URL , getSelfUser ( ) . getId ( ) , next , next . startsWith ( "a_" ) ? ".gif" : ".png" ) ; }
The new avatar url
23,624
public boolean isEmpty ( ) { return title == null && description . length ( ) == 0 && timestamp == null && thumbnail == null && author == null && footer == null && image == null && fields . isEmpty ( ) ; }
Checks if the given embed is empty . Empty embeds will throw an exception if built
23,625
public final EmbedBuilder setDescription ( CharSequence description ) { this . description . setLength ( 0 ) ; if ( description != null && description . length ( ) >= 1 ) appendDescription ( description ) ; return this ; }
Sets the Description of the embed . This is where the main chunk of text for an embed is typically placed .
23,626
public EmbedBuilder appendDescription ( CharSequence description ) { Checks . notNull ( description , "description" ) ; Checks . check ( this . description . length ( ) + description . length ( ) <= MessageEmbed . TEXT_MAX_LENGTH , "Description cannot be longer than %d characters." , MessageEmbed . TEXT_MAX_LENGTH ) ; this . description . append ( description ) ; return this ; }
Appends to the description of the embed . This is where the main chunk of text for an embed is typically placed .
23,627
public EmbedBuilder setTimestamp ( TemporalAccessor temporal ) { if ( temporal == null ) { this . timestamp = null ; } else if ( temporal instanceof OffsetDateTime ) { this . timestamp = ( OffsetDateTime ) temporal ; } else { ZoneOffset offset ; try { offset = ZoneOffset . from ( temporal ) ; } catch ( DateTimeException ignore ) { offset = ZoneOffset . UTC ; } try { LocalDateTime ldt = LocalDateTime . from ( temporal ) ; this . timestamp = OffsetDateTime . of ( ldt , offset ) ; } catch ( DateTimeException ignore ) { try { Instant instant = Instant . from ( temporal ) ; this . timestamp = OffsetDateTime . ofInstant ( instant , offset ) ; } catch ( DateTimeException ex ) { throw new DateTimeException ( "Unable to obtain OffsetDateTime from TemporalAccessor: " + temporal + " of type " + temporal . getClass ( ) . getName ( ) , ex ) ; } } } return this ; }
Sets the Timestamp of the embed .
23,628
public EmbedBuilder setColor ( Color color ) { this . color = color == null ? Role . DEFAULT_COLOR_RAW : color . getRGB ( ) ; return this ; }
Sets the Color of the embed .
23,629
public EmbedBuilder setThumbnail ( String url ) { if ( url == null ) { this . thumbnail = null ; } else { urlCheck ( url ) ; this . thumbnail = new MessageEmbed . Thumbnail ( url , null , 0 , 0 ) ; } return this ; }
Sets the Thumbnail of the embed .
23,630
public EmbedBuilder setImage ( String url ) { if ( url == null ) { this . image = null ; } else { urlCheck ( url ) ; this . image = new MessageEmbed . ImageInfo ( url , null , 0 , 0 ) ; } return this ; }
Sets the Image of the embed .
23,631
public EmbedBuilder setAuthor ( String name , String url ) { return setAuthor ( name , url , null ) ; }
Sets the Author of the embed . The author appears in the top left of the embed and can have a small image beside it along with the author s name being made clickable by way of providing a url . This convenience method just sets the name and the url .
23,632
public EmbedBuilder setAuthor ( String name , String url , String iconUrl ) { if ( name == null ) { this . author = null ; } else { urlCheck ( url ) ; urlCheck ( iconUrl ) ; this . author = new MessageEmbed . AuthorInfo ( name , url , iconUrl , null ) ; } return this ; }
Sets the Author of the embed . The author appears in the top left of the embed and can have a small image beside it along with the author s name being made clickable by way of providing a url .
23,633
public EmbedBuilder setFooter ( String text , String iconUrl ) { if ( text == null ) { this . footer = null ; } else { Checks . check ( text . length ( ) <= MessageEmbed . TEXT_MAX_LENGTH , "Text cannot be longer than %d characters." , MessageEmbed . TEXT_MAX_LENGTH ) ; urlCheck ( iconUrl ) ; this . footer = new MessageEmbed . Footer ( text , iconUrl , null ) ; } return this ; }
Sets the Footer of the embed .
23,634
public EmbedBuilder addField ( String name , String value , boolean inline ) { if ( name == null && value == null ) return this ; this . fields . add ( new MessageEmbed . Field ( name , value , inline ) ) ; return this ; }
Adds a Field to the embed .
23,635
public WebhookMessageBuilder reset ( ) { content . setLength ( 0 ) ; embeds . clear ( ) ; resetFiles ( ) ; username = null ; avatarUrl = null ; isTTS = false ; return this ; }
Resets this builder to default settings .
23,636
public WebhookMessageBuilder append ( String content ) { Checks . notNull ( content , "Content" ) ; Checks . check ( this . content . length ( ) + content . length ( ) <= 2000 , "Content may not exceed 2000 characters!" ) ; this . content . append ( content ) ; return this ; }
Appends to the currently set content of the resulting message .
23,637
public AccountManager setName ( String name , String currentPassword ) { Checks . notBlank ( name , "Name" ) ; Checks . check ( name . length ( ) >= 2 && name . length ( ) <= 32 , "Name must be between 2-32 characters long" ) ; this . currentPassword = currentPassword ; this . name = name ; set |= NAME ; return this ; }
Sets the username for the currently logged in account
23,638
public AccountManager setAvatar ( Icon avatar , String currentPassword ) { this . currentPassword = currentPassword ; this . avatar = avatar ; set |= AVATAR ; return this ; }
Sets the avatar for the currently logged in account
23,639
public AccountManager setEmail ( String email , String currentPassword ) { Checks . notNull ( email , "email" ) ; this . currentPassword = currentPassword ; this . email = email ; set |= EMAIL ; return this ; }
Sets the email for the currently logged in client account .
23,640
@ SuppressWarnings ( "unchecked" ) public M swapPosition ( int swapPosition ) { Checks . notNegative ( swapPosition , "Provided swapPosition" ) ; Checks . check ( swapPosition < orderList . size ( ) , "Provided swapPosition is too big and is out of bounds. swapPosition: " + swapPosition ) ; T selectedItem = orderList . get ( selectedPosition ) ; T swapItem = orderList . get ( swapPosition ) ; orderList . set ( swapPosition , selectedItem ) ; orderList . set ( selectedPosition , swapItem ) ; return ( M ) this ; }
Swaps the currently selected entity with the entity located at the specified position . No other entities are affected by this operation .
23,641
@ SuppressWarnings ( "unchecked" ) public M swapPosition ( T swapEntity ) { Checks . notNull ( swapEntity , "Provided swapEntity" ) ; validateInput ( swapEntity ) ; return swapPosition ( orderList . indexOf ( swapEntity ) ) ; }
Swaps the currently selected entity with the specified entity . No other entities are affected by this operation .
23,642
public MessageBuilder replace ( String target , String replacement ) { int index = builder . indexOf ( target ) ; while ( index != - 1 ) { builder . replace ( index , index + target . length ( ) , replacement ) ; index = builder . indexOf ( target , index + replacement . length ( ) ) ; } return this ; }
Replaces each substring that matches the target string with the specified replacement string . The replacement proceeds from the beginning of the string to the end for example replacing aa with b in the message aaa will result in ba rather than ab .
23,643
public MessageBuilder replaceFirst ( String target , String replacement ) { int index = builder . indexOf ( target ) ; if ( index != - 1 ) { builder . replace ( index , index + target . length ( ) , replacement ) ; } return this ; }
Replaces the first substring that matches the target string with the specified replacement string .
23,644
public MessageBuilder replaceLast ( String target , String replacement ) { int index = builder . lastIndexOf ( target ) ; if ( index != - 1 ) { builder . replace ( index , index + target . length ( ) , replacement ) ; } return this ; }
Replaces the last substring that matches the target string with the specified replacement string .
23,645
public int indexOf ( CharSequence target , int fromIndex , int endIndex ) { if ( fromIndex < 0 ) throw new IndexOutOfBoundsException ( "index out of range: " + fromIndex ) ; if ( endIndex < 0 ) throw new IndexOutOfBoundsException ( "index out of range: " + endIndex ) ; if ( fromIndex > length ( ) ) throw new IndexOutOfBoundsException ( "fromIndex > length()" ) ; if ( fromIndex > endIndex ) throw new IndexOutOfBoundsException ( "fromIndex > endIndex" ) ; if ( endIndex >= builder . length ( ) ) { endIndex = builder . length ( ) - 1 ; } int targetCount = target . length ( ) ; if ( targetCount == 0 ) { return fromIndex ; } char strFirstChar = target . charAt ( 0 ) ; int max = endIndex + targetCount - 1 ; lastCharSearch : for ( int i = fromIndex ; i <= max ; i ++ ) { if ( builder . charAt ( i ) == strFirstChar ) { for ( int j = 1 ; j < targetCount ; j ++ ) { if ( builder . charAt ( i + j ) != target . charAt ( j ) ) { continue lastCharSearch ; } } return i ; } } return - 1 ; }
Returns the index within this string of the first occurrence of the specified substring between the specified indices .
23,646
public int lastIndexOf ( CharSequence target , int fromIndex , int endIndex ) { if ( fromIndex < 0 ) throw new IndexOutOfBoundsException ( "index out of range: " + fromIndex ) ; if ( endIndex < 0 ) throw new IndexOutOfBoundsException ( "index out of range: " + endIndex ) ; if ( fromIndex > length ( ) ) throw new IndexOutOfBoundsException ( "fromIndex > length()" ) ; if ( fromIndex > endIndex ) throw new IndexOutOfBoundsException ( "fromIndex > endIndex" ) ; if ( endIndex >= builder . length ( ) ) { endIndex = builder . length ( ) - 1 ; } int targetCount = target . length ( ) ; if ( targetCount == 0 ) { return endIndex ; } int rightIndex = endIndex - targetCount ; if ( fromIndex > rightIndex ) { fromIndex = rightIndex ; } int strLastIndex = targetCount - 1 ; char strLastChar = target . charAt ( strLastIndex ) ; int min = fromIndex + targetCount - 1 ; lastCharSearch : for ( int i = endIndex ; i >= min ; i -- ) { if ( builder . charAt ( i ) == strLastChar ) { for ( int j = strLastIndex - 1 , k = 1 ; j >= 0 ; j -- , k ++ ) { if ( builder . charAt ( i - k ) != target . charAt ( j ) ) { continue lastCharSearch ; } } return i - target . length ( ) + 1 ; } } return - 1 ; }
Returns the index within this string of the last occurrence of the specified substring between the specified indices .
23,647
public ChannelAction setName ( String name ) { Checks . notNull ( name , "Channel name" ) ; if ( name . length ( ) < 1 || name . length ( ) > 100 ) throw new IllegalArgumentException ( "Provided channel name must be 1 to 100 characters in length" ) ; this . name = name ; return this ; }
Sets the name for the new Channel
23,648
public ChannelAction setTopic ( String topic ) { if ( type != ChannelType . TEXT ) throw new UnsupportedOperationException ( "Can only set the topic for a TextChannel!" ) ; if ( topic != null && topic . length ( ) > 1024 ) throw new IllegalArgumentException ( "Channel Topic must not be greater than 1024 in length!" ) ; this . topic = topic ; return this ; }
Sets the topic for the new TextChannel
23,649
public ChannelAction setNSFW ( boolean nsfw ) { if ( type != ChannelType . TEXT ) throw new UnsupportedOperationException ( "Can only set nsfw for a TextChannel!" ) ; this . nsfw = nsfw ; return this ; }
Sets the NSFW flag for the new TextChannel
23,650
public ChannelAction setSlowmode ( int slowmode ) { Checks . check ( slowmode <= 120 && slowmode >= 0 , "Slowmode must be between 0 and 120 (seconds)!" ) ; this . slowmode = slowmode ; return this ; }
Sets the slowmode value which limits the amount of time that individual users must wait between sending messages in the new TextChannel . This is measured in seconds .
23,651
public ChannelAction setBitrate ( Integer bitrate ) { if ( type != ChannelType . VOICE ) throw new UnsupportedOperationException ( "Can only set the bitrate for a VoiceChannel!" ) ; if ( bitrate != null ) { int maxBitrate = guild . getFeatures ( ) . contains ( "VIP_REGIONS" ) ? 128000 : 96000 ; if ( bitrate < 8000 ) throw new IllegalArgumentException ( "Bitrate must be greater than 8000." ) ; else if ( bitrate > maxBitrate ) throw new IllegalArgumentException ( "Bitrate must be less than " + maxBitrate ) ; } this . bitrate = bitrate ; return this ; }
Sets the bitrate for the new VoiceChannel
23,652
public ChannelAction setUserlimit ( Integer userlimit ) { if ( type != ChannelType . VOICE ) throw new UnsupportedOperationException ( "Can only set the userlimit for a VoiceChannel!" ) ; if ( userlimit != null && ( userlimit < 0 || userlimit > 99 ) ) throw new IllegalArgumentException ( "Userlimit must be between 0-99!" ) ; this . userlimit = userlimit ; return this ; }
Sets the userlimit for the new VoiceChannel
23,653
private boolean send ( String request ) { needRateLimit = ! client . send ( request , false ) ; attemptedToSend = true ; return ! needRateLimit ; }
returns true if send was successful
23,654
public static byte [ ] readFully ( File file ) throws IOException { Checks . notNull ( file , "File" ) ; Checks . check ( file . exists ( ) , "Provided file does not exist!" ) ; try ( InputStream is = new FileInputStream ( file ) ) { long length = file . length ( ) ; if ( length > Integer . MAX_VALUE ) { throw new IOException ( "Cannot read the file into memory completely due to it being too large!" ) ; } byte [ ] bytes = new byte [ ( int ) length ] ; int offset = 0 ; int numRead = 0 ; while ( offset < bytes . length && ( numRead = is . read ( bytes , offset , bytes . length - offset ) ) >= 0 ) { offset += numRead ; } if ( offset < bytes . length ) { throw new IOException ( "Could not completely read file " + file . getName ( ) ) ; } is . close ( ) ; return bytes ; } }
Used as an alternate to Java s nio Files . readAllBytes .
23,655
public static String getPremadeWidgetHtml ( Guild guild , WidgetTheme theme , int width , int height ) { Checks . notNull ( guild , "Guild" ) ; return getPremadeWidgetHtml ( guild . getId ( ) , theme , width , height ) ; }
Gets the pre - made HTML Widget for the specified guild using the specified settings . The widget will only display correctly if the guild in question has the Widget enabled .
23,656
public static String getPremadeWidgetHtml ( String guildId , WidgetTheme theme , int width , int height ) { Checks . notNull ( guildId , "GuildId" ) ; Checks . notNull ( theme , "WidgetTheme" ) ; Checks . notNegative ( width , "Width" ) ; Checks . notNegative ( height , "Height" ) ; return String . format ( WIDGET_HTML , guildId , theme . name ( ) . toLowerCase ( ) , width , height ) ; }
Gets the pre - made HTML Widget for the specified guild using the specified settings . The widget will only display correctly if the guild in question has the Widget enabled . Additionally this method can be used independently of being on the guild in question .
23,657
public static void appendTo ( Formatter formatter , int width , int precision , boolean leftJustified , String out ) { try { Appendable appendable = formatter . out ( ) ; if ( precision > - 1 && out . length ( ) > precision ) { appendable . append ( Helpers . truncate ( out , precision ) ) ; return ; } if ( leftJustified ) appendable . append ( Helpers . rightPad ( out , width ) ) ; else appendable . append ( Helpers . leftPad ( out , width ) ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } }
Can be used to append a String to a formatter .
23,658
public RequestFuture < ? > send ( String content ) { Checks . notBlank ( content , "Content" ) ; Checks . check ( content . length ( ) <= 2000 , "Content may not exceed 2000 characters!" ) ; return execute ( newBody ( new JSONObject ( ) . put ( "content" , content ) . toString ( ) ) ) ; }
Sends the provided text message to this webhook .
23,659
public RoleAction setColor ( Color color ) { return this . setColor ( color != null ? color . getRGB ( ) : null ) ; }
Sets the color which the new role should be displayed with .
23,660
public static Game of ( GameType type , String name ) { return of ( type , name , null ) ; }
Creates a new Game instance with the specified name and url .
23,661
@ SuppressWarnings ( "unchecked" ) public M limit ( final int limit ) { Checks . check ( maxLimit == 0 || limit <= maxLimit , "Limit must not exceed %d!" , maxLimit ) ; Checks . check ( minLimit == 0 || limit >= minLimit , "Limit must be greater or equal to %d" , minLimit ) ; synchronized ( this . limit ) { this . limit . set ( limit ) ; } return ( M ) this ; }
Sets the limit that should be used in the next RestAction completion call .
23,662
private float processBubble ( BubbleValue bubbleValue , PointF point ) { final float rawX = computator . computeRawX ( bubbleValue . getX ( ) ) ; final float rawY = computator . computeRawY ( bubbleValue . getY ( ) ) ; float radius = ( float ) Math . sqrt ( Math . abs ( bubbleValue . getZ ( ) ) / Math . PI ) ; float rawRadius ; if ( isBubbleScaledByX ) { radius *= bubbleScaleX ; rawRadius = computator . computeRawDistanceX ( radius ) ; } else { radius *= bubbleScaleY ; rawRadius = computator . computeRawDistanceY ( radius ) ; } if ( rawRadius < minRawRadius + touchAdditional ) { rawRadius = minRawRadius + touchAdditional ; } bubbleCenter . set ( rawX , rawY ) ; if ( ValueShape . SQUARE . equals ( bubbleValue . getShape ( ) ) ) { bubbleRect . set ( rawX - rawRadius , rawY - rawRadius , rawX + rawRadius , rawY + rawRadius ) ; } return rawRadius ; }
Calculate bubble radius and center x and y coordinates . Center x and x will be stored in point parameter radius will be returned as float value .
23,663
public static float nextUpF ( float f ) { if ( Float . isNaN ( f ) || f == Float . POSITIVE_INFINITY ) { return f ; } else { f += 0.0f ; return Float . intBitsToFloat ( Float . floatToRawIntBits ( f ) + ( ( f >= 0.0f ) ? + 1 : - 1 ) ) ; } }
Returns next bigger float value considering precision of the argument .
23,664
public static float nextDownF ( float f ) { if ( Float . isNaN ( f ) || f == Float . NEGATIVE_INFINITY ) { return f ; } else { if ( f == 0.0f ) { return - Float . MIN_VALUE ; } else { return Float . intBitsToFloat ( Float . floatToRawIntBits ( f ) + ( ( f > 0.0f ) ? - 1 : + 1 ) ) ; } } }
Returns next smaller float value considering precision of the argument .
23,665
public static double nextUp ( double d ) { if ( Double . isNaN ( d ) || d == Double . POSITIVE_INFINITY ) { return d ; } else { d += 0.0 ; return Double . longBitsToDouble ( Double . doubleToRawLongBits ( d ) + ( ( d >= 0.0 ) ? + 1 : - 1 ) ) ; } }
Returns next bigger double value considering precision of the argument .
23,666
public static boolean almostEqual ( float a , float b , float absoluteDiff , float relativeDiff ) { float diff = Math . abs ( a - b ) ; if ( diff <= absoluteDiff ) { return true ; } a = Math . abs ( a ) ; b = Math . abs ( b ) ; float largest = ( a > b ) ? a : b ; if ( diff <= largest * relativeDiff ) { return true ; } return false ; }
Method checks if two float numbers are similar .
23,667
public static void computeAutoGeneratedAxisValues ( float start , float stop , int steps , AxisAutoValues outValues ) { double range = stop - start ; if ( steps == 0 || range <= 0 ) { outValues . values = new float [ ] { } ; outValues . valuesNumber = 0 ; return ; } double rawInterval = range / steps ; double interval = roundToOneSignificantFigure ( rawInterval ) ; double intervalMagnitude = Math . pow ( 10 , ( int ) Math . log10 ( interval ) ) ; int intervalSigDigit = ( int ) ( interval / intervalMagnitude ) ; if ( intervalSigDigit > 5 ) { interval = Math . floor ( 10 * intervalMagnitude ) ; } double first = Math . ceil ( start / interval ) * interval ; double last = nextUp ( Math . floor ( stop / interval ) * interval ) ; double intervalValue ; int valueIndex ; int valuesNum = 0 ; for ( intervalValue = first ; intervalValue <= last ; intervalValue += interval ) { ++ valuesNum ; } outValues . valuesNumber = valuesNum ; if ( outValues . values . length < valuesNum ) { outValues . values = new float [ valuesNum ] ; } for ( intervalValue = first , valueIndex = 0 ; valueIndex < valuesNum ; intervalValue += interval , ++ valueIndex ) { outValues . values [ valueIndex ] = ( float ) intervalValue ; } if ( interval < 1 ) { outValues . decimals = ( int ) Math . ceil ( - Math . log10 ( interval ) ) ; } else { outValues . decimals = 0 ; } }
Computes the set of axis labels to show given start and stop boundaries and an ideal number of stops between these boundaries .
23,668
public void setContentRect ( int width , int height , int paddingLeft , int paddingTop , int paddingRight , int paddingBottom ) { chartWidth = width ; chartHeight = height ; maxContentRect . set ( paddingLeft , paddingTop , width - paddingRight , height - paddingBottom ) ; contentRectMinusAxesMargins . set ( maxContentRect ) ; contentRectMinusAllMargins . set ( maxContentRect ) ; }
Calculates available width and height . Should be called when chart dimensions change . ContentRect is relative to chart view not the device s screen .
23,669
public void constrainViewport ( float left , float top , float right , float bottom ) { if ( right - left < minViewportWidth ) { right = left + minViewportWidth ; if ( left < maxViewport . left ) { left = maxViewport . left ; right = left + minViewportWidth ; } else if ( right > maxViewport . right ) { right = maxViewport . right ; left = right - minViewportWidth ; } } if ( top - bottom < minViewportHeight ) { bottom = top - minViewportHeight ; if ( top > maxViewport . top ) { top = maxViewport . top ; bottom = top - minViewportHeight ; } else if ( bottom < maxViewport . bottom ) { bottom = maxViewport . bottom ; top = bottom + minViewportHeight ; } } currentViewport . left = Math . max ( maxViewport . left , left ) ; currentViewport . top = Math . min ( maxViewport . top , top ) ; currentViewport . right = Math . min ( maxViewport . right , right ) ; currentViewport . bottom = Math . max ( maxViewport . bottom , bottom ) ; viewportChangeListener . onViewportChanged ( currentViewport ) ; }
Checks if new viewport doesn t exceed max available viewport .
23,670
public float computeRawX ( float valueX ) { final float pixelOffset = ( valueX - currentViewport . left ) * ( contentRectMinusAllMargins . width ( ) / currentViewport . width ( ) ) ; return contentRectMinusAllMargins . left + pixelOffset ; }
Translates chart value into raw pixel value . Returned value is absolute pixel X coordinate . If this method return 0 that means left most pixel of the screen .
23,671
public float computeRawY ( float valueY ) { final float pixelOffset = ( valueY - currentViewport . bottom ) * ( contentRectMinusAllMargins . height ( ) / currentViewport . height ( ) ) ; return contentRectMinusAllMargins . bottom - pixelOffset ; }
Translates chart value into raw pixel value . Returned value is absolute pixel Y coordinate . If this method return 0 that means top most pixel of the screen .
23,672
public boolean isWithinContentRect ( float x , float y , float precision ) { if ( x >= contentRectMinusAllMargins . left - precision && x <= contentRectMinusAllMargins . right + precision ) { if ( y <= contentRectMinusAllMargins . bottom + precision && y >= contentRectMinusAllMargins . top - precision ) { return true ; } } return false ; }
Check if given coordinates lies inside contentRectMinusAllMargins .
23,673
public void setCurrentViewport ( Viewport viewport ) { constrainViewport ( viewport . left , viewport . top , viewport . right , viewport . bottom ) ; }
Set current viewport to the same values as viewport passed in parameter . This method use deep copy so parameter can be safely modified later . Current viewport must be equal or smaller than maximum viewport .
23,674
public void setCurrentViewport ( float left , float top , float right , float bottom ) { constrainViewport ( left , top , right , bottom ) ; }
Set new values for curent viewport that will change what part of chart is visible . Current viewport must be equal or smaller than maximum viewport .
23,675
public void setMaxViewport ( Viewport maxViewport ) { setMaxViewport ( maxViewport . left , maxViewport . top , maxViewport . right , maxViewport . bottom ) ; }
Set maximum viewport to the same values as viewport passed in parameter . This method use deep copy so parameter can be safely modified later .
23,676
public void setMaxViewport ( float left , float top , float right , float bottom ) { this . maxViewport . set ( left , top , right , bottom ) ; computeMinimumWidthAndHeight ( ) ; }
Set new values for maximum viewport that will change what part of chart is visible .
23,677
public boolean computeZoom ( ) { if ( mFinished ) { return false ; } long tRTC = SystemClock . elapsedRealtime ( ) - mStartRTC ; if ( tRTC >= mAnimationDurationMillis ) { mFinished = true ; mCurrentZoom = mEndZoom ; return false ; } float t = tRTC * 1f / mAnimationDurationMillis ; mCurrentZoom = mEndZoom * mInterpolator . getInterpolation ( t ) ; return true ; }
Computes the current zoom level returning true if the zoom is still active and false if the zoom has finished .
23,678
public static Axis generateAxisFromRange ( float start , float stop , float step ) { List < AxisValue > values = new ArrayList < AxisValue > ( ) ; for ( float value = start ; value <= stop ; value += step ) { AxisValue axisValue = new AxisValue ( value ) ; values . add ( axisValue ) ; } Axis axis = new Axis ( values ) ; return axis ; }
Generates Axis with values from start to stop inclusive .
23,679
public static Axis generateAxisFromCollection ( List < Float > axisValues ) { List < AxisValue > values = new ArrayList < AxisValue > ( ) ; int index = 0 ; for ( float value : axisValues ) { AxisValue axisValue = new AxisValue ( value ) ; values . add ( axisValue ) ; ++ index ; } Axis axis = new Axis ( values ) ; return axis ; }
Generates Axis with values from given list .
23,680
public static Axis generateAxisFromCollection ( List < Float > axisValues , List < String > axisValuesLabels ) { if ( axisValues . size ( ) != axisValuesLabels . size ( ) ) { throw new IllegalArgumentException ( "Values and labels lists must have the same size!" ) ; } List < AxisValue > values = new ArrayList < AxisValue > ( ) ; int index = 0 ; for ( float value : axisValues ) { AxisValue axisValue = new AxisValue ( value ) . setLabel ( axisValuesLabels . get ( index ) ) ; values . add ( axisValue ) ; ++ index ; } Axis axis = new Axis ( values ) ; return axis ; }
Generates Axis with values and labels from given lists both lists must have the same size .
23,681
protected void drawLabelTextAndBackground ( Canvas canvas , char [ ] labelBuffer , int startIndex , int numChars , int autoBackgroundColor ) { final float textX ; final float textY ; if ( isValueLabelBackgroundEnabled ) { if ( isValueLabelBackgroundAuto ) { labelBackgroundPaint . setColor ( autoBackgroundColor ) ; } canvas . drawRect ( labelBackgroundRect , labelBackgroundPaint ) ; textX = labelBackgroundRect . left + labelMargin ; textY = labelBackgroundRect . bottom - labelMargin ; } else { textX = labelBackgroundRect . left ; textY = labelBackgroundRect . bottom ; } canvas . drawText ( labelBuffer , startIndex , numChars , textX , textY , labelPaint ) ; }
Draws label text and label background if isValueLabelBackgroundEnabled is true .
23,682
public void set ( Viewport src ) { this . left = src . left ; this . top = src . top ; this . right = src . right ; this . bottom = src . bottom ; }
Copy the coordinates from src into this viewport .
23,683
public boolean contains ( Viewport v ) { return this . left < this . right && this . bottom < this . top && left <= v . left && top >= v . top && right >= v . right && bottom <= v . bottom ; }
Returns true iff the specified viewport r is inside or equal to this viewport . An empty viewport never contains another viewport .
23,684
public void drawInForeground ( Canvas canvas ) { Axis axis = chart . getChartData ( ) . getAxisYLeft ( ) ; if ( null != axis ) { drawAxisLabelsAndName ( canvas , axis , LEFT ) ; } axis = chart . getChartData ( ) . getAxisYRight ( ) ; if ( null != axis ) { drawAxisLabelsAndName ( canvas , axis , RIGHT ) ; } axis = chart . getChartData ( ) . getAxisXBottom ( ) ; if ( null != axis ) { drawAxisLabelsAndName ( canvas , axis , BOTTOM ) ; } axis = chart . getChartData ( ) . getAxisXTop ( ) ; if ( null != axis ) { drawAxisLabelsAndName ( canvas , axis , TOP ) ; } }
Draw axes labels and names in the foreground .
23,685
private void drawPoints ( Canvas canvas , Line line , int lineIndex , int mode ) { pointPaint . setColor ( line . getPointColor ( ) ) ; int valueIndex = 0 ; for ( PointValue pointValue : line . getValues ( ) ) { int pointRadius = ChartUtils . dp2px ( density , line . getPointRadius ( ) ) ; final float rawX = computator . computeRawX ( pointValue . getX ( ) ) ; final float rawY = computator . computeRawY ( pointValue . getY ( ) ) ; if ( computator . isWithinContentRect ( rawX , rawY , checkPrecision ) ) { if ( MODE_DRAW == mode ) { drawPoint ( canvas , line , pointValue , rawX , rawY , pointRadius ) ; if ( line . hasLabels ( ) ) { drawLabel ( canvas , line , pointValue , rawX , rawY , pointRadius + labelOffset ) ; } } else if ( MODE_HIGHLIGHT == mode ) { highlightPoint ( canvas , line , pointValue , rawX , rawY , lineIndex , valueIndex ) ; } else { throw new IllegalStateException ( "Cannot process points in mode: " + mode ) ; } } ++ valueIndex ; } }
implementing point styles .
23,686
public boolean canScrollHorizontally ( int direction ) { if ( getZoomLevel ( ) <= 1.0 ) { return false ; } final Viewport currentViewport = getCurrentViewport ( ) ; final Viewport maximumViewport = getMaximumViewport ( ) ; if ( direction < 0 ) { return currentViewport . left > maximumViewport . left ; } else { return currentViewport . right < maximumViewport . right ; } }
When embedded in a ViewPager this will be called in order to know if we can scroll . If this returns true the ViewPager will ignore the drag so that we can scroll our content . If this return false the ViewPager will assume we won t be able to scroll and will consume the drag
23,687
private float pointToAngle ( float x , float y , float centerX , float centerY ) { double diffX = x - centerX ; double diffY = y - centerY ; double radian = Math . atan2 ( - diffX , diffY ) ; float angle = ( ( float ) Math . toDegrees ( radian ) + 360 ) % 360 ; angle += 90f ; return angle ; }
Calculates angle of touched point .
23,688
private void calculateMaxViewport ( ) { tempMaximumViewport . set ( 0 , MAX_WIDTH_HEIGHT , MAX_WIDTH_HEIGHT , 0 ) ; maxSum = 0.0f ; for ( SliceValue sliceValue : dataProvider . getPieChartData ( ) . getValues ( ) ) { maxSum += Math . abs ( sliceValue . getValue ( ) ) ; } }
Viewport is not really important for PieChart this kind of chart doesn t relay on viewport but uses pixels coordinates instead . This method also calculates sum of all SliceValues .
23,689
protected String translate ( String key , Object ... objects ) { return messageSource . getMessage ( key , objects , null ) ; }
Get the messageSource .
23,690
protected < T extends AbstractBase > ResponseEntity < Response < T > > buildOKResponse ( T ... params ) { return buildResponse ( HttpStatus . OK , "" , "" , params ) ; }
Build an response object that signals a success response to the caller .
23,691
protected String getLocationForCreatedResource ( HttpServletRequest req , String objId ) { StringBuffer url = req . getRequestURL ( ) ; UriTemplate template = new UriTemplate ( url . append ( "/{objId}/" ) . toString ( ) ) ; return template . expand ( objId ) . toASCIIString ( ) ; }
Append the ID of the object that was created to the original request URL and return it .
23,692
private static Properties overrideDockerPropertiesWithSystemProperties ( Properties p , Properties systemProperties ) { Properties overriddenProperties = new Properties ( ) ; overriddenProperties . putAll ( p ) ; for ( String key : CONFIG_KEYS ) { if ( systemProperties . containsKey ( key ) ) { overriddenProperties . setProperty ( key , systemProperties . getProperty ( key ) ) ; } } return overriddenProperties ; }
Creates a new Properties object containing values overridden from the System properties
23,693
static Builder createDefaultConfigBuilder ( Map < String , String > env , Properties systemProperties ) { Properties properties = loadIncludedDockerProperties ( systemProperties ) ; properties = overrideDockerPropertiesWithSettingsFromUserHome ( properties , systemProperties ) ; properties = overrideDockerPropertiesWithEnv ( properties , env ) ; properties = overrideDockerPropertiesWithSystemProperties ( properties , systemProperties ) ; return new Builder ( ) . withProperties ( properties ) ; }
Allows you to build the config without system environment interfering for more robust testing
23,694
public SSLContext getSSLContext ( ) throws KeyManagementException , UnrecoverableKeyException , NoSuchAlgorithmException , KeyStoreException { final SSLContext context = SSLContext . getInstance ( "TLS" ) ; String httpProtocols = System . getProperty ( "https.protocols" ) ; System . setProperty ( "https.protocols" , "TLSv1" ) ; if ( httpProtocols != null ) { System . setProperty ( "https.protocols" , httpProtocols ) ; } final KeyManagerFactory keyManagerFactory = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; keyManagerFactory . init ( keystore , keystorePassword . toCharArray ( ) ) ; context . init ( keyManagerFactory . getKeyManagers ( ) , new TrustManager [ ] { new X509TrustManager ( ) { public X509Certificate [ ] getAcceptedIssuers ( ) { return new X509Certificate [ ] { } ; } public void checkClientTrusted ( final X509Certificate [ ] arg0 , final String arg1 ) { } public void checkServerTrusted ( final X509Certificate [ ] arg0 , final String arg1 ) { } } } , new SecureRandom ( ) ) ; return context ; }
Get the SSL Context out of the keystore .
23,695
public Integer awaitStatusCode ( long timeout , TimeUnit timeUnit ) { try { if ( ! awaitCompletion ( timeout , timeUnit ) ) { throw new DockerClientException ( "Awaiting status code timeout." ) ; } } catch ( InterruptedException e ) { throw new DockerClientException ( "Awaiting status code interrupted: " , e ) ; } return getStatusCode ( ) ; }
Awaits the status code from the container .
23,696
public static List < Certificate > loadCertificates ( final String certpem ) throws IOException , CertificateException { final StringReader certReader = new StringReader ( certpem ) ; try ( BufferedReader reader = new BufferedReader ( certReader ) ) { return loadCertificates ( reader ) ; } }
from cert . pem String
23,697
public static List < Certificate > loadCertificates ( final Reader reader ) throws IOException , CertificateException { try ( PEMParser pemParser = new PEMParser ( reader ) ) { List < Certificate > certificates = new ArrayList < > ( ) ; JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter ( ) . setProvider ( BouncyCastleProvider . PROVIDER_NAME ) ; Object certObj = pemParser . readObject ( ) ; if ( certObj instanceof X509CertificateHolder ) { X509CertificateHolder certificateHolder = ( X509CertificateHolder ) certObj ; certificates . add ( certificateConverter . getCertificate ( certificateHolder ) ) ; } return certificates ; } }
cert . pem from reader
23,698
private static PrivateKeyInfo getPrivateKeyInfoOrNull ( Object pemObject ) throws NoSuchAlgorithmException { PrivateKeyInfo privateKeyInfo = null ; if ( pemObject instanceof PEMKeyPair ) { PEMKeyPair pemKeyPair = ( PEMKeyPair ) pemObject ; privateKeyInfo = pemKeyPair . getPrivateKeyInfo ( ) ; } else if ( pemObject instanceof PrivateKeyInfo ) { privateKeyInfo = ( PrivateKeyInfo ) pemObject ; } else if ( pemObject instanceof ASN1ObjectIdentifier ) { final ASN1ObjectIdentifier asn1ObjectIdentifier = ( ASN1ObjectIdentifier ) pemObject ; LOG . trace ( "Ignoring asn1ObjectIdentifier {}" , asn1ObjectIdentifier ) ; } else { LOG . warn ( "Unknown object '{}' from PEMParser" , pemObject ) ; } return privateKeyInfo ; }
Find a PrivateKeyInfo in the PEM object details . Returns null if the PEM object type is unknown .
23,699
public static PrivateKey loadPrivateKey ( final String keypem ) throws IOException , NoSuchAlgorithmException , InvalidKeySpecException { try ( StringReader certReader = new StringReader ( keypem ) ; BufferedReader reader = new BufferedReader ( certReader ) ) { return loadPrivateKey ( reader ) ; } }
Return KeyPair from key . pem