idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
9,400
public TheRockWithdrawalResponse withdrawRipple ( Currency currency , BigDecimal amount , String destinationAddress , Long destinationTag ) throws TheRockException , IOException { final TheRockWithdrawal withdrawal = TheRockWithdrawal . createRippleWithdrawal ( currency . getCurrencyCode ( ) , amount , destinationAddress , destinationTag ) ; return theRockAuthenticated . withdraw ( apiKey , signatureCreator , exchange . getNonceFactory ( ) , withdrawal ) ; }
Withdraw to Ripple
9,401
public List < CoinbaseAccount > getCoinbaseAccounts ( ) throws IOException { String apiKey = exchange . getExchangeSpecification ( ) . getApiKey ( ) ; BigDecimal timestamp = coinbase . getTime ( Coinbase . CB_VERSION_VALUE ) . getData ( ) . getEpoch ( ) ; return coinbase . getAccounts ( Coinbase . CB_VERSION_VALUE , apiKey , signatureCreator2 , timestamp ) . getData ( ) ; }
Authenticated resource that shows the current user accounts .
9,402
public CoinbaseAccount getCoinbaseAccount ( Currency currency ) throws IOException { String apiKey = exchange . getExchangeSpecification ( ) . getApiKey ( ) ; BigDecimal timestamp = coinbase . getTime ( Coinbase . CB_VERSION_VALUE ) . getData ( ) . getEpoch ( ) ; return coinbase . getAccount ( Coinbase . CB_VERSION_VALUE , apiKey , signatureCreator2 , timestamp , currency . getCurrencyCode ( ) ) . getData ( ) ; }
Authenticated resource that shows the current user account for the give currency .
9,403
public CoinbaseAccount createCoinbaseAccount ( String name ) throws IOException { CreateCoinbaseAccountPayload payload = new CreateCoinbaseAccountPayload ( name ) ; String path = "/v2/accounts" ; String apiKey = exchange . getExchangeSpecification ( ) . getApiKey ( ) ; BigDecimal timestamp = coinbase . getTime ( Coinbase . CB_VERSION_VALUE ) . getData ( ) . getEpoch ( ) ; String body = new ObjectMapper ( ) . writeValueAsString ( payload ) ; String signature = getSignature ( timestamp , HttpMethod . POST , path , body ) ; showCurl ( HttpMethod . POST , apiKey , timestamp , signature , path , body ) ; return coinbase . createAccount ( MediaType . APPLICATION_JSON , Coinbase . CB_VERSION_VALUE , apiKey , signature , timestamp , payload ) . getData ( ) ; }
Authenticated resource that creates a new BTC account for the current user .
9,404
public List < CoinbasePaymentMethod > getCoinbasePaymentMethods ( ) throws IOException { String apiKey = exchange . getExchangeSpecification ( ) . getApiKey ( ) ; BigDecimal timestamp = coinbase . getTime ( Coinbase . CB_VERSION_VALUE ) . getData ( ) . getEpoch ( ) ; return coinbase . getPaymentMethods ( Coinbase . CB_VERSION_VALUE , apiKey , signatureCreator2 , timestamp ) . getData ( ) ; }
Authenticated resource that shows the current user payment methods .
9,405
public static Ticker adaptTicker ( BitbayTicker bitbayTicker , CurrencyPair currencyPair ) { BigDecimal ask = bitbayTicker . getAsk ( ) ; BigDecimal bid = bitbayTicker . getBid ( ) ; BigDecimal high = bitbayTicker . getMax ( ) ; BigDecimal low = bitbayTicker . getMin ( ) ; BigDecimal volume = bitbayTicker . getVolume ( ) ; BigDecimal last = bitbayTicker . getLast ( ) ; return new Ticker . Builder ( ) . currencyPair ( currencyPair ) . last ( last ) . bid ( bid ) . ask ( ask ) . high ( high ) . low ( low ) . volume ( volume ) . build ( ) ; }
Adapts a BitbayTicker to a Ticker Object
9,406
public synchronized String getSignature ( long nonce ) { return HexEncoder . encode ( sha256HMAC . doFinal ( buildSignatureData ( nonce ) ) ) . toLowerCase ( Locale . ROOT ) ; }
Returns a valid signature for the given nonce .
9,407
public CoinbaseUsers getCoinbaseUsers ( ) throws IOException { final CoinbaseUsers users = coinbase . getUsers ( exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return users ; }
Authenticated resource that shows the current user and their settings .
9,408
public boolean redeemCoinbaseToken ( String tokenId ) throws IOException { final CoinbaseBaseResponse response = coinbase . redeemToken ( tokenId , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return handleResponse ( response ) . isSuccess ( ) ; }
Authenticated resource which claims a redeemable token for its address and Bitcoin .
9,409
public CoinbaseAddresses getCoinbaseAddresses ( Integer page , final Integer limit , final String filter ) throws IOException { final CoinbaseAddresses receiveResult = coinbase . getAddresses ( page , limit , filter , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return receiveResult ; }
Authenticated resource that returns Bitcoin addresses a user has associated with their account .
9,410
public CoinbaseAddress generateCoinbaseReceiveAddress ( String callbackUrl , final String label ) throws IOException { final CoinbaseAddressCallback callbackUrlParam = new CoinbaseAddressCallback ( callbackUrl , label ) ; final CoinbaseAddress generateReceiveAddress = coinbase . generateReceiveAddress ( callbackUrlParam , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return handleResponse ( generateReceiveAddress ) ; }
Authenticated resource that generates a new Bitcoin receive address for the user .
9,411
public CoinbaseContacts getCoinbaseContacts ( Integer page , final Integer limit , final String filter ) throws IOException { final CoinbaseContacts contacts = coinbase . getContacts ( page , limit , filter , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return contacts ; }
Authenticated resource that returns contacts the user has previously sent to or received from .
9,412
public CoinbaseTransaction getCoinbaseTransaction ( String transactionIdOrIdemField ) throws IOException { final CoinbaseTransaction transaction = coinbase . getTransactionDetails ( transactionIdOrIdemField , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return handleResponse ( transaction ) ; }
Authenticated resource which returns the details of an individual transaction .
9,413
public CoinbaseTransaction requestMoneyCoinbaseRequest ( CoinbaseRequestMoneyRequest transactionRequest ) throws IOException { final CoinbaseTransaction pendingTransaction = coinbase . requestMoney ( new CoinbaseTransaction ( transactionRequest ) , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return handleResponse ( pendingTransaction ) ; }
Authenticated resource which lets the user request money from a Bitcoin address .
9,414
public CoinbaseTransaction sendMoneyCoinbaseRequest ( CoinbaseSendMoneyRequest transactionRequest ) throws IOException { final CoinbaseTransaction pendingTransaction = coinbase . sendMoney ( new CoinbaseTransaction ( transactionRequest ) , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return handleResponse ( pendingTransaction ) ; }
Authenticated resource which lets you send money to an email or Bitcoin address .
9,415
public CoinbaseBaseResponse resendCoinbaseRequest ( String transactionId ) throws IOException { final CoinbaseBaseResponse response = coinbase . resendRequest ( transactionId , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return handleResponse ( response ) ; }
Authenticated resource which lets the user resend a money request .
9,416
public CoinbaseBaseResponse cancelCoinbaseRequest ( String transactionId ) throws IOException { final CoinbaseBaseResponse response = coinbase . cancelRequest ( transactionId , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return handleResponse ( response ) ; }
Authenticated resource which lets a user cancel a money request . Money requests can be canceled by the sender or the recipient .
9,417
public CoinbaseButton createCoinbaseButton ( CoinbaseButton button ) throws IOException { final CoinbaseButton createdButton = coinbase . createButton ( button , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return handleResponse ( createdButton ) ; }
Authenticated resource that creates a payment button page or iFrame to accept Bitcoin on your website . This can be used to accept Bitcoin for an individual item or to integrate with your existing shopping cart solution . For example you could create a new payment button for each shopping cart on your website setting the total and order number in the button at checkout .
9,418
public CoinbaseOrder getCoinbaseOrder ( String orderIdOrCustom ) throws IOException { final CoinbaseOrder order = coinbase . getOrder ( orderIdOrCustom , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return handleResponse ( order ) ; }
Authenticated resource which returns order details for a specific order id or merchant custom .
9,419
public CoinbaseOrder createCoinbaseOrder ( CoinbaseButton button ) throws IOException { final CoinbaseOrder createdOrder = coinbase . createOrder ( button , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return handleResponse ( createdOrder ) ; }
Authenticated resource which returns an order for a new button .
9,420
public CoinbaseRecurringPayment getCoinbaseRecurringPayment ( String recurringPaymentId ) throws IOException { final CoinbaseRecurringPayment recurringPayment = coinbase . getRecurringPayment ( recurringPaymentId , exchange . getExchangeSpecification ( ) . getApiKey ( ) , signatureCreator , exchange . getNonceFactory ( ) ) ; return recurringPayment ; }
Authenticated resource that lets you show an individual recurring payment .
9,421
public Map < Long , DSXTradeHistoryResult > getDSXTradeHistory ( Integer count , Long fromId , Long endId , DSXAuthenticatedV2 . SortOrder order , Long since , Long end , String pair ) throws IOException { DSXTradeHistoryReturn dsxTradeHistory = dsx . tradeHistory ( apiKey , signatureCreator , exchange . getNonceFactory ( ) , count , fromId , endId , order , since , end , pair ) ; String error = dsxTradeHistory . getError ( ) ; if ( MSG_NO_TRADES . equals ( error ) ) { return Collections . emptyMap ( ) ; } checkResult ( dsxTradeHistory ) ; return dsxTradeHistory . getReturnValue ( ) ; }
Get Map of trade history from DSX exchange . All parameters are nullable
9,422
public Map < Long , DSXTransHistoryResult > getDSXTransHistory ( Integer count , Long fromId , Long endId , DSXAuthenticatedV2 . SortOrder order , Long since , Long end , DSXTransHistoryResult . Type type , DSXTransHistoryResult . Status status , String currency ) throws IOException { DSXTransHistoryReturn dsxTransHistory = dsx . transHistory ( apiKey , signatureCreator , exchange . getNonceFactory ( ) , count , fromId , endId , order , since , end , type , status , currency ) ; String error = dsxTransHistory . getError ( ) ; if ( MSG_NO_TRADES . equals ( error ) ) { return Collections . emptyMap ( ) ; } checkResult ( dsxTransHistory ) ; return dsxTransHistory . getReturnValue ( ) ; }
Get Map of transaction history from DSX exchange . All parameters are nullable
9,423
public Map < Long , DSXOrderHistoryResult > getDSXOrderHistory ( Long count , Long fromId , Long endId , DSXAuthenticatedV2 . SortOrder order , Long since , Long end , String pair ) throws IOException { DSXOrderHistoryReturn dsxOrderHistory = dsx . orderHistory ( apiKey , signatureCreator , exchange . getNonceFactory ( ) , count , fromId , endId , order , since , end , pair ) ; String error = dsxOrderHistory . getError ( ) ; if ( MSG_NO_TRADES . equals ( error ) ) { return Collections . emptyMap ( ) ; } checkResult ( dsxOrderHistory ) ; return dsxOrderHistory . getReturnValue ( ) ; }
Get Map of order history from DSX exchange . All parameters are nullable
9,424
public static Map < CurrencyPair , Fee > adaptDynamicTradingFees ( BitfinexTradingFeeResponse [ ] responses , List < CurrencyPair > currencyPairs ) { Map < CurrencyPair , Fee > result = new HashMap < > ( ) ; for ( BitfinexTradingFeeResponse response : responses ) { BitfinexTradingFeeResponse . BitfinexTradingFeeResponseRow [ ] responseRows = response . getTradingFees ( ) ; for ( BitfinexTradingFeeResponse . BitfinexTradingFeeResponseRow responseRow : responseRows ) { Currency currency = Currency . getInstance ( responseRow . getCurrency ( ) ) ; BigDecimal percentToFraction = BigDecimal . ONE . divide ( BigDecimal . ONE . scaleByPowerOfTen ( 2 ) ) ; Fee fee = new Fee ( responseRow . getMakerFee ( ) . multiply ( percentToFraction ) , responseRow . getTakerFee ( ) . multiply ( percentToFraction ) ) ; for ( CurrencyPair pair : currencyPairs ) { if ( pair . base . equals ( currency ) ) { if ( result . put ( pair , fee ) != null ) { throw new IllegalStateException ( "Fee for currency pair " + pair + " is overspecified" ) ; } } } } } return result ; }
Each element in the response array contains a set of currencies that are at a given fee tier . The API returns the fee per currency in each tier and does not make any promises that they are all the same so this adapter will use the fee per currency instead of the fee per tier .
9,425
public IRippleTradeTransaction getTrade ( final String account , final RippleNotification notification ) throws RippleException , IOException { final RippleExchange ripple = ( RippleExchange ) exchange ; if ( ripple . isStoreTradeTransactionDetails ( ) ) { Map < String , IRippleTradeTransaction > cache = rawTradeStore . get ( account ) ; if ( cache == null ) { cache = new ConcurrentHashMap < > ( ) ; rawTradeStore . put ( account , cache ) ; } if ( cache . containsKey ( notification . getHash ( ) ) ) { return cache . get ( notification . getHash ( ) ) ; } } final IRippleTradeTransaction trade ; try { if ( notification . getType ( ) . equals ( "order" ) ) { trade = ripplePublic . orderTransaction ( account , notification . getHash ( ) ) ; } else if ( notification . getType ( ) . equals ( "payment" ) ) { trade = ripplePublic . paymentTransaction ( account , notification . getHash ( ) ) ; } else { throw new IllegalArgumentException ( String . format ( "unexpected notification %s type for transaction[%s] and account[%s]" , notification . getType ( ) , notification . getHash ( ) , notification . getAccount ( ) ) ) ; } } catch ( final RippleException e ) { if ( e . getHttpStatusCode ( ) == 500 && e . getErrorType ( ) . equals ( "transaction" ) ) { logger . error ( "exception reading {} transaction[{}] for account[{}]" , notification . getType ( ) , notification . getHash ( ) , account , e ) ; return null ; } else { throw e ; } } if ( ripple . isStoreTradeTransactionDetails ( ) ) { rawTradeStore . get ( account ) . put ( notification . getHash ( ) , trade ) ; } return trade ; }
Retrieve order details from local store if they have been previously stored otherwise query external server .
9,426
public void clearOrderDetailsStore ( ) { for ( final Map < String , IRippleTradeTransaction > cache : rawTradeStore . values ( ) ) { cache . clear ( ) ; } rawTradeStore . clear ( ) ; }
Clear any stored order details to allow memory to be released .
9,427
public static < V > V callWithRetries ( int nAttempts , int initialRetrySec , Callable < V > action , IPredicate < Exception > retryableException ) throws Exception { int retryDelaySec = initialRetrySec ; for ( int attemptsLeftAfterThis = nAttempts - 1 ; attemptsLeftAfterThis >= 0 ; attemptsLeftAfterThis -- ) { try { return action . call ( ) ; } catch ( Exception e ) { if ( ! retryableException . test ( e ) ) { throw e ; } if ( attemptsLeftAfterThis <= 0 ) { throw new RuntimeException ( "Ultimately failed after " + nAttempts + " attempts." , e ) ; } log . warn ( "Failed; {} attempts left: {}" , e . toString ( ) , attemptsLeftAfterThis ) ; } retryDelaySec = pauseAndIncrease ( retryDelaySec ) ; } throw new RuntimeException ( "Failed; total attempts allowed: " + nAttempts ) ; }
Allows a client to attempt a call and retry a finite amount of times if the exception thrown is the right kind . The retries back off exponentially .
9,428
private static String join ( String sep , Collection < String > collection ) { StringBuilder builder = new StringBuilder ( ) ; boolean first = true ; for ( String element : collection ) { if ( first ) { first = false ; } else { builder . append ( sep ) ; } builder . append ( element ) ; } return builder . toString ( ) ; }
This is a reimplementation of Java 8 s String . join .
9,429
public static < T > String apiVersion ( T item , String apiVersion ) { if ( item instanceof HasMetadata && Utils . isNotNullOrEmpty ( ( ( HasMetadata ) item ) . getApiVersion ( ) ) ) { return trimVersion ( ( ( HasMetadata ) item ) . getApiVersion ( ) ) ; } else if ( apiVersion != null && ! apiVersion . isEmpty ( ) ) { return trimVersion ( apiVersion ) ; } return null ; }
Returns the api version falling back to the items apiGroupVersion if not null .
9,430
static boolean isOpenShift ( Client client ) { URL masterUrl = client . getMasterUrl ( ) ; if ( IS_OPENSHIFT . containsKey ( masterUrl ) ) { return IS_OPENSHIFT . get ( masterUrl ) ; } else { RootPaths rootPaths = client . rootPaths ( ) ; if ( rootPaths != null ) { List < String > paths = rootPaths . getPaths ( ) ; if ( paths != null ) { for ( String path : paths ) { if ( path . endsWith ( ".openshift.io" ) || path . contains ( ".openshift.io/" ) ) { USES_OPENSHIFT_APIGROUPS . putIfAbsent ( masterUrl , true ) ; IS_OPENSHIFT . putIfAbsent ( masterUrl , true ) ; return true ; } } for ( String path : paths ) { if ( java . util . Objects . equals ( "/oapi" , path ) || java . util . Objects . equals ( "oapi" , path ) ) { IS_OPENSHIFT . putIfAbsent ( masterUrl , true ) ; return true ; } } } } } IS_OPENSHIFT . putIfAbsent ( masterUrl , false ) ; return false ; }
Check if OpenShift is available .
9,431
static boolean isOpenShiftAPIGroups ( Client client ) { Config configuration = client . getConfiguration ( ) ; if ( configuration instanceof OpenShiftConfig ) { OpenShiftConfig openShiftConfig = ( OpenShiftConfig ) configuration ; if ( openShiftConfig . isDisableApiGroupCheck ( ) ) { return false ; } } URL masterUrl = client . getMasterUrl ( ) ; if ( isOpenShift ( client ) && USES_OPENSHIFT_APIGROUPS . containsKey ( masterUrl ) ) { return USES_OPENSHIFT_APIGROUPS . get ( masterUrl ) ; } return false ; }
Check if OpenShift API Groups are available
9,432
static boolean hasCustomOpenShiftUrl ( OpenShiftConfig config ) { try { URI masterUri = new URI ( config . getMasterUrl ( ) ) . resolve ( "/" ) ; URI openshfitUri = new URI ( config . getOpenShiftUrl ( ) ) . resolve ( "/" ) ; return ! masterUri . equals ( openshfitUri ) ; } catch ( Exception e ) { throw KubernetesClientException . launderThrowable ( e ) ; } }
Checks if a custom URL for OpenShift has been used .
9,433
private static String notReadyToString ( Iterable < HasMetadata > resources ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Resources that are not ready: " ) ; boolean first = true ; for ( HasMetadata r : resources ) { if ( first ) { first = false ; } else { sb . append ( ", " ) ; } sb . append ( "[Kind:" ) . append ( r . getKind ( ) ) . append ( " Name:" ) . append ( r . getMetadata ( ) . getName ( ) ) . append ( " Namespace:" ) . append ( r . getMetadata ( ) . getNamespace ( ) ) . append ( "]" ) ; } return sb . toString ( ) ; }
Creates a string listing all the resources that are not ready .
9,434
public static < T > T unmarshal ( InputStream is , ObjectMapper mapper ) { return unmarshal ( is , mapper , Collections . < String , String > emptyMap ( ) ) ; }
Unmarshals a stream .
9,435
private void waitUntilScaled ( final int count ) { final ArrayBlockingQueue < Object > queue = new ArrayBlockingQueue < > ( 1 ) ; final AtomicReference < Integer > replicasRef = new AtomicReference < > ( 0 ) ; final String name = checkName ( getItem ( ) ) ; final String namespace = checkNamespace ( getItem ( ) ) ; final Runnable tPoller = ( ) -> { try { T t = get ( ) ; if ( t == null ) { if ( count == 0 ) { queue . put ( true ) ; } else { queue . put ( new IllegalStateException ( "Can't wait for " + getType ( ) . getSimpleName ( ) + ": " + name + " in namespace: " + namespace + " to scale. Resource is no longer available." ) ) ; } return ; } int currentReplicas = getCurrentReplicas ( t ) ; int desiredReplicas = getDesiredReplicas ( t ) ; replicasRef . set ( currentReplicas ) ; long generation = t . getMetadata ( ) . getGeneration ( ) != null ? t . getMetadata ( ) . getGeneration ( ) : - 1 ; long observedGeneration = getObservedGeneration ( t ) ; if ( observedGeneration >= generation && Objects . equals ( desiredReplicas , currentReplicas ) ) { queue . put ( true ) ; } Log . debug ( "Only {}/{} replicas scheduled for {}: {} in namespace: {} seconds so waiting..." , currentReplicas , desiredReplicas , t . getKind ( ) , t . getMetadata ( ) . getName ( ) , namespace ) ; } catch ( Throwable t ) { Log . error ( "Error while waiting for resource to be scaled." , t ) ; } } ; ScheduledExecutorService executor = Executors . newSingleThreadScheduledExecutor ( ) ; ScheduledFuture poller = executor . scheduleWithFixedDelay ( tPoller , 0 , POLL_INTERVAL_MS , TimeUnit . MILLISECONDS ) ; try { if ( Utils . waitUntilReady ( queue , rollingTimeout , rollingTimeUnit ) ) { Log . debug ( "{}/{} pod(s) ready for {}: {} in namespace: {}." , replicasRef . get ( ) , count , getType ( ) . getSimpleName ( ) , name , namespace ) ; } else { Log . error ( "{}/{} pod(s) ready for {}: {} in namespace: {} after waiting for {} seconds so giving up" , replicasRef . get ( ) , count , getType ( ) . getSimpleName ( ) , name , namespace , rollingTimeUnit . toSeconds ( rollingTimeout ) ) ; } } finally { poller . cancel ( true ) ; executor . shutdown ( ) ; } }
Let s wait until there are enough Ready pods .
9,436
private void waitUntilPodsAreReady ( final T obj , final String namespace , final int requiredPodCount ) { final CountDownLatch countDownLatch = new CountDownLatch ( 1 ) ; final AtomicInteger podCount = new AtomicInteger ( 0 ) ; final Runnable readyPodsPoller = ( ) -> { PodList podList = listSelectedPods ( obj ) ; int count = 0 ; List < Pod > items = podList . getItems ( ) ; for ( Pod item : items ) { for ( PodCondition c : item . getStatus ( ) . getConditions ( ) ) { if ( c . getType ( ) . equals ( "Ready" ) && c . getStatus ( ) . equals ( "True" ) ) { count ++ ; } } } podCount . set ( count ) ; if ( count == requiredPodCount ) { countDownLatch . countDown ( ) ; } } ; ScheduledExecutorService executor = Executors . newSingleThreadScheduledExecutor ( ) ; ScheduledFuture poller = executor . scheduleWithFixedDelay ( readyPodsPoller , 0 , 1 , TimeUnit . SECONDS ) ; ScheduledFuture logger = executor . scheduleWithFixedDelay ( ( ) -> LOG . debug ( "Only {}/{} pod(s) ready for {}: {} in namespace: {} seconds so waiting..." , podCount . get ( ) , requiredPodCount , obj . getKind ( ) , obj . getMetadata ( ) . getName ( ) , namespace ) , 0 , loggingIntervalMillis , TimeUnit . MILLISECONDS ) ; try { countDownLatch . await ( rollingTimeoutMillis , TimeUnit . MILLISECONDS ) ; executor . shutdown ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; poller . cancel ( true ) ; logger . cancel ( true ) ; executor . shutdown ( ) ; LOG . warn ( "Only {}/{} pod(s) ready for {}: {} in namespace: {} after waiting for {} seconds so giving up" , podCount . get ( ) , requiredPodCount , obj . getKind ( ) , obj . getMetadata ( ) . getName ( ) , namespace , TimeUnit . MILLISECONDS . toSeconds ( rollingTimeoutMillis ) ) ; } }
Lets wait until there are enough Ready pods of the given RC
9,437
private static PodCondition getPodReadyCondition ( Pod pod ) { Utils . checkNotNull ( pod , "Pod can't be null." ) ; if ( pod . getStatus ( ) == null || pod . getStatus ( ) . getConditions ( ) == null ) { return null ; } for ( PodCondition condition : pod . getStatus ( ) . getConditions ( ) ) { if ( POD_READY . equals ( condition . getType ( ) ) ) { return condition ; } } return null ; }
Returns the ready condition of the pod .
9,438
private static NodeCondition getNodeReadyCondition ( Node node ) { Utils . checkNotNull ( node , "Node can't be null." ) ; if ( node . getStatus ( ) == null || node . getStatus ( ) . getConditions ( ) == null ) { return null ; } for ( NodeCondition condition : node . getStatus ( ) . getConditions ( ) ) { if ( NODE_READY . equals ( condition . getType ( ) ) ) { return condition ; } } return null ; }
Returns the ready condition of the node .
9,439
public static String getResourceVersion ( HasMetadata entity ) { if ( entity != null ) { ObjectMeta metadata = entity . getMetadata ( ) ; if ( metadata != null ) { String resourceVersion = metadata . getResourceVersion ( ) ; if ( ! Utils . isNullOrEmpty ( resourceVersion ) ) { return resourceVersion ; } } } return null ; }
Returns the resource version for the entity or null if it does not have one
9,440
public static String getKind ( HasMetadata entity ) { if ( entity != null ) { if ( entity instanceof KubernetesList ) { return "List" ; } else { return entity . getClass ( ) . getSimpleName ( ) ; } } else { return null ; } }
Returns the kind of the entity
9,441
public static String getQualifiedName ( HasMetadata entity ) { if ( entity != null ) { return "" + getNamespace ( entity ) + "/" + getName ( entity ) ; } else { return null ; } }
Returns Qualified name for the specified Kubernetes Resource
9,442
public static String getNamespace ( HasMetadata entity ) { if ( entity != null ) { return getNamespace ( entity . getMetadata ( ) ) ; } else { return null ; } }
Getting namespace from Kubernetes Resource
9,443
public static Map < String , String > getOrCreateLabels ( HasMetadata entity ) { ObjectMeta metadata = getOrCreateMetadata ( entity ) ; Map < String , String > answer = metadata . getLabels ( ) ; if ( answer == null ) { answer = new LinkedHashMap < > ( ) ; metadata . setLabels ( answer ) ; } return answer ; }
Null safe get method for getting Labels of a Kubernetes Resource
9,444
@ SuppressWarnings ( "unchecked" ) public static Map < String , String > getLabels ( ObjectMeta metadata ) { if ( metadata != null ) { Map < String , String > labels = metadata . getLabels ( ) ; if ( labels != null ) { return labels ; } } return Collections . EMPTY_MAP ; }
Returns the labels of the given metadata object or an empty map if the metadata or labels are null
9,445
public static boolean isValidName ( String name ) { return Utils . isNotNullOrEmpty ( name ) && name . length ( ) < KUBERNETES_DNS1123_LABEL_MAX_LENGTH && KUBERNETES_DNS1123_LABEL_REGEX . matcher ( name ) . matches ( ) ; }
Validates name of Kubernetes Resource name label or annotation based on Kubernetes regex
9,446
public static InputStream replaceValues ( InputStream is , Map < String , String > valuesMap ) { return new ReplaceValueStream ( valuesMap ) . createInputStream ( is ) ; }
Returns a stream with the template parameter expressions replaced
9,447
private static final String getKey ( String apiVersion , String kind ) { if ( kind == null ) { return null ; } else if ( apiVersion == null ) { return kind ; } else { return String . format ( "%s#%s" , apiVersion , kind ) ; } }
Returns a composite key for apiVersion and kind .
9,448
public static String getUserToken ( Config config , Context context ) { AuthInfo authInfo = getUserAuthInfo ( config , context ) ; if ( authInfo != null ) { return authInfo . getToken ( ) ; } return null ; }
Returns the current user token for the config and current context
9,449
private static boolean checkConditionMetForAll ( CountDownLatch latch , int expected , AtomicInteger actual , long amount , TimeUnit timeUnit ) { try { if ( latch . await ( amount , timeUnit ) ) { return actual . intValue ( ) == expected ; } return false ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; return false ; } }
Waits until the latch reaches to zero and then checks if the expected result
9,450
protected T periodicWatchUntilReady ( int i , long started , long interval , long amount ) { T item = fromServer ( ) . get ( ) ; if ( Readiness . isReady ( item ) ) { return item ; } ReadinessWatcher < T > watcher = new ReadinessWatcher < > ( item ) ; try ( Watch watch = watch ( item . getMetadata ( ) . getResourceVersion ( ) , watcher ) ) { try { return watcher . await ( interval , TimeUnit . MILLISECONDS ) ; } catch ( KubernetesClientTimeoutException e ) { if ( i <= 0 ) { throw e ; } } long remaining = ( started + amount ) - System . nanoTime ( ) ; long next = Math . max ( 0 , Math . min ( remaining , interval ) ) ; return periodicWatchUntilReady ( i - 1 , started , next , amount ) ; } }
A wait method that combines watching and polling . The need for that is that in some cases a pure watcher approach consistently fails .
9,451
public static String replaceAllWithoutRegex ( String text , String from , String to ) { if ( text == null ) { return null ; } int idx = 0 ; while ( true ) { idx = text . indexOf ( from , idx ) ; if ( idx >= 0 ) { text = text . substring ( 0 , idx ) + to + text . substring ( idx + from . length ( ) ) ; idx += to . length ( ) ; } else { break ; } } return text ; }
Replaces all occurrences of the from text with to text without any regular expressions
9,452
public static final String toUrlEncoded ( String str ) { try { return URLEncoder . encode ( str , "UTF-8" ) ; } catch ( UnsupportedEncodingException exception ) { } return null ; }
Converts string to URL encoded string .
9,453
private static < T > String name ( T item , String name ) { if ( name != null && ! name . isEmpty ( ) ) { return name ; } else if ( item instanceof HasMetadata ) { HasMetadata h = ( HasMetadata ) item ; return h . getMetadata ( ) != null ? h . getMetadata ( ) . getName ( ) : null ; } return null ; }
Returns the name and falls back to the item name .
9,454
protected void updateApiVersionResource ( Object resource ) { if ( resource instanceof HasMetadata ) { HasMetadata hasMetadata = ( HasMetadata ) resource ; updateApiVersion ( hasMetadata ) ; } else if ( resource instanceof KubernetesResourceList ) { KubernetesResourceList list = ( KubernetesResourceList ) resource ; updateApiVersion ( list ) ; } }
Updates the list or single item if it has a missing or incorrect apiGroupVersion
9,455
protected void updateApiVersion ( KubernetesResourceList list ) { String version = getApiVersion ( ) ; if ( list != null && version != null && version . length ( ) > 0 ) { List items = list . getItems ( ) ; if ( items != null ) { for ( Object item : items ) { if ( item instanceof HasMetadata ) { updateApiVersion ( ( HasMetadata ) item ) ; } } } } }
Updates the list items if they have missing or default apiGroupVersion values and the resource is currently using API Groups with custom version strings
9,456
protected void updateApiVersion ( HasMetadata hasMetadata ) { String version = getApiVersion ( ) ; if ( hasMetadata != null && version != null && version . length ( ) > 0 ) { String current = hasMetadata . getApiVersion ( ) ; if ( current == null || "v1" . equals ( current ) || current . indexOf ( '/' ) < 0 && version . indexOf ( '/' ) > 0 ) { hasMetadata . setApiVersion ( version ) ; } } }
Updates the resource if it has missing or default apiGroupVersion values and the resource is currently using API Groups with custom version strings
9,457
protected < T , I > T handleCreate ( I resource , Class < T > outputType ) throws ExecutionException , InterruptedException , KubernetesClientException , IOException { RequestBody body = RequestBody . create ( JSON , JSON_MAPPER . writeValueAsString ( resource ) ) ; Request . Builder requestBuilder = new Request . Builder ( ) . post ( body ) . url ( getNamespacedUrl ( checkNamespace ( resource ) ) ) ; return handleResponse ( requestBuilder , outputType , Collections . < String , String > emptyMap ( ) ) ; }
Create a resource .
9,458
protected < T > T handleReplace ( T updated , Class < T > type ) throws ExecutionException , InterruptedException , KubernetesClientException , IOException { return handleReplace ( updated , type , Collections . < String , String > emptyMap ( ) ) ; }
Replace a resource .
9,459
protected < T > T handleReplace ( T updated , Class < T > type , Map < String , String > parameters ) throws ExecutionException , InterruptedException , KubernetesClientException , IOException { RequestBody body = RequestBody . create ( JSON , JSON_MAPPER . writeValueAsString ( updated ) ) ; Request . Builder requestBuilder = new Request . Builder ( ) . put ( body ) . url ( getResourceUrl ( checkNamespace ( updated ) , checkName ( updated ) ) ) ; return handleResponse ( requestBuilder , type , parameters ) ; }
Replace a resource optionally performing placeholder substitution to the response .
9,460
protected < T > T handlePatch ( T current , T updated , Class < T > type ) throws ExecutionException , InterruptedException , KubernetesClientException , IOException { JsonNode diff = JsonDiff . asJson ( patchMapper ( ) . valueToTree ( current ) , patchMapper ( ) . valueToTree ( updated ) ) ; RequestBody body = RequestBody . create ( JSON_PATCH , JSON_MAPPER . writeValueAsString ( diff ) ) ; Request . Builder requestBuilder = new Request . Builder ( ) . patch ( body ) . url ( getResourceUrl ( checkNamespace ( updated ) , checkName ( updated ) ) ) ; return handleResponse ( requestBuilder , type , Collections . < String , String > emptyMap ( ) ) ; }
Send an http patch and handle the response .
9,461
protected < T > T handleGet ( URL resourceUrl , Class < T > type ) throws ExecutionException , InterruptedException , KubernetesClientException , IOException { return handleGet ( resourceUrl , type , Collections . < String , String > emptyMap ( ) ) ; }
Send an http get .
9,462
protected < T > T handleGet ( URL resourceUrl , Class < T > type , Map < String , String > parameters ) throws ExecutionException , InterruptedException , KubernetesClientException , IOException { Request . Builder requestBuilder = new Request . Builder ( ) . get ( ) . url ( resourceUrl ) ; return handleResponse ( requestBuilder , type , parameters ) ; }
Send an http optionally performing placeholder substitution to the response .
9,463
protected < T > T handleResponse ( Request . Builder requestBuilder , Class < T > type ) throws ExecutionException , InterruptedException , KubernetesClientException , IOException { return handleResponse ( requestBuilder , type , Collections . < String , String > emptyMap ( ) ) ; }
Send an http request and handle the response .
9,464
protected < T > T handleResponse ( OkHttpClient client , Request . Builder requestBuilder , Class < T > type , Map < String , String > parameters ) throws ExecutionException , InterruptedException , KubernetesClientException , IOException { VersionUsageUtils . log ( this . resourceT , this . apiGroupVersion ) ; Request request = requestBuilder . build ( ) ; Response response = client . newCall ( request ) . execute ( ) ; try ( ResponseBody body = response . body ( ) ) { assertResponseCode ( request , response ) ; if ( type != null ) { try ( InputStream bodyInputStream = body . byteStream ( ) ) { return Serialization . unmarshal ( bodyInputStream , type , parameters ) ; } } else { return null ; } } catch ( Exception e ) { if ( e instanceof KubernetesClientException ) { throw e ; } throw requestException ( request , e ) ; } finally { if ( response != null && response . body ( ) != null ) { response . body ( ) . close ( ) ; } } }
Send an http request and handle the response optionally performing placeholder substitution to the response .
9,465
protected void assertResponseCode ( Request request , Response response ) { int statusCode = response . code ( ) ; String customMessage = config . getErrorMessages ( ) . get ( statusCode ) ; if ( response . isSuccessful ( ) ) { return ; } else if ( customMessage != null ) { throw requestFailure ( request , createStatus ( statusCode , combineMessages ( customMessage , createStatus ( response ) ) ) ) ; } else { throw requestFailure ( request , createStatus ( response ) ) ; } }
Checks if the response status code is the expected and throws the appropriate KubernetesClientException if not .
9,466
private void waitUntilJobIsScaled ( ) { final CountDownLatch countDownLatch = new CountDownLatch ( 1 ) ; final AtomicReference < Job > atomicJob = new AtomicReference < > ( ) ; final Runnable jobPoller = ( ) -> { try { Job job = getMandatory ( ) ; atomicJob . set ( job ) ; Integer activeJobs = job . getStatus ( ) . getActive ( ) ; if ( activeJobs == null ) { activeJobs = 0 ; } if ( Objects . equals ( job . getSpec ( ) . getParallelism ( ) , activeJobs ) ) { countDownLatch . countDown ( ) ; } else { LOG . debug ( "Only {}/{} pods scheduled for Job: {} in namespace: {} seconds so waiting..." , job . getStatus ( ) . getActive ( ) , job . getSpec ( ) . getParallelism ( ) , job . getMetadata ( ) . getName ( ) , namespace ) ; } } catch ( Throwable t ) { LOG . error ( "Error while waiting for Job to be scaled." , t ) ; } } ; ScheduledExecutorService executor = Executors . newSingleThreadScheduledExecutor ( ) ; ScheduledFuture poller = executor . scheduleWithFixedDelay ( jobPoller , 0 , POLL_INTERVAL_MS , TimeUnit . MILLISECONDS ) ; try { countDownLatch . await ( getConfig ( ) . getScaleTimeout ( ) , TimeUnit . MILLISECONDS ) ; executor . shutdown ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; poller . cancel ( true ) ; executor . shutdown ( ) ; LOG . error ( "Only {}/{} pod(s) ready for Job: {} in namespace: {} - giving up" , atomicJob . get ( ) . getStatus ( ) . getActive ( ) , atomicJob . get ( ) . getSpec ( ) . getParallelism ( ) , atomicJob . get ( ) . getMetadata ( ) . getName ( ) , namespace ) ; } }
Lets wait until there are enough Ready pods of the given Job
9,467
public static Config autoConfigure ( String context ) { Config config = new Config ( ) ; return autoConfigure ( config , context ) ; }
Does auto detection with some opinionated defaults .
9,468
public static Counter . Builder prepareCounterFor ( final MethodDescriptor < ? , ? > method , final String name , final String description ) { return Counter . builder ( name ) . description ( description ) . baseUnit ( "messages" ) . tag ( TAG_SERVICE_NAME , extractServiceName ( method ) ) . tag ( TAG_METHOD_NAME , extractMethodName ( method ) ) ; }
Creates a new counter builder for the given method . By default the base unit will be messages .
9,469
public static Timer . Builder prepareTimerFor ( final MethodDescriptor < ? , ? > method , final String name , final String description ) { return Timer . builder ( name ) . description ( description ) . tag ( TAG_SERVICE_NAME , extractServiceName ( method ) ) . tag ( TAG_METHOD_NAME , extractMethodName ( method ) ) ; }
Creates a new timer builder for the given method .
9,470
public static Function < X509CertificateAuthentication , String > patternExtractor ( final String key , final Function < ? super X509CertificateAuthentication , String > fallback ) { requireNonNull ( key , "key" ) ; requireNonNull ( fallback , "fallback" ) ; final Pattern pattern = Pattern . compile ( key + "=(.+?)(?:,|$)" , Pattern . CASE_INSENSITIVE ) ; return authentication -> { final Object principal = authentication . getPrincipal ( ) ; if ( principal instanceof X500Principal ) { final X500Principal x500Principal = ( X500Principal ) principal ; final Matcher matcher = pattern . matcher ( x500Principal . getName ( ) ) ; if ( matcher . find ( ) ) { return matcher . group ( 1 ) ; } } return fallback . apply ( authentication ) ; } ; }
Creates a new case - insensitive pattern extractor with the given pattern .
9,471
public static String extractMethodName ( final MethodDescriptor < ? , ? > method ) { final String fullMethodName = method . getFullMethodName ( ) ; final int index = fullMethodName . lastIndexOf ( '/' ) ; if ( index == - 1 ) { return fullMethodName ; } return fullMethodName . substring ( index + 1 ) ; }
Extracts the method name from the given method .
9,472
protected List < String > collectMethodNamesForService ( final ServiceDescriptor serviceDescriptor ) { final List < String > methods = new ArrayList < > ( ) ; for ( final MethodDescriptor < ? , ? > grpcMethod : serviceDescriptor . getMethods ( ) ) { methods . add ( extractMethodName ( grpcMethod ) ) ; } methods . sort ( String . CASE_INSENSITIVE_ORDER ) ; return methods ; }
Gets all method names from the given service descriptor .
9,473
@ ConditionalOnSingleCandidate ( LoadBalancer . Factory . class ) @ ConditionalOnMissingBean ( name = "grpcLoadBalancerConfigurer" ) @ SuppressWarnings ( "deprecation" ) public GrpcChannelConfigurer grpcLoadBalancerConfigurer ( final LoadBalancer . Factory loadBalancerFactory ) { return ( channel , name ) -> channel . loadBalancerFactory ( loadBalancerFactory ) ; }
Creates the load balancer configurer bean for the given load balancer factory .
9,474
@ ConditionalOnMissingBean ( GrpcChannelFactory . class ) @ ConditionalOnClass ( name = { "io.netty.channel.Channel" , "io.grpc.netty.NettyChannelBuilder" } ) public GrpcChannelFactory nettyGrpcChannelFactory ( final GrpcChannelsProperties properties , final NameResolver . Factory nameResolverFactory , final GlobalClientInterceptorRegistry globalClientInterceptorRegistry , final List < GrpcChannelConfigurer > channelConfigurers ) { final NettyChannelFactory channelFactory = new NettyChannelFactory ( properties , nameResolverFactory , globalClientInterceptorRegistry , channelConfigurers ) ; final InProcessChannelFactory inProcessChannelFactory = new InProcessChannelFactory ( properties , globalClientInterceptorRegistry , channelConfigurers ) ; return new InProcessOrAlternativeChannelFactory ( properties , inProcessChannelFactory , channelFactory ) ; }
Then try the normal netty channel factory
9,475
@ ConditionalOnMissingBean ( GrpcChannelFactory . class ) public GrpcChannelFactory inProcessGrpcChannelFactory ( final GrpcChannelsProperties properties , final GlobalClientInterceptorRegistry globalClientInterceptorRegistry , final List < GrpcChannelConfigurer > channelConfigurers ) { return new InProcessChannelFactory ( properties , globalClientInterceptorRegistry , channelConfigurers ) ; }
Finally try the in process channel factory
9,476
@ ConditionalOnClass ( name = { "io.grpc.netty.shaded.io.netty.channel.Channel" , "io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder" } ) public ShadedNettyGrpcServerFactory shadedNettyGrpcServerFactory ( final GrpcServerProperties properties , final GrpcServiceDiscoverer serviceDiscoverer , final List < GrpcServerConfigurer > serverConfigurers ) { final ShadedNettyGrpcServerFactory factory = new ShadedNettyGrpcServerFactory ( properties , serverConfigurers ) ; for ( final GrpcServiceDefinition service : serviceDiscoverer . findGrpcServices ( ) ) { factory . addService ( service ) ; } return factory ; }
Creates a GrpcServerFactory using the shaded netty . This is the recommended default for gRPC .
9,477
@ ConditionalOnClass ( name = { "io.netty.channel.Channel" , "io.grpc.netty.NettyServerBuilder" } ) public NettyGrpcServerFactory nettyGrpcServerFactory ( final GrpcServerProperties properties , final GrpcServiceDiscoverer serviceDiscoverer , final List < GrpcServerConfigurer > serverConfigurers ) { final NettyGrpcServerFactory factory = new NettyGrpcServerFactory ( properties , serverConfigurers ) ; for ( final GrpcServiceDefinition service : serviceDiscoverer . findGrpcServices ( ) ) { factory . addService ( service ) ; } return factory ; }
Creates a GrpcServerFactory using the non - shaded netty . This is the fallback if the shaded one is not present .
9,478
@ ConditionalOnClass ( name = { "io.netty.channel.Channel" , "io.grpc.netty.NettyServerBuilder" } ) public GrpcServerLifecycle nettyGrpcServerLifecycle ( final NettyGrpcServerFactory factory ) { return new GrpcServerLifecycle ( factory ) ; }
The server lifecycle bean for netty based server .
9,479
@ ConditionalOnProperty ( prefix = "grpc.server" , name = "inProcessName" ) public InProcessGrpcServerFactory inProcessGrpcServerFactory ( final GrpcServerProperties properties , final GrpcServiceDiscoverer serviceDiscoverer ) { final InProcessGrpcServerFactory factory = new InProcessGrpcServerFactory ( properties ) ; for ( final GrpcServiceDefinition service : serviceDiscoverer . findGrpcServices ( ) ) { factory . addService ( service ) ; } return factory ; }
Creates a GrpcServerFactory using the in - process - server if a name is specified .
9,480
public GrpcChannelProperties getChannel ( final String name ) { final GrpcChannelProperties properties = getRawChannel ( name ) ; properties . copyDefaultsFrom ( getGlobalChannel ( ) ) ; return properties ; }
Gets the properties for the given channel . If the properties for the specified channel name do not yet exist they are created automatically . Before the instance is returned the unset values are filled with values from the global properties .
9,481
protected Function < Code , Timer > asTimerFunction ( final Supplier < Timer . Builder > timerTemplate ) { final Map < Code , Timer > cache = new EnumMap < > ( Code . class ) ; final Function < Code , Timer > creator = code -> timerTemplate . get ( ) . tag ( TAG_STATUS_CODE , code . name ( ) ) . register ( this . registry ) ; final Function < Code , Timer > cacheResolver = code -> cache . computeIfAbsent ( code , creator ) ; for ( final Code code : this . eagerInitializedCodes ) { cacheResolver . apply ( code ) ; } return cacheResolver ; }
Creates a new timer function using the given template . This method initializes the default timers .
9,482
public void copyDefaultsFrom ( final GrpcChannelProperties config ) { if ( this == config ) { return ; } if ( this . address == null ) { this . address = config . address ; } if ( this . defaultLoadBalancingPolicy == null ) { this . defaultLoadBalancingPolicy = config . defaultLoadBalancingPolicy ; } if ( this . enableKeepAlive == null ) { this . enableKeepAlive = config . enableKeepAlive ; } if ( this . keepAliveTime == null ) { this . keepAliveTime = config . keepAliveTime ; } if ( this . keepAliveTimeout == null ) { this . keepAliveTimeout = config . keepAliveTimeout ; } if ( this . keepAliveWithoutCalls == null ) { this . keepAliveWithoutCalls = config . keepAliveWithoutCalls ; } if ( this . maxInboundMessageSize == null ) { this . maxInboundMessageSize = config . maxInboundMessageSize ; } if ( this . fullStreamDecompression == null ) { this . fullStreamDecompression = config . fullStreamDecompression ; } if ( this . negotiationType == null ) { this . negotiationType = config . negotiationType ; } this . security . copyDefaultsFrom ( config . security ) ; }
Copies the defaults from the given configuration . Values are considered default if they are null . Please note that the getters might return fallback values instead .
9,483
public ManualGrpcSecurityMetadataSource set ( final ServiceDescriptor service , final AccessPredicate predicate ) { requireNonNull ( service , "service" ) ; final Collection < ConfigAttribute > wrappedPredicate = wrap ( predicate ) ; for ( final MethodDescriptor < ? , ? > method : service . getMethods ( ) ) { this . accessMap . put ( method , wrappedPredicate ) ; } return this ; }
Set the given access predicate for the all methods of the given service . This will replace previously set predicates .
9,484
public ManualGrpcSecurityMetadataSource remove ( final ServiceDescriptor service ) { requireNonNull ( service , "service" ) ; for ( final MethodDescriptor < ? , ? > method : service . getMethods ( ) ) { this . accessMap . remove ( method ) ; } return this ; }
Removes all access predicates for the all methods of the given service . After that the default will be used for those methods .
9,485
public ManualGrpcSecurityMetadataSource set ( final MethodDescriptor < ? , ? > method , final AccessPredicate predicate ) { requireNonNull ( method , "method" ) ; this . accessMap . put ( method , wrap ( predicate ) ) ; return this ; }
Set the given access predicate for the given method . This will replace previously set predicates .
9,486
private Collection < ConfigAttribute > wrap ( final AccessPredicate predicate ) { requireNonNull ( predicate , "predicate" ) ; if ( predicate == AccessPredicates . PERMIT_ALL ) { return of ( ) ; } return of ( new AccessPredicateConfigAttribute ( predicate ) ) ; }
Wraps the given predicate in a configuration attribute and an immutable collection .
9,487
protected void configureServices ( final T builder ) { if ( this . properties . isHealthServiceEnabled ( ) ) { builder . addService ( this . healthStatusManager . getHealthService ( ) ) ; } if ( this . properties . isReflectionServiceEnabled ( ) ) { builder . addService ( ProtoReflectionService . newInstance ( ) ) ; } for ( final GrpcServiceDefinition service : this . serviceList ) { final String serviceName = service . getDefinition ( ) . getServiceDescriptor ( ) . getName ( ) ; log . info ( "Registered gRPC service: " + serviceName + ", bean: " + service . getBeanName ( ) + ", class: " + service . getBeanClazz ( ) . getName ( ) ) ; builder . addService ( service . getDefinition ( ) ) ; this . healthStatusManager . setStatus ( serviceName , HealthCheckResponse . ServingStatus . SERVING ) ; } }
Configures the services that should be served by the server .
9,488
protected void configureLimits ( final T builder ) { final Integer maxInboundMessageSize = this . properties . getMaxInboundMessageSize ( ) ; if ( maxInboundMessageSize != null ) { builder . maxInboundMessageSize ( maxInboundMessageSize ) ; } }
Configures limits such as max message sizes that should be used by the server .
9,489
protected void configure ( final T builder , final String name ) { configureKeepAlive ( builder , name ) ; configureSecurity ( builder , name ) ; configureLimits ( builder , name ) ; configureCompression ( builder , name ) ; for ( final GrpcChannelConfigurer channelConfigurer : this . channelConfigurers ) { channelConfigurer . accept ( builder , name ) ; } }
Configures the given channel builder . This method can be overwritten to add features that are not yet supported by this library .
9,490
protected void configureKeepAlive ( final T builder , final String name ) { final GrpcChannelProperties properties = getPropertiesFor ( name ) ; if ( properties . isEnableKeepAlive ( ) ) { builder . keepAliveTime ( properties . getKeepAliveTime ( ) . toNanos ( ) , TimeUnit . NANOSECONDS ) . keepAliveTimeout ( properties . getKeepAliveTimeout ( ) . toNanos ( ) , TimeUnit . NANOSECONDS ) . keepAliveWithoutCalls ( properties . isKeepAliveWithoutCalls ( ) ) ; } }
Configures the keep alive options that should be used by the channel .
9,491
protected void configureSecurity ( final T builder , final String name ) { final GrpcChannelProperties properties = getPropertiesFor ( name ) ; final Security security = properties . getSecurity ( ) ; if ( properties . getNegotiationType ( ) != NegotiationType . TLS || isNonNullAndNonBlank ( security . getAuthorityOverride ( ) ) || isNonNullAndNonBlank ( security . getCertificateChainPath ( ) ) || isNonNullAndNonBlank ( security . getPrivateKeyPath ( ) ) || isNonNullAndNonBlank ( security . getTrustCertCollectionPath ( ) ) ) { throw new IllegalStateException ( "Security is configured but this implementation does not support security!" ) ; } }
Configures the security options that should be used by the channel .
9,492
protected void configureLimits ( final T builder , final String name ) { final GrpcChannelProperties properties = getPropertiesFor ( name ) ; final Integer maxInboundMessageSize = properties . getMaxInboundMessageSize ( ) ; if ( maxInboundMessageSize != null ) { builder . maxInboundMessageSize ( maxInboundMessageSize ) ; } }
Configures limits such as max message sizes that should be used by the channel .
9,493
protected void configureCompression ( final T builder , final String name ) { final GrpcChannelProperties properties = getPropertiesFor ( name ) ; if ( properties . isFullStreamDecompression ( ) ) { builder . enableFullStreamDecompression ( ) ; } }
Configures the compression options that should be used by the channel .
9,494
public synchronized void close ( ) { if ( this . shutdown ) { return ; } this . shutdown = true ; for ( final ManagedChannel channel : this . channels . values ( ) ) { channel . shutdown ( ) ; } try { final long waitLimit = System . currentTimeMillis ( ) + 60_000 ; for ( final ManagedChannel channel : this . channels . values ( ) ) { int i = 0 ; do { log . debug ( "Awaiting channel shutdown: {} ({}s)" , channel , i ++ ) ; } while ( System . currentTimeMillis ( ) < waitLimit && ! channel . awaitTermination ( 1 , TimeUnit . SECONDS ) ) ; } } catch ( final InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; log . debug ( "We got interrupted - Speeding up shutdown process" ) ; } finally { for ( final ManagedChannel channel : this . channels . values ( ) ) { if ( ! channel . isTerminated ( ) ) { log . debug ( "Channel not terminated yet - force shutdown now: {} " , channel ) ; channel . shutdownNow ( ) ; } } } final int channelCount = this . channels . size ( ) ; this . channels . clear ( ) ; log . debug ( "GrpcCannelFactory closed (including {} channels)" , channelCount ) ; }
Closes this channel factory and the channels created by this instance . The shutdown happens in two phases first an orderly shutdown is initiated on all channels and then the method waits for all channels to terminate . If the channels don t have terminated after 60 seconds then they will be forcefully shutdown .
9,495
protected void createAndStartGrpcServer ( ) throws IOException { final Server localServer = this . server ; if ( localServer == null ) { this . server = this . factory . createServer ( ) ; this . server . start ( ) ; log . info ( "gRPC Server started, listening on address: " + this . factory . getAddress ( ) + ", port: " + this . factory . getPort ( ) ) ; final Thread awaitThread = new Thread ( "container-" + ( serverCounter . incrementAndGet ( ) ) ) { public void run ( ) { try { GrpcServerLifecycle . this . server . awaitTermination ( ) ; } catch ( final InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } } ; awaitThread . setDaemon ( false ) ; awaitThread . start ( ) ; } }
Creates and starts the grpc server .
9,496
protected void stopAndReleaseGrpcServer ( ) { factory . destroy ( ) ; Server localServer = this . server ; if ( localServer != null ) { localServer . shutdown ( ) ; this . server = null ; log . info ( "gRPC server shutdown." ) ; } }
Initiates an orderly shutdown of the grpc server and releases the references to the server . This call does not wait for the server to be completely shut down .
9,497
public static CallCredentials bearerAuth ( final String token ) { final Metadata extraHeaders = new Metadata ( ) ; extraHeaders . put ( AUTHORIZATION_HEADER , BEARER_AUTH_PREFIX + token ) ; return new StaticSecurityHeaderCallCredentials ( extraHeaders ) ; }
Creates a new call credential with the given token for bearer auth .
9,498
public static CallCredentials basicAuth ( final String username , final String password ) { final Metadata extraHeaders = new Metadata ( ) ; extraHeaders . put ( AUTHORIZATION_HEADER , encodeBasicAuth ( username , password ) ) ; return new StaticSecurityHeaderCallCredentials ( extraHeaders ) ; }
Creates a new call credential with the given username and password for basic auth .
9,499
@ Secured ( "ROLE_TEST" ) public void sayHello ( final HelloRequest req , final StreamObserver < HelloReply > responseObserver ) { final HelloReply reply = HelloReply . newBuilder ( ) . setMessage ( "Hello ==> " + req . getName ( ) ) . build ( ) ; responseObserver . onNext ( reply ) ; responseObserver . onCompleted ( ) ; }
A grpc method that requests the user to be authenticated and have the role ROLE_GREET .