idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
152,700
|
public < T > ApiResponse < T > execute ( Call call , Type returnType ) throws ApiException { try { Response response = call . execute ( ) ; T data = handleResponse ( response , returnType ) ; return new ApiResponse < T > ( response . code ( ) , response . headers ( ) . toMultimap ( ) , data ) ; } catch ( IOException e ) { throw new ApiException ( e ) ; } }
|
Execute HTTP call and deserialize the HTTP response body into the given return type .
| 97
| 18
|
152,701
|
@ SuppressWarnings ( "unchecked" ) public < T > void executeAsync ( Call call , final Type returnType , final ApiCallback < T > callback ) { call . enqueue ( new Callback ( ) { @ Override public void onFailure ( Request request , IOException e ) { callback . onFailure ( new ApiException ( e ) , 0 , null ) ; } @ Override public void onResponse ( Response response ) throws IOException { T result ; try { result = ( T ) handleResponse ( response , returnType ) ; } catch ( ApiException e ) { callback . onFailure ( e , response . code ( ) , response . headers ( ) . toMultimap ( ) ) ; return ; } callback . onSuccess ( result , response . code ( ) , response . headers ( ) . toMultimap ( ) ) ; } } ) ; }
|
Execute HTTP call asynchronously .
| 189
| 8
|
152,702
|
public Call buildCall ( String path , String method , List < Pair > queryParams , List < Pair > collectionQueryParams , Object body , Map < String , String > headerParams , Map < String , Object > formParams , String [ ] authNames , ProgressRequestBody . ProgressRequestListener progressRequestListener ) throws ApiException { Request request = buildRequest ( path , method , queryParams , collectionQueryParams , body , headerParams , formParams , authNames , progressRequestListener ) ; return httpClient . newCall ( request ) ; }
|
Build HTTP call with the given options .
| 121
| 8
|
152,703
|
public Request buildRequest ( String path , String method , List < Pair > queryParams , List < Pair > collectionQueryParams , Object body , Map < String , String > headerParams , Map < String , Object > formParams , String [ ] authNames , ProgressRequestBody . ProgressRequestListener progressRequestListener ) throws ApiException { updateParamsForAuth ( authNames , queryParams , headerParams ) ; final String url = buildUrl ( path , queryParams , collectionQueryParams ) ; final Request . Builder reqBuilder = new Request . Builder ( ) . url ( url ) ; processHeaderParams ( headerParams , reqBuilder ) ; String contentType = ( String ) headerParams . get ( "Content-Type" ) ; // ensuring a default content type if ( contentType == null ) { contentType = "application/json" ; } RequestBody reqBody ; if ( ! HttpMethod . permitsRequestBody ( method ) ) { reqBody = null ; } else if ( "application/x-www-form-urlencoded" . equals ( contentType ) ) { reqBody = buildRequestBodyFormEncoding ( formParams ) ; } else if ( "multipart/form-data" . equals ( contentType ) ) { reqBody = buildRequestBodyMultipart ( formParams ) ; } else if ( body == null ) { if ( "DELETE" . equals ( method ) ) { // allow calling DELETE without sending a request body reqBody = null ; } else { // use an empty request body (for POST, PUT and PATCH) reqBody = RequestBody . create ( MediaType . parse ( contentType ) , "" ) ; } } else { reqBody = serialize ( body , contentType ) ; } Request request = null ; if ( progressRequestListener != null && reqBody != null ) { ProgressRequestBody progressRequestBody = new ProgressRequestBody ( reqBody , progressRequestListener ) ; request = reqBuilder . method ( method , progressRequestBody ) . build ( ) ; } else { request = reqBuilder . method ( method , reqBody ) . build ( ) ; } return request ; }
|
Build an HTTP request with the given options .
| 464
| 9
|
152,704
|
public void processHeaderParams ( Map < String , String > headerParams , Request . Builder reqBuilder ) { for ( Entry < String , String > param : headerParams . entrySet ( ) ) { reqBuilder . header ( param . getKey ( ) , parameterToString ( param . getValue ( ) ) ) ; } for ( Entry < String , String > header : defaultHeaderMap . entrySet ( ) ) { if ( ! headerParams . containsKey ( header . getKey ( ) ) ) { reqBuilder . header ( header . getKey ( ) , parameterToString ( header . getValue ( ) ) ) ; } } }
|
Set header parameters to the request builder including default headers .
| 137
| 11
|
152,705
|
public void updateParamsForAuth ( String [ ] authNames , List < Pair > queryParams , Map < String , String > headerParams ) { for ( String authName : authNames ) { Authentication auth = authentications . get ( authName ) ; if ( auth == null ) throw new RuntimeException ( "Authentication undefined: " + authName ) ; auth . applyToParams ( queryParams , headerParams ) ; } }
|
Update query and header parameters based on authentication settings .
| 95
| 10
|
152,706
|
public RequestBody buildRequestBodyFormEncoding ( Map < String , Object > formParams ) { FormEncodingBuilder formBuilder = new FormEncodingBuilder ( ) ; for ( Entry < String , Object > param : formParams . entrySet ( ) ) { formBuilder . add ( param . getKey ( ) , parameterToString ( param . getValue ( ) ) ) ; } return formBuilder . build ( ) ; }
|
Build a form - encoding request body with the given form parameters .
| 91
| 13
|
152,707
|
private void applySslSettings ( ) { try { TrustManager [ ] trustManagers = null ; HostnameVerifier hostnameVerifier = null ; if ( ! verifyingSsl ) { TrustManager trustAll = new X509TrustManager ( ) { @ Override public void checkClientTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { } @ Override public void checkServerTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { } @ Override public X509Certificate [ ] getAcceptedIssuers ( ) { return null ; } } ; SSLContext sslContext = SSLContext . getInstance ( "TLS" ) ; trustManagers = new TrustManager [ ] { trustAll } ; hostnameVerifier = new HostnameVerifier ( ) { @ Override public boolean verify ( String hostname , SSLSession session ) { return true ; } } ; } else if ( sslCaCert != null ) { char [ ] password = null ; // Any password will work. CertificateFactory certificateFactory = CertificateFactory . getInstance ( "X.509" ) ; Collection < ? extends Certificate > certificates = certificateFactory . generateCertificates ( sslCaCert ) ; if ( certificates . isEmpty ( ) ) { throw new IllegalArgumentException ( "expected non-empty set of trusted certificates" ) ; } KeyStore caKeyStore = newEmptyKeyStore ( password ) ; int index = 0 ; for ( Certificate certificate : certificates ) { String certificateAlias = "ca" + Integer . toString ( index ++ ) ; caKeyStore . setCertificateEntry ( certificateAlias , certificate ) ; } TrustManagerFactory trustManagerFactory = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; trustManagerFactory . init ( caKeyStore ) ; trustManagers = trustManagerFactory . getTrustManagers ( ) ; } if ( keyManagers != null || trustManagers != null ) { SSLContext sslContext = SSLContext . getInstance ( "TLS" ) ; sslContext . init ( keyManagers , trustManagers , new SecureRandom ( ) ) ; httpClient . setSslSocketFactory ( sslContext . getSocketFactory ( ) ) ; } else { httpClient . setSslSocketFactory ( null ) ; } httpClient . setHostnameVerifier ( hostnameVerifier ) ; } catch ( GeneralSecurityException e ) { throw new RuntimeException ( e ) ; } }
|
Apply SSL related settings to httpClient according to the current values of verifyingSsl and sslCaCert .
| 531
| 22
|
152,708
|
public void stop ( ) { reflector . stop ( ) ; reflectorFuture . cancel ( true ) ; reflectExecutor . shutdown ( ) ; if ( resyncFuture != null ) { resyncFuture . cancel ( true ) ; resyncExecutor . shutdown ( ) ; } }
|
stops the resync thread pool firstly then stop the reflector
| 59
| 14
|
152,709
|
private void processLoop ( ) { while ( true ) { try { this . queue . pop ( this . processFunc ) ; } catch ( InterruptedException t ) { log . error ( "DefaultController#processLoop get interrupted {}" , t . getMessage ( ) , t ) ; } } }
|
processLoop drains the work queue .
| 64
| 7
|
152,710
|
@ Override public void add ( Object obj ) { lock . writeLock ( ) . lock ( ) ; try { populated = true ; this . queueActionLocked ( DeltaType . Added , obj ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
|
Add items to the delta FIFO .
| 59
| 9
|
152,711
|
@ Override public void update ( Object obj ) { lock . writeLock ( ) . lock ( ) ; try { populated = true ; this . queueActionLocked ( DeltaType . Updated , obj ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
|
Update items in the delta FIFO .
| 59
| 9
|
152,712
|
@ Override public void delete ( Object obj ) { String id = this . keyOf ( obj ) ; lock . writeLock ( ) . lock ( ) ; try { this . populated = true ; if ( this . knownObjects == null ) { if ( ! this . items . containsKey ( id ) ) { // Presumably, this was deleted when a relist happened. // Don't provide a second report of the same deletion. return ; } } else { // We only want to skip the "deletion" action if the object doesn't // exist in knownObjects and it doesn't have corresponding item in items. if ( this . knownObjects . getByKey ( id ) == null && ! this . items . containsKey ( id ) ) { return ; } } this . queueActionLocked ( DeltaType . Deleted , obj ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
|
Delete items from the delta FIFO .
| 195
| 9
|
152,713
|
@ Override public void replace ( List list , String resourceVersion ) { lock . writeLock ( ) . lock ( ) ; try { Set < String > keys = new HashSet <> ( ) ; for ( Object obj : list ) { String key = this . keyOf ( obj ) ; keys . add ( key ) ; this . queueActionLocked ( DeltaType . Sync , obj ) ; } if ( this . knownObjects == null ) { for ( Map . Entry < String , Deque < MutablePair < DeltaType , Object > > > entry : this . items . entrySet ( ) ) { if ( keys . contains ( entry . getKey ( ) ) ) { continue ; } Object deletedObj = null ; MutablePair < DeltaType , Object > delta = entry . getValue ( ) . peekLast ( ) ; // get newest if ( delta != null ) { deletedObj = delta . getRight ( ) ; } this . queueActionLocked ( DeltaType . Deleted , new DeletedFinalStateUnknown ( entry . getKey ( ) , deletedObj ) ) ; } if ( ! this . populated ) { this . populated = true ; this . initialPopulationCount = list . size ( ) ; } return ; } // Detect deletions not already in the queue. List < String > knownKeys = this . knownObjects . listKeys ( ) ; int queueDeletion = 0 ; for ( String knownKey : knownKeys ) { if ( keys . contains ( knownKey ) ) { continue ; } Object deletedObj = this . knownObjects . getByKey ( knownKey ) ; if ( deletedObj == null ) { log . warn ( "Key {} does not exist in known objects store, placing DeleteFinalStateUnknown marker without object" , knownKey ) ; } queueDeletion ++ ; this . queueActionLocked ( DeltaType . Deleted , new DeletedFinalStateUnknown <> ( knownKey , deletedObj ) ) ; } if ( ! this . populated ) { this . populated = true ; this . initialPopulationCount = list . size ( ) + queueDeletion ; } } finally { lock . writeLock ( ) . unlock ( ) ; } }
|
Replace the item forcibly .
| 463
| 6
|
152,714
|
@ Override public void resync ( ) { lock . writeLock ( ) . lock ( ) ; try { if ( this . knownObjects == null ) { return ; } List < String > keys = this . knownObjects . listKeys ( ) ; for ( String key : keys ) { syncKeyLocked ( key ) ; } } finally { lock . writeLock ( ) . unlock ( ) ; } }
|
Re - sync the delta FIFO . First It locks the queue to block any more write operation until it finishes processing all the pending items in the queue .
| 87
| 32
|
152,715
|
@ Override public List < String > listKeys ( ) { lock . readLock ( ) . lock ( ) ; try { List < String > keyList = new ArrayList <> ( items . size ( ) ) ; for ( Map . Entry < String , Deque < MutablePair < DeltaType , Object > > > entry : items . entrySet ( ) ) { keyList . add ( entry . getKey ( ) ) ; } return keyList ; } finally { lock . readLock ( ) . unlock ( ) ; } }
|
List keys list .
| 113
| 4
|
152,716
|
@ Override public Object get ( Object obj ) { String key = this . keyOf ( obj ) ; return this . getByKey ( key ) ; }
|
Get object .
| 33
| 3
|
152,717
|
@ Override public List < Object > list ( ) { lock . readLock ( ) . lock ( ) ; List < Object > objects = new ArrayList <> ( ) ; try { // TODO: make a generic deep copy utility for ( Map . Entry < String , Deque < MutablePair < DeltaType , Object > > > entry : items . entrySet ( ) ) { Deque < MutablePair < DeltaType , Object > > copiedDeltas = new LinkedList <> ( entry . getValue ( ) ) ; objects . add ( copiedDeltas ) ; } } finally { lock . readLock ( ) . unlock ( ) ; } return objects ; }
|
List list .
| 146
| 3
|
152,718
|
public Deque < MutablePair < DeltaType , Object > > pop ( Consumer < Deque < MutablePair < DeltaType , Object > > > func ) throws InterruptedException { lock . writeLock ( ) . lock ( ) ; try { while ( true ) { while ( queue . isEmpty ( ) ) { notEmpty . await ( ) ; } // there should have data now String id = this . queue . removeFirst ( ) ; if ( this . initialPopulationCount > 0 ) { this . initialPopulationCount -- ; } if ( ! this . items . containsKey ( id ) ) { // Item may have been deleted subsequently. continue ; } Deque < MutablePair < DeltaType , Object > > deltas = this . items . get ( id ) ; this . items . remove ( id ) ; func . accept ( deltas ) ; // Don't make any copyDeltas here return deltas ; } } finally { lock . writeLock ( ) . unlock ( ) ; } }
|
Pop deltas .
| 216
| 5
|
152,719
|
private void queueActionLocked ( DeltaType actionType , Object obj ) { String id = this . keyOf ( obj ) ; // If object is supposed to be deleted (last event is Deleted), // then we should ignore Sync events, because it would result in // recreation of this object. if ( actionType == DeltaType . Sync && this . willObjectBeDeletedLocked ( id ) ) { return ; } Deque < MutablePair < DeltaType , Object > > deltas = items . get ( id ) ; if ( deltas == null ) { Deque < MutablePair < DeltaType , Object > > deltaList = new LinkedList <> ( ) ; deltaList . add ( new MutablePair ( actionType , obj ) ) ; deltas = new LinkedList <> ( deltaList ) ; } else { deltas . add ( new MutablePair < DeltaType , Object > ( actionType , obj ) ) ; } // TODO(yue9944882): Eliminate the force class casting here Deque < MutablePair < DeltaType , Object > > combinedDeltaList = combineDeltas ( ( LinkedList < MutablePair < DeltaType , Object > > ) deltas ) ; boolean exist = items . containsKey ( id ) ; if ( combinedDeltaList != null && combinedDeltaList . size ( ) > 0 ) { if ( ! exist ) { this . queue . add ( id ) ; } this . items . put ( id , new LinkedList <> ( combinedDeltaList ) ) ; notEmpty . signalAll ( ) ; } else { this . items . remove ( id ) ; } }
|
queueActionLocked appends to the delta list for the object . Caller must hold the lock .
| 361
| 20
|
152,720
|
private boolean willObjectBeDeletedLocked ( String id ) { if ( ! this . items . containsKey ( id ) ) { return false ; } Deque < MutablePair < DeltaType , Object > > deltas = this . items . get ( id ) ; return ! ( Collections . isEmptyCollection ( deltas ) ) && deltas . peekLast ( ) . getLeft ( ) . equals ( DeltaType . Deleted ) ; }
|
willObjectBeDeletedLocked returns true only if the last delta for the give object is Deleted . Caller must hold the lock .
| 98
| 28
|
152,721
|
private String keyOf ( Object obj ) { Object innerObj = obj ; if ( obj instanceof Deque ) { Deque < MutablePair < DeltaType , Object > > deltas = ( Deque < MutablePair < DeltaType , Object > > ) obj ; if ( deltas . size ( ) == 0 ) { throw new NoSuchElementException ( "0 length Deltas object; can't get key" ) ; } innerObj = deltas . peekLast ( ) . getRight ( ) ; } if ( innerObj instanceof DeletedFinalStateUnknown ) { return ( ( DeletedFinalStateUnknown ) innerObj ) . key ; } return keyFunc . apply ( ( ApiType ) innerObj ) ; }
|
DeletedFinalStateUnknown objects .
| 160
| 7
|
152,722
|
private void syncKeyLocked ( String key ) { ApiType obj = this . knownObjects . getByKey ( key ) ; if ( obj == null ) { return ; } String id = this . keyOf ( obj ) ; Deque < MutablePair < DeltaType , Object > > deltas = this . items . get ( id ) ; if ( deltas != null && ! ( Collections . isEmptyCollection ( deltas ) ) ) { return ; } this . queueActionLocked ( DeltaType . Sync , obj ) ; }
|
Add Sync delta . Caller must hold the lock .
| 119
| 10
|
152,723
|
private Deque < MutablePair < DeltaType , Object > > combineDeltas ( LinkedList < MutablePair < DeltaType , Object > > deltas ) { if ( deltas . size ( ) < 2 ) { return deltas ; } int size = deltas . size ( ) ; MutablePair < DeltaType , Object > d1 = deltas . peekLast ( ) ; MutablePair < DeltaType , Object > d2 = deltas . get ( size - 2 ) ; MutablePair < DeltaType , Object > out = isDuplicate ( d1 , d2 ) ; if ( out != null ) { Deque < MutablePair < DeltaType , Object > > newDeltas = new LinkedList <> ( ) ; newDeltas . addAll ( deltas . subList ( 0 , size - 2 ) ) ; newDeltas . add ( out ) ; return newDeltas ; } return deltas ; }
|
order . This will combine the most recent two deltas if they are the same .
| 221
| 18
|
152,724
|
private MutablePair < DeltaType , Object > isDuplicate ( MutablePair < DeltaType , Object > d1 , MutablePair < DeltaType , Object > d2 ) { MutablePair < DeltaType , Object > deletionDelta = isDeletionDup ( d1 , d2 ) ; if ( deletionDelta != null ) { return deletionDelta ; } return null ; }
|
If d1 & d2 represent the same event returns the delta that ought to be kept .
| 87
| 19
|
152,725
|
private MutablePair < DeltaType , Object > isDeletionDup ( MutablePair < DeltaType , Object > d1 , MutablePair < DeltaType , Object > d2 ) { if ( ! d1 . getLeft ( ) . equals ( DeltaType . Deleted ) || ! d2 . getLeft ( ) . equals ( DeltaType . Deleted ) ) { return null ; } Object obj = d2 . getRight ( ) ; if ( obj instanceof DeletedFinalStateUnknown ) { return d1 ; } return d2 ; }
|
keep the one with the most information if both are deletions .
| 121
| 13
|
152,726
|
public void run ( ) { try { log . info ( "{}#Start listing and watching..." , apiTypeClass ) ; ApiListType list = listerWatcher . list ( new CallGeneratorParams ( Boolean . FALSE , null , null ) ) ; V1ListMeta listMeta = Reflect . listMetadata ( list ) ; String resourceVersion = listMeta . getResourceVersion ( ) ; List < ApiType > items = Reflect . getItems ( list ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "{}#Extract resourceVersion {} list meta" , apiTypeClass , resourceVersion ) ; } this . syncWith ( items , resourceVersion ) ; this . lastSyncResourceVersion = resourceVersion ; if ( log . isDebugEnabled ( ) ) { log . debug ( "{}#Start watching with {}..." , apiTypeClass , lastSyncResourceVersion ) ; } while ( true ) { if ( ! isActive . get ( ) ) { if ( watch != null ) { watch . close ( ) ; return ; } } try { if ( log . isDebugEnabled ( ) ) { log . debug ( "{}#Start watch with resource version {}" , apiTypeClass , lastSyncResourceVersion ) ; } watch = listerWatcher . watch ( new CallGeneratorParams ( Boolean . TRUE , lastSyncResourceVersion , Long . valueOf ( Duration . ofMinutes ( 5 ) . toMillis ( ) ) . intValue ( ) ) ) ; watchHandler ( watch ) ; } catch ( Throwable t ) { log . info ( "{}#Watch connection get exception {}" , apiTypeClass , t . getMessage ( ) ) ; Throwable cause = t . getCause ( ) ; // If this is "connection refused" error, it means that most likely apiserver is not // responsive. // It doesn't make sense to re-list all objects because most likely we will be able to // restart // watch where we ended. // If that's the case wait and resend watch request. if ( cause != null && ( cause instanceof ConnectException ) ) { log . info ( "{}#Watch get connect exception, retry watch" , apiTypeClass ) ; Thread . sleep ( 1000L ) ; continue ; } if ( ( t instanceof RuntimeException ) && t . getMessage ( ) . contains ( "IO Exception during hasNext" ) ) { log . info ( "{}#Read timeout retry list and watch" , apiTypeClass ) ; return ; } log . error ( "{}#Watch failed as {} unexpected" , apiTypeClass , t . getMessage ( ) , t ) ; return ; } finally { if ( watch != null ) { watch . close ( ) ; watch = null ; } } } } catch ( Throwable t ) { log . error ( "{}#Failed to list-watch: {}" , apiTypeClass , t ) ; } }
|
run first lists all items and get the resource version at the moment of call and then use the resource version to watch .
| 621
| 24
|
152,727
|
public static ClientBuilder cluster ( ) throws IOException { final ClientBuilder builder = new ClientBuilder ( ) ; final String host = System . getenv ( ENV_SERVICE_HOST ) ; final String port = System . getenv ( ENV_SERVICE_PORT ) ; builder . setBasePath ( "https://" + host + ":" + port ) ; final String token = new String ( Files . readAllBytes ( Paths . get ( SERVICEACCOUNT_TOKEN_PATH ) ) , Charset . defaultCharset ( ) ) ; builder . setCertificateAuthority ( Files . readAllBytes ( Paths . get ( SERVICEACCOUNT_CA_PATH ) ) ) ; builder . setAuthentication ( new AccessTokenAuthentication ( token ) ) ; return builder ; }
|
Creates a builder which is pre - configured from the cluster configuration .
| 169
| 14
|
152,728
|
public static List < String > getAllNameSpaces ( ) throws ApiException { V1NamespaceList listNamespace = COREV1_API . listNamespace ( null , "true" , null , null , null , 0 , null , Integer . MAX_VALUE , Boolean . FALSE ) ; List < String > list = listNamespace . getItems ( ) . stream ( ) . map ( v1Namespace -> v1Namespace . getMetadata ( ) . getName ( ) ) . collect ( Collectors . toList ( ) ) ; return list ; }
|
Get all namespaces in k8s cluster
| 123
| 9
|
152,729
|
public static List < String > getPods ( ) throws ApiException { V1PodList v1podList = COREV1_API . listPodForAllNamespaces ( null , null , null , null , null , null , null , null , null ) ; List < String > podList = v1podList . getItems ( ) . stream ( ) . map ( v1Pod -> v1Pod . getMetadata ( ) . getName ( ) ) . collect ( Collectors . toList ( ) ) ; return podList ; }
|
List all pod names in all namespaces in k8s cluster
| 117
| 13
|
152,730
|
public static List < String > getNamespacedPod ( String namespace , String label ) throws ApiException { V1PodList listNamespacedPod = COREV1_API . listNamespacedPod ( namespace , null , null , null , null , label , Integer . MAX_VALUE , null , TIME_OUT_VALUE , Boolean . FALSE ) ; List < String > listPods = listNamespacedPod . getItems ( ) . stream ( ) . map ( v1pod -> v1pod . getMetadata ( ) . getName ( ) ) . collect ( Collectors . toList ( ) ) ; return listPods ; }
|
List pod in specific namespace with label
| 135
| 7
|
152,731
|
public static List < String > getServices ( ) throws ApiException { V1ServiceList listNamespacedService = COREV1_API . listNamespacedService ( DEFAULT_NAME_SPACE , null , null , null , null , null , Integer . MAX_VALUE , null , TIME_OUT_VALUE , Boolean . FALSE ) ; return listNamespacedService . getItems ( ) . stream ( ) . map ( v1service -> v1service . getMetadata ( ) . getName ( ) ) . collect ( Collectors . toList ( ) ) ; }
|
List all Services in default namespace
| 122
| 6
|
152,732
|
public static void printLog ( String namespace , String podName ) throws ApiException { // https://github.com/kubernetes-client/java/blob/master/kubernetes/docs/CoreV1Api.md#readNamespacedPodLog String readNamespacedPodLog = COREV1_API . readNamespacedPodLog ( podName , namespace , null , Boolean . FALSE , Integer . MAX_VALUE , null , Boolean . FALSE , Integer . MAX_VALUE , 40 , Boolean . FALSE ) ; System . out . println ( readNamespacedPodLog ) ; }
|
Print out the Log for specific Pods
| 129
| 8
|
152,733
|
public static KubeConfig loadKubeConfig ( Reader input ) { Yaml yaml = new Yaml ( new SafeConstructor ( ) ) ; Object config = yaml . load ( input ) ; Map < String , Object > configMap = ( Map < String , Object > ) config ; String currentContext = ( String ) configMap . get ( "current-context" ) ; ArrayList < Object > contexts = ( ArrayList < Object > ) configMap . get ( "contexts" ) ; ArrayList < Object > clusters = ( ArrayList < Object > ) configMap . get ( "clusters" ) ; ArrayList < Object > users = ( ArrayList < Object > ) configMap . get ( "users" ) ; Object preferences = configMap . get ( "preferences" ) ; KubeConfig kubeConfig = new KubeConfig ( contexts , clusters , users ) ; kubeConfig . setContext ( currentContext ) ; kubeConfig . setPreferences ( preferences ) ; return kubeConfig ; }
|
Load a Kubernetes config from a Reader
| 216
| 10
|
152,734
|
@ SuppressWarnings ( "unchecked" ) private String tokenViaExecCredential ( Map < String , Object > execMap ) { if ( execMap == null ) { return null ; } String apiVersion = ( String ) execMap . get ( "apiVersion" ) ; if ( ! "client.authentication.k8s.io/v1beta1" . equals ( apiVersion ) && ! "client.authentication.k8s.io/v1alpha1" . equals ( apiVersion ) ) { log . error ( "Unrecognized user.exec.apiVersion: {}" , apiVersion ) ; return null ; } String command = ( String ) execMap . get ( "command" ) ; JsonElement root = runExec ( command , ( List ) execMap . get ( "args" ) , ( List ) execMap . get ( "env" ) ) ; if ( root == null ) { return null ; } if ( ! "ExecCredential" . equals ( root . getAsJsonObject ( ) . get ( "kind" ) . getAsString ( ) ) ) { log . error ( "Unrecognized kind in response" ) ; return null ; } if ( ! apiVersion . equals ( root . getAsJsonObject ( ) . get ( "apiVersion" ) . getAsString ( ) ) ) { log . error ( "Mismatched apiVersion in response" ) ; return null ; } JsonObject status = root . getAsJsonObject ( ) . get ( "status" ) . getAsJsonObject ( ) ; JsonElement token = status . get ( "token" ) ; if ( token == null ) { // TODO handle clientCertificateData/clientKeyData // (KubeconfigAuthentication is not yet set up for that to be dynamic) log . warn ( "No token produced by {}" , command ) ; return null ; } log . debug ( "Obtained a token from {}" , command ) ; return token . getAsString ( ) ; // TODO cache tokens between calls, up to .status.expirationTimestamp // TODO a 401 is supposed to force a refresh, // but KubeconfigAuthentication hardcodes AccessTokenAuthentication which does not support that // and anyway ClientBuilder only calls Authenticator.provide once per ApiClient; // we would need to do it on every request }
|
Attempt to create an access token by running a configured external program .
| 516
| 13
|
152,735
|
private Call getNextCall ( Integer nextLimit , String continueToken ) { PagerParams params = new PagerParams ( ( nextLimit != null ) ? nextLimit : limit , continueToken ) ; return listFunc . apply ( params ) ; }
|
returns next list call by setting continue variable and limit
| 54
| 11
|
152,736
|
private ApiListType executeRequest ( Call call ) throws IOException , ApiException { return client . handleResponse ( call . execute ( ) , listType ) ; }
|
executes the list call and sets the continue variable for next list call
| 36
| 14
|
152,737
|
public PortForwardResult forward ( V1Pod pod , List < Integer > ports ) throws ApiException , IOException { return forward ( pod . getMetadata ( ) . getNamespace ( ) , pod . getMetadata ( ) . getName ( ) , ports ) ; }
|
PortForward to a container
| 59
| 5
|
152,738
|
public PortForwardResult forward ( String namespace , String name , List < Integer > ports ) throws ApiException , IOException { String path = makePath ( namespace , name ) ; WebSocketStreamHandler handler = new WebSocketStreamHandler ( ) ; PortForwardResult result = new PortForwardResult ( handler , ports ) ; List < Pair > queryParams = new ArrayList <> ( ) ; for ( Integer port : ports ) { queryParams . add ( new Pair ( "ports" , port . toString ( ) ) ) ; } WebSockets . stream ( path , "GET" , queryParams , apiClient , handler ) ; // Wait for streams to start. result . init ( ) ; return result ; }
|
PortForward to a container .
| 152
| 6
|
152,739
|
@ Override public void add ( ApiType obj ) { String key = keyFunc . apply ( obj ) ; lock . lock ( ) ; try { ApiType oldObj = this . items . get ( key ) ; this . items . put ( key , obj ) ; this . updateIndices ( oldObj , obj , key ) ; } finally { lock . unlock ( ) ; } }
|
Add objects .
| 84
| 3
|
152,740
|
@ Override public void delete ( ApiType obj ) { String key = keyFunc . apply ( obj ) ; lock . lock ( ) ; try { boolean exists = this . items . containsKey ( key ) ; if ( exists ) { this . deleteFromIndices ( this . items . get ( key ) , key ) ; this . items . remove ( key ) ; } } finally { lock . unlock ( ) ; } }
|
Delete the object .
| 91
| 4
|
152,741
|
@ Override public void replace ( List < ApiType > list , String resourceVersion ) { lock . lock ( ) ; try { Map < String , ApiType > newItems = new HashMap <> ( ) ; for ( ApiType item : list ) { String key = keyFunc . apply ( item ) ; newItems . put ( key , item ) ; } this . items = newItems ; // rebuild any index this . indices = new HashMap <> ( ) ; for ( Map . Entry < String , ApiType > itemEntry : items . entrySet ( ) ) { this . updateIndices ( null , itemEntry . getValue ( ) , itemEntry . getKey ( ) ) ; } } finally { lock . unlock ( ) ; } }
|
Replace the content in the cache completely .
| 163
| 9
|
152,742
|
@ Override public List < String > listKeys ( ) { lock . lock ( ) ; try { List < String > keys = new ArrayList <> ( this . items . size ( ) ) ; for ( Map . Entry < String , ApiType > entry : this . items . entrySet ( ) ) { keys . add ( entry . getKey ( ) ) ; } return keys ; } finally { lock . unlock ( ) ; } }
|
List keys .
| 93
| 3
|
152,743
|
@ Override public ApiType get ( ApiType obj ) { String key = this . keyFunc . apply ( obj ) ; lock . lock ( ) ; try { return this . getByKey ( key ) ; } finally { lock . unlock ( ) ; } }
|
Get object t .
| 58
| 4
|
152,744
|
@ Override public List < ApiType > list ( ) { lock . lock ( ) ; try { List < ApiType > itemList = new ArrayList <> ( this . items . size ( ) ) ; for ( Map . Entry < String , ApiType > entry : this . items . entrySet ( ) ) { itemList . add ( entry . getValue ( ) ) ; } return itemList ; } finally { lock . unlock ( ) ; } }
|
List all objects in the cache .
| 99
| 7
|
152,745
|
@ Override public List < ApiType > index ( String indexName , Object obj ) { lock . lock ( ) ; try { if ( ! this . indexers . containsKey ( indexName ) ) { throw new IllegalArgumentException ( String . format ( "index %s doesn't exist!" , indexName ) ) ; } Function < ApiType , List < String > > indexFunc = this . indexers . get ( indexName ) ; List < String > indexKeys = indexFunc . apply ( ( ApiType ) obj ) ; Map < String , Set < String > > index = this . indices . get ( indexName ) ; if ( io . kubernetes . client . util . common . Collections . isEmptyMap ( index ) ) { return new ArrayList <> ( ) ; } Set < String > returnKeySet = new HashSet <> ( ) ; for ( String indexKey : indexKeys ) { Set < String > set = index . get ( indexKey ) ; if ( io . kubernetes . client . util . common . Collections . isEmptyCollection ( set ) ) { continue ; } returnKeySet . addAll ( set ) ; } List < ApiType > items = new ArrayList <> ( returnKeySet . size ( ) ) ; for ( String absoluteKey : returnKeySet ) { items . add ( this . items . get ( absoluteKey ) ) ; } return items ; } finally { lock . unlock ( ) ; } }
|
Get objects .
| 316
| 3
|
152,746
|
@ Override public List < String > indexKeys ( String indexName , String indexKey ) { lock . lock ( ) ; try { if ( ! this . indexers . containsKey ( indexName ) ) { throw new IllegalArgumentException ( String . format ( "index %s doesn't exist!" , indexName ) ) ; } Map < String , Set < String > > index = this . indices . get ( indexName ) ; Set < String > set = index . get ( indexKey ) ; List < String > keys = new ArrayList <> ( set . size ( ) ) ; for ( String key : set ) { keys . add ( key ) ; } return keys ; } finally { lock . unlock ( ) ; } }
|
Index keys list .
| 154
| 4
|
152,747
|
@ Override public List < ApiType > byIndex ( String indexName , String indexKey ) { lock . lock ( ) ; try { if ( ! this . indexers . containsKey ( indexName ) ) { throw new IllegalArgumentException ( String . format ( "index %s doesn't exist!" , indexName ) ) ; } Map < String , Set < String > > index = this . indices . get ( indexName ) ; Set < String > set = index . get ( indexKey ) ; if ( set == null ) { return Arrays . asList ( ) ; } List < ApiType > items = new ArrayList <> ( set . size ( ) ) ; for ( String key : set ) { items . add ( this . items . get ( key ) ) ; } return items ; } finally { lock . unlock ( ) ; } }
|
By index list .
| 182
| 4
|
152,748
|
public void updateIndices ( ApiType oldObj , ApiType newObj , String key ) { // if we got an old object, we need to remove it before we can add // it again. if ( oldObj != null ) { deleteFromIndices ( oldObj , key ) ; } for ( Map . Entry < String , Function < ApiType , List < String > > > indexEntry : indexers . entrySet ( ) ) { String indexName = indexEntry . getKey ( ) ; Function < ApiType , List < String > > indexFunc = indexEntry . getValue ( ) ; List < String > indexValues = indexFunc . apply ( newObj ) ; if ( io . kubernetes . client . util . common . Collections . isEmptyCollection ( indexValues ) ) { continue ; } Map < String , Set < String > > index = this . indices . computeIfAbsent ( indexName , k -> new HashMap <> ( ) ) ; for ( String indexValue : indexValues ) { Set < String > indexSet = index . computeIfAbsent ( indexValue , k -> new HashSet <> ( ) ) ; indexSet . add ( key ) ; } } }
|
updateIndices modifies the objects location in the managed indexes if this is an update you must provide an oldObj .
| 259
| 24
|
152,749
|
private void deleteFromIndices ( ApiType oldObj , String key ) { for ( Map . Entry < String , Function < ApiType , List < String > > > indexEntry : this . indexers . entrySet ( ) ) { Function < ApiType , List < String > > indexFunc = indexEntry . getValue ( ) ; List < String > indexValues = indexFunc . apply ( oldObj ) ; if ( io . kubernetes . client . util . common . Collections . isEmptyCollection ( indexValues ) ) { continue ; } Map < String , Set < String > > index = this . indices . get ( indexEntry . getKey ( ) ) ; if ( index == null ) { continue ; } for ( String indexValue : indexValues ) { Set < String > indexSet = index . get ( indexValue ) ; if ( indexSet != null ) { indexSet . remove ( key ) ; } } } }
|
deleteFromIndices removes the object from each of the managed indexes .
| 201
| 14
|
152,750
|
public static < ApiType > String deletionHandlingMetaNamespaceKeyFunc ( ApiType object ) { if ( object instanceof DeltaFIFO . DeletedFinalStateUnknown ) { DeltaFIFO . DeletedFinalStateUnknown deleteObj = ( DeltaFIFO . DeletedFinalStateUnknown ) object ; return deleteObj . getKey ( ) ; } return metaNamespaceKeyFunc ( object ) ; }
|
deletionHandlingMetaNamespaceKeyFunc checks for DeletedFinalStateUnknown objects before calling metaNamespaceKeyFunc .
| 90
| 28
|
152,751
|
public static List < String > metaNamespaceIndexFunc ( Object obj ) { try { V1ObjectMeta metadata = Reflect . objectMetadata ( obj ) ; if ( metadata == null ) { return Collections . emptyList ( ) ; } return Collections . singletonList ( metadata . getNamespace ( ) ) ; } catch ( ObjectMetaReflectException e ) { // NOTE(yue9944882): might want to handle this as a checked exception throw new RuntimeException ( e ) ; } }
|
metaNamespaceIndexFunc is a default index function that indexes based on an object s namespace .
| 105
| 20
|
152,752
|
public < T extends Message > ObjectOrStatus < T > list ( T . Builder builder , String path ) throws ApiException , IOException { return get ( builder , path ) ; }
|
List is fluent semantic sugar method on top of get which is intended to convey that the object is a List of objects rather than a single object
| 39
| 28
|
152,753
|
public < T extends Message > ObjectOrStatus < T > create ( T obj , String path , String apiVersion , String kind ) throws ApiException , IOException { return request ( obj . newBuilderForType ( ) , path , "POST" , obj , apiVersion , kind ) ; }
|
Create a Kubernetes API object using protocol buffer encoding . Performs a POST
| 62
| 17
|
152,754
|
public < T extends Message > ObjectOrStatus < T > request ( T . Builder builder , String path , String method , T body , String apiVersion , String kind ) throws ApiException , IOException { HashMap < String , String > headers = new HashMap <> ( ) ; headers . put ( "Content-Type" , MEDIA_TYPE ) ; headers . put ( "Accept" , MEDIA_TYPE ) ; String [ ] localVarAuthNames = new String [ ] { "BearerToken" } ; Request request = apiClient . buildRequest ( path , method , new ArrayList < Pair > ( ) , new ArrayList < Pair > ( ) , null , headers , new HashMap < String , Object > ( ) , localVarAuthNames , null ) ; if ( body != null ) { byte [ ] bytes = encode ( body , apiVersion , kind ) ; switch ( method ) { case "POST" : request = request . newBuilder ( ) . post ( RequestBody . create ( MediaType . parse ( MEDIA_TYPE ) , bytes ) ) . build ( ) ; break ; case "PUT" : request = request . newBuilder ( ) . put ( RequestBody . create ( MediaType . parse ( MEDIA_TYPE ) , bytes ) ) . build ( ) ; break ; case "PATCH" : request = request . newBuilder ( ) . patch ( RequestBody . create ( MediaType . parse ( MEDIA_TYPE ) , bytes ) ) . build ( ) ; break ; default : throw new ApiException ( "Unknown proto client API method: " + method ) ; } } Response resp = apiClient . getHttpClient ( ) . newCall ( request ) . execute ( ) ; Unknown u = parse ( resp . body ( ) . byteStream ( ) ) ; resp . body ( ) . close ( ) ; if ( u . getTypeMeta ( ) . getApiVersion ( ) . equals ( "v1" ) && u . getTypeMeta ( ) . getKind ( ) . equals ( "Status" ) ) { Status status = Status . newBuilder ( ) . mergeFrom ( u . getRaw ( ) ) . build ( ) ; return new ObjectOrStatus ( null , status ) ; } return new ObjectOrStatus ( ( T ) builder . mergeFrom ( u . getRaw ( ) ) . build ( ) , null ) ; }
|
Generic protocol buffer based HTTP request . Not intended for general consumption but public for advance use cases .
| 502
| 19
|
152,755
|
public static void stream ( String path , String method , ApiClient client , SocketListener listener ) throws ApiException , IOException { stream ( path , method , new ArrayList < Pair > ( ) , client , listener ) ; }
|
Create a new WebSocket stream
| 49
| 6
|
152,756
|
public synchronized InputStream getInputStream ( int stream ) { if ( state == State . CLOSED ) throw new IllegalStateException ( ) ; if ( ! input . containsKey ( stream ) ) { try { PipedInputStream pipeIn = new PipedInputStream ( ) ; PipedOutputStream pipeOut = new PipedOutputStream ( pipeIn ) ; pipedOutput . put ( stream , pipeOut ) ; input . put ( stream , pipeIn ) ; } catch ( IOException ex ) { // This is _very_ unlikely, as it requires the above constructor to fail. // don't force callers to catch, but still throw throw new IllegalStateException ( ex ) ; } } return input . get ( stream ) ; }
|
Get a specific input stream using its identifier . Caller is responsible for closing these streams .
| 154
| 17
|
152,757
|
public synchronized OutputStream getOutputStream ( int stream ) { if ( ! output . containsKey ( stream ) ) { output . put ( stream , new WebSocketOutputStream ( stream ) ) ; } return output . get ( stream ) ; }
|
Gets a specific output stream using it s identified
| 50
| 10
|
152,758
|
private synchronized OutputStream getSocketInputOutputStream ( int stream ) { if ( ! pipedOutput . containsKey ( stream ) ) { try { PipedInputStream pipeIn = new PipedInputStream ( ) ; PipedOutputStream pipeOut = new PipedOutputStream ( pipeIn ) ; pipedOutput . put ( stream , pipeOut ) ; input . put ( stream , pipeIn ) ; } catch ( IOException ex ) { // This is _very_ unlikely, as it requires the above constructor to fail. // don't force callers to catch, but still throw throw new IllegalStateException ( ex ) ; } } return pipedOutput . get ( stream ) ; }
|
Get the pipe to write data to a specific InputStream . This is called when new data is read from the web socket to send the data on to the right stream .
| 143
| 34
|
152,759
|
@ Override public void addEventHandlerWithResyncPeriod ( ResourceEventHandler < ApiType > handler , long resyncPeriodMillis ) { if ( stopped ) { log . info ( "DefaultSharedIndexInformer#Handler was not added to shared informer because it has stopped already" ) ; return ; } if ( resyncPeriodMillis > 0 ) { if ( resyncPeriodMillis < MINIMUM_RESYNC_PERIOD_MILLIS ) { log . warn ( "DefaultSharedIndexInformer#resyncPeriod {} is too small. Changing it to the minimum allowed rule of {}" , resyncPeriodMillis , MINIMUM_RESYNC_PERIOD_MILLIS ) ; resyncPeriodMillis = MINIMUM_RESYNC_PERIOD_MILLIS ; } if ( resyncPeriodMillis < this . resyncCheckPeriodMillis ) { if ( started ) { log . warn ( "DefaultSharedIndexInformer#resyncPeriod {} is smaller than resyncCheckPeriod {} and the informer has already started. Changing it to {}" , resyncPeriodMillis , resyncCheckPeriodMillis ) ; resyncPeriodMillis = resyncCheckPeriodMillis ; } else { // if the event handler's resyncPeriod is smaller than the current resyncCheckPeriod, // update resyncCheckPeriod to match resyncPeriod and adjust the resync periods of all // the listeners accordingly this . resyncCheckPeriodMillis = resyncPeriodMillis ; } } } ProcessorListener < ApiType > listener = new ProcessorListener ( handler , determineResyncPeriod ( resyncCheckPeriodMillis , this . resyncCheckPeriodMillis ) ) ; if ( ! started ) { this . processor . addListener ( listener ) ; return ; } this . processor . addAndStartListener ( listener ) ; List < ApiType > objectList = this . indexer . list ( ) ; for ( Object item : objectList ) { listener . add ( new ProcessorListener . AddNotification ( item ) ) ; } }
|
add event callback with a resync period
| 469
| 8
|
152,760
|
private void handleDeltas ( Deque < MutablePair < DeltaFIFO . DeltaType , Object > > deltas ) { if ( Collections . isEmptyCollection ( deltas ) ) { return ; } // from oldest to newest for ( MutablePair < DeltaFIFO . DeltaType , Object > delta : deltas ) { DeltaFIFO . DeltaType deltaType = delta . getLeft ( ) ; switch ( deltaType ) { case Sync : case Added : case Updated : boolean isSync = deltaType == DeltaFIFO . DeltaType . Sync ; Object oldObj = this . indexer . get ( ( ApiType ) delta . getRight ( ) ) ; if ( oldObj != null ) { this . indexer . update ( ( ApiType ) delta . getRight ( ) ) ; this . processor . distribute ( new ProcessorListener . UpdateNotification ( oldObj , delta . getRight ( ) ) , isSync ) ; } else { this . indexer . add ( ( ApiType ) delta . getRight ( ) ) ; this . processor . distribute ( new ProcessorListener . AddNotification ( delta . getRight ( ) ) , isSync ) ; } break ; case Deleted : this . indexer . delete ( ( ApiType ) delta . getRight ( ) ) ; this . processor . distribute ( new ProcessorListener . DeleteNotification ( delta . getRight ( ) ) , false ) ; break ; } } }
|
handleDeltas handles deltas and call processor distribute .
| 313
| 13
|
152,761
|
public static < T > T loadAs ( String content , Class < T > clazz ) { return getSnakeYaml ( ) . loadAs ( new StringReader ( content ) , clazz ) ; }
|
Load an API object from a YAML string representation . Returns a concrete typed object using the type specified .
| 43
| 22
|
152,762
|
public static < T > T loadAs ( File f , Class < T > clazz ) throws IOException { return getSnakeYaml ( ) . loadAs ( new FileReader ( f ) , clazz ) ; }
|
Load an API object from a YAML file . Returns a concrete typed object using the type specified .
| 46
| 21
|
152,763
|
public static < T > T loadAs ( Reader reader , Class < T > clazz ) { return getSnakeYaml ( ) . loadAs ( reader , clazz ) ; }
|
Load an API object from a YAML stream . Returns a concrete typed object using the type specified .
| 38
| 21
|
152,764
|
public static void dumpAll ( Iterator < ? extends Object > data , Writer output ) { getSnakeYaml ( ) . dumpAll ( data , output ) ; }
|
Takes an Iterator of YAML API objects and writes a YAML String representing all of them .
| 35
| 23
|
152,765
|
public synchronized < ApiType , ApiListType > SharedIndexInformer < ApiType > sharedIndexInformerFor ( Function < CallGeneratorParams , Call > callGenerator , Class < ApiType > apiTypeClass , Class < ApiListType > apiListTypeClass ) { return sharedIndexInformerFor ( callGenerator , apiTypeClass , apiListTypeClass , 0 ) ; }
|
Shared index informer for shared index informer .
| 88
| 11
|
152,766
|
public synchronized void startAllRegisteredInformers ( ) { if ( Collections . isEmptyMap ( informers ) ) { return ; } informers . forEach ( ( informerType , informer ) -> { if ( ! startedInformers . containsKey ( informerType ) ) { startedInformers . put ( informerType , informerExecutor . submit ( informer :: run ) ) ; } } ) ; }
|
Start all registered informers .
| 91
| 6
|
152,767
|
public synchronized void stopAllRegisteredInformers ( ) { if ( Collections . isEmptyMap ( informers ) ) { return ; } informers . forEach ( ( informerType , informer ) -> { if ( startedInformers . containsKey ( informerType ) ) { startedInformers . remove ( informerType ) ; informer . stop ( ) ; } } ) ; informerExecutor . shutdown ( ) ; }
|
Stop all registered informers .
| 93
| 6
|
152,768
|
public void setSwipeItemMenuEnabled ( int position , boolean enabled ) { if ( enabled ) { if ( mDisableSwipeItemMenuList . contains ( position ) ) { mDisableSwipeItemMenuList . remove ( Integer . valueOf ( position ) ) ; } } else { if ( ! mDisableSwipeItemMenuList . contains ( position ) ) { mDisableSwipeItemMenuList . add ( position ) ; } } }
|
Set the item menu to enable status .
| 93
| 8
|
152,769
|
public void addHeaderView ( View view ) { mHeaderViewList . add ( view ) ; if ( mAdapterWrapper != null ) { mAdapterWrapper . addHeaderViewAndNotify ( view ) ; } }
|
Add view at the headers .
| 47
| 6
|
152,770
|
public void removeHeaderView ( View view ) { mHeaderViewList . remove ( view ) ; if ( mAdapterWrapper != null ) { mAdapterWrapper . removeHeaderViewAndNotify ( view ) ; } }
|
Remove view from header .
| 47
| 5
|
152,771
|
public void addFooterView ( View view ) { mFooterViewList . add ( view ) ; if ( mAdapterWrapper != null ) { mAdapterWrapper . addFooterViewAndNotify ( view ) ; } }
|
Add view at the footer .
| 50
| 7
|
152,772
|
public final void expandParent ( int parentPosition ) { if ( ! isExpanded ( parentPosition ) ) { mExpandItemArray . append ( parentPosition , true ) ; int position = positionFromParentPosition ( parentPosition ) ; int childCount = childItemCount ( parentPosition ) ; notifyItemRangeInserted ( position + 1 , childCount ) ; } }
|
Expand parent .
| 77
| 4
|
152,773
|
public final void collapseParent ( int parentPosition ) { if ( isExpanded ( parentPosition ) ) { mExpandItemArray . append ( parentPosition , false ) ; int position = positionFromParentPosition ( parentPosition ) ; int childCount = childItemCount ( parentPosition ) ; notifyItemRangeRemoved ( position + 1 , childCount ) ; } }
|
Collapse parent .
| 75
| 4
|
152,774
|
public final boolean isParentItem ( int adapterPosition ) { int itemCount = 0 ; int parentCount = parentItemCount ( ) ; for ( int i = 0 ; i < parentCount ; i ++ ) { if ( itemCount == adapterPosition ) { return true ; } itemCount += 1 ; if ( isExpanded ( i ) ) { itemCount += childItemCount ( i ) ; } else { // itemCount += 1; } } return false ; }
|
Item is a parent item .
| 97
| 6
|
152,775
|
public final int parentItemPosition ( int adapterPosition ) { int itemCount = 0 ; for ( int i = 0 ; i < parentItemCount ( ) ; i ++ ) { itemCount += 1 ; if ( isExpanded ( i ) ) { int childCount = childItemCount ( i ) ; itemCount += childCount ; } if ( adapterPosition < itemCount ) { return i ; } } throw new IllegalStateException ( "The adapter position is not a parent type: " + adapterPosition ) ; }
|
Get the position of the parent item from the adapter position .
| 107
| 12
|
152,776
|
public final int childItemPosition ( int childAdapterPosition ) { int itemCount = 0 ; int parentCount = parentItemCount ( ) ; for ( int i = 0 ; i < parentCount ; i ++ ) { itemCount += 1 ; if ( isExpanded ( i ) ) { int childCount = childItemCount ( i ) ; itemCount += childCount ; if ( childAdapterPosition < itemCount ) { return childCount - ( itemCount - childAdapterPosition ) ; } } else { // itemCount += 1; } } throw new IllegalStateException ( "The adapter position is invalid: " + childAdapterPosition ) ; }
|
Get the position of the child item from the adapter position .
| 133
| 12
|
152,777
|
public void drawLeft ( View view , Canvas c ) { int left = view . getLeft ( ) - mWidth ; int top = view . getTop ( ) - mHeight ; int right = left + mWidth ; int bottom = view . getBottom ( ) + mHeight ; mDivider . setBounds ( left , top , right , bottom ) ; mDivider . draw ( c ) ; }
|
Draw the divider on the left side of the Item .
| 87
| 12
|
152,778
|
private int getSwipeDuration ( MotionEvent ev , int velocity ) { int sx = getScrollX ( ) ; int dx = ( int ) ( ev . getX ( ) - sx ) ; final int width = mSwipeCurrentHorizontal . getMenuWidth ( ) ; final int halfWidth = width / 2 ; final float distanceRatio = Math . min ( 1f , 1.0f * Math . abs ( dx ) / width ) ; final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration ( distanceRatio ) ; int duration ; if ( velocity > 0 ) { duration = 4 * Math . round ( 1000 * Math . abs ( distance / velocity ) ) ; } else { final float pageDelta = ( float ) Math . abs ( dx ) / width ; duration = ( int ) ( ( pageDelta + 1 ) * 100 ) ; } duration = Math . min ( duration , mScrollerDuration ) ; return duration ; }
|
compute finish duration .
| 204
| 5
|
152,779
|
protected MapTileModuleProviderBase findNextAppropriateProvider ( final MapTileRequestState aState ) { MapTileModuleProviderBase provider ; boolean providerDoesntExist = false , providerCantGetDataConnection = false , providerCantServiceZoomlevel = false ; // The logic of the while statement is // "Keep looping until you get null, or a provider that still exists // and has a data connection if it needs one and can service the zoom level," do { provider = aState . getNextProvider ( ) ; // Perform some checks to see if we can use this provider // If any of these are true, then that disqualifies the provider for this tile request. if ( provider != null ) { providerDoesntExist = ! this . getProviderExists ( provider ) ; providerCantGetDataConnection = ! useDataConnection ( ) && provider . getUsesDataConnection ( ) ; int zoomLevel = MapTileIndex . getZoom ( aState . getMapTile ( ) ) ; providerCantServiceZoomlevel = zoomLevel > provider . getMaximumZoomLevel ( ) || zoomLevel < provider . getMinimumZoomLevel ( ) ; } } while ( ( provider != null ) && ( providerDoesntExist || providerCantGetDataConnection || providerCantServiceZoomlevel ) ) ; return provider ; }
|
We want to not use a provider that doesn t exist anymore in the chain and we want to not use a provider that requires a data connection when one is not available .
| 284
| 34
|
152,780
|
private void reloadMarker ( BoundingBox latLonArea , double zoom ) { Log . d ( TAG , "reloadMarker " + latLonArea + ", zoom " + zoom ) ; this . mCurrentBackgroundMarkerLoaderTask = new BackgroundMarkerLoaderTask ( ) ; this . mCurrentBackgroundMarkerLoaderTask . execute ( latLonArea . getLatSouth ( ) , latLonArea . getLatNorth ( ) , latLonArea . getLonEast ( ) , latLonArea . getLonWest ( ) , zoom ) ; }
|
called by MapView if zoom or scroll has changed to reload marker for new visible region
| 124
| 17
|
152,781
|
private long next ( ) { while ( true ) { final long index ; synchronized ( mTileAreas ) { if ( ! mTileIndices . hasNext ( ) ) { return - 1 ; } index = mTileIndices . next ( ) ; } final Drawable drawable = mCache . getMapTile ( index ) ; if ( drawable == null ) { return index ; } } }
|
Get the next tile to search for
| 84
| 7
|
152,782
|
private void search ( final long pMapTileIndex ) { for ( final MapTileModuleProviderBase provider : mProviders ) { try { if ( provider instanceof MapTileDownloader ) { final ITileSource tileSource = ( ( MapTileDownloader ) provider ) . getTileSource ( ) ; if ( tileSource instanceof OnlineTileSourceBase ) { if ( ! ( ( OnlineTileSourceBase ) tileSource ) . getTileSourcePolicy ( ) . acceptsPreventive ( ) ) { continue ; } } } final Drawable drawable = provider . getTileLoader ( ) . loadTile ( pMapTileIndex ) ; if ( drawable == null ) { continue ; } mCache . putTile ( pMapTileIndex , drawable ) ; return ; } catch ( CantContinueException exception ) { // just dismiss that lazily: we don't need to be severe here } } }
|
Search for a tile bitmap into the list of providers and put it in the memory cache
| 187
| 18
|
152,783
|
private void promptForFiles ( ) { DialogProperties properties = new DialogProperties ( ) ; properties . selection_mode = DialogConfigs . MULTI_MODE ; properties . selection_type = DialogConfigs . FILE_SELECT ; properties . root = new File ( DialogConfigs . DEFAULT_DIR ) ; properties . error_dir = new File ( DialogConfigs . DEFAULT_DIR ) ; properties . offset = new File ( DialogConfigs . DEFAULT_DIR ) ; Set < String > registeredExtensions = ArchiveFileFactory . getRegisteredExtensions ( ) ; //api check if ( Build . VERSION . SDK_INT >= 14 ) registeredExtensions . add ( "gpkg" ) ; registeredExtensions . add ( "map" ) ; String [ ] ret = new String [ registeredExtensions . size ( ) ] ; ret = registeredExtensions . toArray ( ret ) ; properties . extensions = ret ; FilePickerDialog dialog = new FilePickerDialog ( getContext ( ) , properties ) ; dialog . setTitle ( "Select a File" ) ; dialog . setDialogSelectionListener ( new DialogSelectionListener ( ) { @ Override public void onSelectedFilePaths ( String [ ] files ) { //files is the array of the paths of files selected by the Application User. setProviderConfig ( files ) ; } } ) ; dialog . show ( ) ; }
|
step 1 users selects files
| 304
| 5
|
152,784
|
private void promptForTileSource ( ) { AlertDialog . Builder builderSingle = new AlertDialog . Builder ( getContext ( ) ) ; builderSingle . setIcon ( R . drawable . icon ) ; builderSingle . setTitle ( "Select Offline Tile source:-" ) ; final ArrayAdapter < ITileSource > arrayAdapter = new ArrayAdapter < ITileSource > ( getContext ( ) , android . R . layout . select_dialog_singlechoice ) ; arrayAdapter . addAll ( tileSources ) ; builderSingle . setNegativeButton ( "cancel" , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { dialog . dismiss ( ) ; } } ) ; builderSingle . setAdapter ( arrayAdapter , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { final ITileSource strName = arrayAdapter . getItem ( which ) ; AlertDialog . Builder builderInner = new AlertDialog . Builder ( getContext ( ) ) ; builderInner . setMessage ( strName . name ( ) ) ; builderInner . setTitle ( "Your Selected Item is" ) ; builderInner . setPositiveButton ( "Ok" , new DialogInterface . OnClickListener ( ) { @ Override public void onClick ( DialogInterface dialog , int which ) { mMapView . setTileSource ( strName ) ; //new XYTileSource(strName, 0, 22, 256, "png", new String[0])); //on tile sources that are supported, center the map an area that's within bounds if ( strName instanceof MapsForgeTileSource ) { final MapsForgeTileSource src = ( MapsForgeTileSource ) strName ; mMapView . post ( new Runnable ( ) { @ Override public void run ( ) { mMapView . getController ( ) . setZoom ( src . getMinimumZoomLevel ( ) ) ; mMapView . setMinZoomLevel ( ( double ) src . getMinimumZoomLevel ( ) ) ; mMapView . setMaxZoomLevel ( ( double ) src . getMaximumZoomLevel ( ) ) ; mMapView . invalidate ( ) ; mMapView . zoomToBoundingBox ( src . getBoundsOsmdroid ( ) , true ) ; } } ) ; } else if ( strName instanceof GeopackageRasterTileSource ) { final GeopackageRasterTileSource src = ( GeopackageRasterTileSource ) strName ; mMapView . post ( new Runnable ( ) { @ Override public void run ( ) { mMapView . getController ( ) . setZoom ( src . getMinimumZoomLevel ( ) ) ; mMapView . setMinZoomLevel ( ( double ) src . getMinimumZoomLevel ( ) ) ; mMapView . setMaxZoomLevel ( ( double ) src . getMaximumZoomLevel ( ) ) ; mMapView . invalidate ( ) ; mMapView . zoomToBoundingBox ( src . getBounds ( ) , true ) ; } } ) ; } dialog . dismiss ( ) ; } } ) ; builderInner . show ( ) ; } } ) ; builderSingle . show ( ) ; }
|
step 3 ask for the tile source
| 716
| 7
|
152,785
|
public synchronized Drawable renderTile ( final long pMapTileIndex ) { Tile tile = new Tile ( MapTileIndex . getX ( pMapTileIndex ) , MapTileIndex . getY ( pMapTileIndex ) , ( byte ) MapTileIndex . getZoom ( pMapTileIndex ) , 256 ) ; model . setFixedTileSize ( 256 ) ; //You could try something like this to load a custom theme //try{ // jobTheme = new ExternalRenderTheme(themeFile); //} //catch(Exception e){ // jobTheme = InternalRenderTheme.OSMARENDER; //} if ( mapDatabase == null ) return null ; try { //Draw the tile RendererJob mapGeneratorJob = new RendererJob ( tile , mapDatabase , theme , model , scale , false , false ) ; AndroidTileBitmap bmp = ( AndroidTileBitmap ) renderer . executeJob ( mapGeneratorJob ) ; if ( bmp != null ) return new BitmapDrawable ( AndroidGraphicFactory . getBitmap ( bmp ) ) ; } catch ( Exception ex ) { Log . d ( IMapView . LOGTAG , "###################### Mapsforge tile generation failed" , ex ) ; } //Make the bad tile easy to spot Bitmap bitmap = Bitmap . createBitmap ( TILE_SIZE_PIXELS , TILE_SIZE_PIXELS , Bitmap . Config . RGB_565 ) ; bitmap . eraseColor ( Color . YELLOW ) ; return new BitmapDrawable ( bitmap ) ; }
|
The synchronized here is VERY important . If missing the mapDatabase read gets corrupted by multiple threads reading the file at once .
| 331
| 24
|
152,786
|
public GeoPoint destinationPoint ( final double aDistanceInMeters , final double aBearingInDegrees ) { // convert distance to angular distance final double dist = aDistanceInMeters / RADIUS_EARTH_METERS ; // convert bearing to radians final double brng = DEG2RAD * aBearingInDegrees ; // get current location in radians final double lat1 = DEG2RAD * getLatitude ( ) ; final double lon1 = DEG2RAD * getLongitude ( ) ; final double lat2 = Math . asin ( Math . sin ( lat1 ) * Math . cos ( dist ) + Math . cos ( lat1 ) * Math . sin ( dist ) * Math . cos ( brng ) ) ; final double lon2 = lon1 + Math . atan2 ( Math . sin ( brng ) * Math . sin ( dist ) * Math . cos ( lat1 ) , Math . cos ( dist ) - Math . sin ( lat1 ) * Math . sin ( lat2 ) ) ; final double lat2deg = lat2 / DEG2RAD ; final double lon2deg = lon2 / DEG2RAD ; return new GeoPoint ( lat2deg , lon2deg ) ; }
|
Calculate a point that is the specified distance and bearing away from this point .
| 278
| 17
|
152,787
|
public static double getSquaredDistanceToPoint ( final double pFromX , final double pFromY , final double pToX , final double pToY ) { final double dX = pFromX - pToX ; final double dY = pFromY - pToY ; return dX * dX + dY * dY ; }
|
Square of the distance between two points
| 75
| 7
|
152,788
|
public static double getSquaredDistanceToLine ( final double pFromX , final double pFromY , final double pAX , final double pAY , final double pBX , final double pBY ) { return getSquaredDistanceToProjection ( pFromX , pFromY , pAX , pAY , pBX , pBY , getProjectionFactorToLine ( pFromX , pFromY , pAX , pAY , pBX , pBY ) ) ; }
|
Square of the distance between a point and line AB
| 105
| 10
|
152,789
|
public static double getSquaredDistanceToSegment ( final double pFromX , final double pFromY , final double pAX , final double pAY , final double pBX , final double pBY ) { return getSquaredDistanceToProjection ( pFromX , pFromY , pAX , pAY , pBX , pBY , getProjectionFactorToSegment ( pFromX , pFromY , pAX , pAY , pBX , pBY ) ) ; }
|
Square of the distance between a point and segment AB
| 107
| 10
|
152,790
|
private static double dotProduct ( final double pAX , final double pAY , final double pBX , final double pBY , final double pCX , final double pCY ) { return ( pBX - pAX ) * ( pCX - pAX ) + ( pBY - pAY ) * ( pCY - pAY ) ; }
|
Compute the dot product AB x AC
| 77
| 8
|
152,791
|
private void debugProjection ( ) { new Thread ( ) { @ Override public void run ( ) { // let the map get redrawn and a new projection calculated try { sleep ( 1000 ) ; } catch ( InterruptedException ignore ) { } // then get the projection runOnUiThread ( new Runnable ( ) { @ Override public void run ( ) { final IProjection projection = mMap . getProjection ( ) ; final IGeoPoint northEast = projection . getNorthEast ( ) ; final IGeoPoint southWest = projection . getSouthWest ( ) ; final IProjection breakpoint = projection ; } } ) ; } } . start ( ) ; }
|
This is just used for debugging
| 146
| 6
|
152,792
|
private static void run ( final String pServerURL , final String pDestinationFile , final String pTempFolder , final int pThreadCount , final String pFileAppendix , final int pMinZoom , final int pMaxZoom , final double pNorth , final double pSouth , final double pEast , final double pWest ) { new File ( pTempFolder ) . mkdirs ( ) ; System . out . println ( "---------------------------" ) ; runFileExpecterWithAbort ( pMinZoom , pMaxZoom , pNorth , pSouth , pEast , pWest ) ; execute ( pServerURL , pDestinationFile , pTempFolder , pThreadCount , pFileAppendix , pMinZoom , pMaxZoom , pNorth , pSouth , pEast , pWest , null ) ; if ( pServerURL != null ) { runCleanup ( pTempFolder , true ) ; } }
|
this starts executing the download and packaging
| 201
| 7
|
152,793
|
public void disableCompass ( ) { mIsCompassEnabled = false ; if ( mOrientationProvider != null ) { mOrientationProvider . stopOrientationProvider ( ) ; } // Reset values mAzimuth = Float . NaN ; // Update the screen to see changes take effect if ( mMapView != null ) { this . invalidateCompass ( ) ; } }
|
Disable orientation updates .
| 84
| 4
|
152,794
|
private void createCompassRosePicture ( ) { // Paint design of north triangle (it's common to paint north in red color) final Paint northPaint = new Paint ( ) ; northPaint . setColor ( 0xFFA00000 ) ; northPaint . setAntiAlias ( true ) ; northPaint . setStyle ( Style . FILL ) ; northPaint . setAlpha ( 220 ) ; // Paint design of south triangle (black) final Paint southPaint = new Paint ( ) ; southPaint . setColor ( Color . BLACK ) ; southPaint . setAntiAlias ( true ) ; southPaint . setStyle ( Style . FILL ) ; southPaint . setAlpha ( 220 ) ; // Create a little white dot in the middle of the compass rose final Paint centerPaint = new Paint ( ) ; centerPaint . setColor ( Color . WHITE ) ; centerPaint . setAntiAlias ( true ) ; centerPaint . setStyle ( Style . FILL ) ; centerPaint . setAlpha ( 220 ) ; final int picBorderWidthAndHeight = ( int ) ( ( mCompassRadius + 5 ) * 2 * mScale ) ; final int center = picBorderWidthAndHeight / 2 ; if ( mCompassRoseBitmap != null ) mCompassRoseBitmap . recycle ( ) ; mCompassRoseBitmap = Bitmap . createBitmap ( picBorderWidthAndHeight , picBorderWidthAndHeight , Config . ARGB_8888 ) ; final Canvas canvas = new Canvas ( mCompassRoseBitmap ) ; // Triangle pointing north final Path pathNorth = new Path ( ) ; pathNorth . moveTo ( center , center - ( mCompassRadius - 3 ) * mScale ) ; pathNorth . lineTo ( center + 4 * mScale , center ) ; pathNorth . lineTo ( center - 4 * mScale , center ) ; pathNorth . lineTo ( center , center - ( mCompassRadius - 3 ) * mScale ) ; pathNorth . close ( ) ; canvas . drawPath ( pathNorth , northPaint ) ; // Triangle pointing south final Path pathSouth = new Path ( ) ; pathSouth . moveTo ( center , center + ( mCompassRadius - 3 ) * mScale ) ; pathSouth . lineTo ( center + 4 * mScale , center ) ; pathSouth . lineTo ( center - 4 * mScale , center ) ; pathSouth . lineTo ( center , center + ( mCompassRadius - 3 ) * mScale ) ; pathSouth . close ( ) ; canvas . drawPath ( pathSouth , southPaint ) ; // Draw a little white dot in the middle canvas . drawCircle ( center , center , 2 , centerPaint ) ; }
|
A conventional red and black compass needle .
| 591
| 8
|
152,795
|
private void createPointerPicture ( ) { final Paint arrowPaint = new Paint ( ) ; arrowPaint . setColor ( Color . BLACK ) ; arrowPaint . setAntiAlias ( true ) ; arrowPaint . setStyle ( Style . FILL ) ; arrowPaint . setAlpha ( 220 ) ; // Create a little white dot in the middle of the compass rose final Paint centerPaint = new Paint ( ) ; centerPaint . setColor ( Color . WHITE ) ; centerPaint . setAntiAlias ( true ) ; centerPaint . setStyle ( Style . FILL ) ; centerPaint . setAlpha ( 220 ) ; final int picBorderWidthAndHeight = ( int ) ( ( mCompassRadius + 5 ) * 2 * mScale ) ; final int center = picBorderWidthAndHeight / 2 ; if ( mCompassRoseBitmap != null ) mCompassRoseBitmap . recycle ( ) ; mCompassRoseBitmap = Bitmap . createBitmap ( picBorderWidthAndHeight , picBorderWidthAndHeight , Config . ARGB_8888 ) ; final Canvas canvas = new Canvas ( mCompassRoseBitmap ) ; // Arrow comprised of 2 triangles final Path pathArrow = new Path ( ) ; pathArrow . moveTo ( center , center - ( mCompassRadius - 3 ) * mScale ) ; pathArrow . lineTo ( center + 4 * mScale , center + ( mCompassRadius - 3 ) * mScale ) ; pathArrow . lineTo ( center , center + 0.5f * ( mCompassRadius - 3 ) * mScale ) ; pathArrow . lineTo ( center - 4 * mScale , center + ( mCompassRadius - 3 ) * mScale ) ; pathArrow . lineTo ( center , center - ( mCompassRadius - 3 ) * mScale ) ; pathArrow . close ( ) ; canvas . drawPath ( pathArrow , arrowPaint ) ; // Draw a little white dot in the middle canvas . drawCircle ( center , center , 2 , centerPaint ) ; }
|
A black pointer arrow .
| 456
| 5
|
152,796
|
static double wrap ( double n , double min , double max ) { return ( n >= min && n < max ) ? n : ( mod ( n - min , max - min ) + min ) ; }
|
Wraps the given value into the inclusive - exclusive interval between min and max .
| 43
| 16
|
152,797
|
public static double computeHeading ( IGeoPoint from , IGeoPoint to ) { // http://williams.best.vwh.net/avform.htm#Crs double fromLat = toRadians ( from . getLatitude ( ) ) ; double fromLng = toRadians ( from . getLongitude ( ) ) ; double toLat = toRadians ( to . getLatitude ( ) ) ; double toLng = toRadians ( to . getLongitude ( ) ) ; double dLng = toLng - fromLng ; double heading = atan2 ( sin ( dLng ) * cos ( toLat ) , cos ( fromLat ) * sin ( toLat ) - sin ( fromLat ) * cos ( toLat ) * cos ( dLng ) ) ; return wrap ( toDegrees ( heading ) , - 180 , 180 ) ; }
|
Returns the heading from one LatLng to another LatLng . Headings are expressed in degrees clockwise from North within the range [ - 180 180 ) .
| 194
| 33
|
152,798
|
public static IGeoPoint computeOffsetOrigin ( IGeoPoint to , double distance , double heading ) { heading = toRadians ( heading ) ; distance /= EARTH_RADIUS ; // http://lists.maptools.org/pipermail/proj/2008-October/003939.html double n1 = cos ( distance ) ; double n2 = sin ( distance ) * cos ( heading ) ; double n3 = sin ( distance ) * sin ( heading ) ; double n4 = sin ( toRadians ( to . getLatitude ( ) ) ) ; // There are two solutions for b. b = n2 * n4 +/- sqrt(), one solution results // in the latitude outside the [-90, 90] range. We first try one solution and // back off to the other if we are outside that range. double n12 = n1 * n1 ; double discriminant = n2 * n2 * n12 + n12 * n12 - n12 * n4 * n4 ; if ( discriminant < 0 ) { // No real solution which would make sense in IGeoPoint-space. return null ; } double b = n2 * n4 + sqrt ( discriminant ) ; b /= n1 * n1 + n2 * n2 ; double a = ( n4 - n2 * b ) / n1 ; double fromLatRadians = atan2 ( a , b ) ; if ( fromLatRadians < - PI / 2 || fromLatRadians > PI / 2 ) { b = n2 * n4 - sqrt ( discriminant ) ; b /= n1 * n1 + n2 * n2 ; fromLatRadians = atan2 ( a , b ) ; } if ( fromLatRadians < - PI / 2 || fromLatRadians > PI / 2 ) { // No solution which would make sense in IGeoPoint-space. return null ; } double fromLngRadians = toRadians ( to . getLongitude ( ) ) - atan2 ( n3 , n1 * cos ( fromLatRadians ) - n2 * sin ( fromLatRadians ) ) ; return new GeoPoint ( toDegrees ( fromLatRadians ) , toDegrees ( fromLngRadians ) ) ; }
|
Returns the location of origin when provided with a IGeoPoint destination meters travelled and original heading . Headings are expressed in degrees clockwise from North . This function returns null when no solution is available .
| 497
| 41
|
152,799
|
public static IGeoPoint interpolate ( IGeoPoint from , IGeoPoint to , double fraction ) { // http://en.wikipedia.org/wiki/Slerp double fromLat = toRadians ( from . getLatitude ( ) ) ; double fromLng = toRadians ( from . getLongitude ( ) ) ; double toLat = toRadians ( to . getLatitude ( ) ) ; double toLng = toRadians ( to . getLongitude ( ) ) ; double cosFromLat = cos ( fromLat ) ; double cosToLat = cos ( toLat ) ; // Computes Spherical interpolation coefficients. double angle = computeAngleBetween ( from , to ) ; double sinAngle = sin ( angle ) ; if ( sinAngle < 1E-6 ) { return from ; } double a = sin ( ( 1 - fraction ) * angle ) / sinAngle ; double b = sin ( fraction * angle ) / sinAngle ; // Converts from polar to vector and interpolate. double x = a * cosFromLat * cos ( fromLng ) + b * cosToLat * cos ( toLng ) ; double y = a * cosFromLat * sin ( fromLng ) + b * cosToLat * sin ( toLng ) ; double z = a * sin ( fromLat ) + b * sin ( toLat ) ; // Converts interpolated vector back to polar. double lat = atan2 ( z , sqrt ( x * x + y * y ) ) ; double lng = atan2 ( y , x ) ; return new GeoPoint ( toDegrees ( lat ) , toDegrees ( lng ) ) ; }
|
Returns the IGeoPoint which lies the given fraction of the way between the origin IGeoPoint and the destination IGeoPoint .
| 368
| 29
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.