code
stringlengths
73
34.1k
label
stringclasses
1 value
@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(); } }
java
@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(); } }
java
@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(); } }
java
@Override public Object get(Object obj) { String key = this.keyOf(obj); return this.getByKey(key); }
java
@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; }
java
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(); } }
java
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); } }
java
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); }
java
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); }
java
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); }
java
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; }
java
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; }
java
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; }
java
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); } }
java
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; }
java
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; }
java
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; }
java
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; }
java
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()); }
java
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); }
java
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; }
java
@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 }
java
private Call getNextCall(Integer nextLimit, String continueToken) { PagerParams params = new PagerParams((nextLimit != null) ? nextLimit : limit, continueToken); return listFunc.apply(params); }
java
private ApiListType executeRequest(Call call) throws IOException, ApiException { return client.handleResponse(call.execute(), listType); }
java
public PortForwardResult forward(V1Pod pod, List<Integer> ports) throws ApiException, IOException { return forward(pod.getMetadata().getNamespace(), pod.getMetadata().getName(), ports); }
java
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; }
java
@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(); } }
java
@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(); } }
java
@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(); } }
java
@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(); } }
java
@Override public ApiType get(ApiType obj) { String key = this.keyFunc.apply(obj); lock.lock(); try { return this.getByKey(key); } finally { lock.unlock(); } }
java
@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(); } }
java
@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(); } }
java
@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(); } }
java
@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(); } }
java
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); } } }
java
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); } } } }
java
public static <ApiType> String deletionHandlingMetaNamespaceKeyFunc(ApiType object) { if (object instanceof DeltaFIFO.DeletedFinalStateUnknown) { DeltaFIFO.DeletedFinalStateUnknown deleteObj = (DeltaFIFO.DeletedFinalStateUnknown) object; return deleteObj.getKey(); } return metaNamespaceKeyFunc(object); }
java
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); } }
java
public <T extends Message> ObjectOrStatus<T> list(T.Builder builder, String path) throws ApiException, IOException { return get(builder, path); }
java
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); }
java
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); }
java
public static void stream(String path, String method, ApiClient client, SocketListener listener) throws ApiException, IOException { stream(path, method, new ArrayList<Pair>(), client, listener); }
java
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); }
java
public synchronized OutputStream getOutputStream(int stream) { if (!output.containsKey(stream)) { output.put(stream, new WebSocketOutputStream(stream)); } return output.get(stream); }
java
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); }
java
@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)); } }
java
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; } } }
java
public static <T> T loadAs(String content, Class<T> clazz) { return getSnakeYaml().loadAs(new StringReader(content), clazz); }
java
public static <T> T loadAs(File f, Class<T> clazz) throws IOException { return getSnakeYaml().loadAs(new FileReader(f), clazz); }
java
public static <T> T loadAs(Reader reader, Class<T> clazz) { return getSnakeYaml().loadAs(reader, clazz); }
java
public static void dumpAll(Iterator<? extends Object> data, Writer output) { getSnakeYaml().dumpAll(data, output); }
java
public synchronized <ApiType, ApiListType> SharedIndexInformer<ApiType> sharedIndexInformerFor( Function<CallGeneratorParams, Call> callGenerator, Class<ApiType> apiTypeClass, Class<ApiListType> apiListTypeClass) { return sharedIndexInformerFor(callGenerator, apiTypeClass, apiListTypeClass, 0); }
java
public synchronized void startAllRegisteredInformers() { if (Collections.isEmptyMap(informers)) { return; } informers.forEach( (informerType, informer) -> { if (!startedInformers.containsKey(informerType)) { startedInformers.put(informerType, informerExecutor.submit(informer::run)); } }); }
java
public synchronized void stopAllRegisteredInformers() { if (Collections.isEmptyMap(informers)) { return; } informers.forEach( (informerType, informer) -> { if (startedInformers.containsKey(informerType)) { startedInformers.remove(informerType); informer.stop(); } }); informerExecutor.shutdown(); }
java
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); } } }
java
public void addHeaderView(View view) { mHeaderViewList.add(view); if (mAdapterWrapper != null) { mAdapterWrapper.addHeaderViewAndNotify(view); } }
java
public void removeHeaderView(View view) { mHeaderViewList.remove(view); if (mAdapterWrapper != null) { mAdapterWrapper.removeHeaderViewAndNotify(view); } }
java
public void addFooterView(View view) { mFooterViewList.add(view); if (mAdapterWrapper != null) { mAdapterWrapper.addFooterViewAndNotify(view); } }
java
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); } }
java
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); } }
java
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; }
java
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); }
java
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); }
java
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); }
java
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; }
java
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; }
java
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); }
java
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; } } }
java
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 } } }
java
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(); }
java
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(); }
java
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); }
java
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); }
java
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; }
java
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)); }
java
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)); }
java
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); }
java
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(); }
java
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); } }
java
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(); } }
java
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); }
java
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); }
java
static double wrap(double n, double min, double max) { return (n >= min && n < max) ? n : (mod(n - min, max - min) + min); }
java
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); }
java
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)); }
java
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)); }
java
private static double distanceRadians(double lat1, double lng1, double lat2, double lng2) { return arcHav(havDistance(lat1, lat2, lng1 - lng2)); }
java
static double computeAngleBetween(IGeoPoint from, IGeoPoint to) { return distanceRadians(toRadians(from.getLatitude()), toRadians(from.getLongitude()), toRadians(to.getLatitude()), toRadians(to.getLongitude())); }
java
public static double computeLength(List<IGeoPoint> path) { if (path.size() < 2) { return 0; } double length = 0; IGeoPoint prev = path.get(0); double prevLat = toRadians(prev.getLatitude()); double prevLng = toRadians(prev.getLongitude()); for (IGeoPoint point : path) { double lat = toRadians(point.getLatitude()); double lng = toRadians(point.getLongitude()); length += distanceRadians(prevLat, prevLng, lat, lng); prevLat = lat; prevLng = lng; } return length * EARTH_RADIUS; }
java
static double computeSignedArea(List<IGeoPoint> path, double radius) { int size = path.size(); if (size < 3) { return 0; } double total = 0; IGeoPoint prev = path.get(size - 1); double prevTanLat = tan((PI / 2 - toRadians(prev.getLatitude())) / 2); double prevLng = toRadians(prev.getLongitude()); // For each edge, accumulate the signed area of the triangle formed by the North Pole // and that edge ("polar triangle"). for (IGeoPoint point : path) { double tanLat = tan((PI / 2 - toRadians(point.getLatitude())) / 2); double lng = toRadians(point.getLongitude()); total += polarTriangleArea(tanLat, lng, prevTanLat, prevLng); prevTanLat = tanLat; prevLng = lng; } return total * (radius * radius); }
java
public void protectDisplayedTilesForCache(final Canvas pCanvas, final Projection pProjection) { if (!setViewPort(pCanvas, pProjection)) { return; } TileSystem.getTileFromMercator(mViewPort, TileSystem.getTileSize(mProjection.getZoomLevel()), mProtectedTiles); final int tileZoomLevel = TileSystem.getInputTileZoomLevel(mProjection.getZoomLevel()); mTileProvider.getTileCache().getMapTileArea().set(tileZoomLevel, mProtectedTiles); mTileProvider.getTileCache().maintenance(); }
java
protected boolean setViewPort(final Canvas pCanvas, final Projection pProjection) { setProjection(pProjection); getProjection().getMercatorViewPort(mViewPort); return true; }
java
public static void closeStream(final Closeable stream) { if (stream != null) { try { stream.close(); } catch (final IOException e) { //don't use android classes here, since this class is used outside of android e.printStackTrace(); } } }
java
private void addPoints(final List<GeoPoint> pPoints, final double pBeginLat, final double pBeginLon, final double pEndLat, final double pEndLon) { final double increment = 10; // in degrees pPoints.add(new GeoPoint(pBeginLat, pBeginLon)); double lat = pBeginLat; double lon = pBeginLon; double incLat = pBeginLat == pEndLat ? 0 : pBeginLat < pEndLat ? increment : -increment; double incLon = pBeginLon == pEndLon ? 0 : pBeginLon < pEndLon ? increment : -increment; while (true) { if (incLat != 0) { lat += incLat; if (incLat < 0) { if (lat < pEndLat) { break; } } else { if (lat > pEndLat) { break; } } } if (incLon != 0) { lon += incLon; if (incLon < 0) { if (lon < pEndLon) { break; } } else { if (lon > pEndLon) { break; } } } pPoints.add(new GeoPoint(lat, lon)); } pPoints.add(new GeoPoint(pEndLat, pEndLon)); }
java
void buildLinePortion(final Projection pProjection, final boolean pStorePoints){ final int size = mOriginalPoints.size(); if (size < 2) { // nothing to paint return; } computeProjected(pProjection); computeDistances(); final PointL offset = new PointL(); getBestOffset(pProjection, offset); mSegmentClipper.init(); clipAndStore(pProjection, offset, false, pStorePoints, mSegmentClipper); mSegmentClipper.end(); }
java
boolean isCloseTo(final GeoPoint pPoint, final double tolerance, final Projection pProjection, final boolean pClosePath) { return getCloseTo(pPoint, tolerance, pProjection, pClosePath) != null; }
java
static public ImageryMetaDataResource getInstanceFromJSON(final JSONObject a_jsonObject, final JSONObject parent) throws Exception { final ImageryMetaDataResource result = new ImageryMetaDataResource(); if(a_jsonObject==null) { throw new Exception("JSON to parse is null"); } result.copyright = parent.getString(COPYRIGHT); if(a_jsonObject.has(IMAGE_HEIGHT)) { result.m_imageHeight = a_jsonObject.getInt(IMAGE_HEIGHT); } if(a_jsonObject.has(IMAGE_WIDTH)) { result.m_imageWidth = a_jsonObject.getInt(IMAGE_WIDTH); } if(a_jsonObject.has(ZOOM_MIN)) { result.m_zoomMin = a_jsonObject.getInt(ZOOM_MIN); } if(a_jsonObject.has(ZOOM_MAX)) { result.m_zoomMax = a_jsonObject.getInt(ZOOM_MAX); } result.m_imageUrl = a_jsonObject.getString(IMAGE_URL); if(result.m_imageUrl!=null && result.m_imageUrl.matches(".*?\\{.*?\\}.*?")) { result.m_imageUrl = result.m_imageUrl.replaceAll("\\{.*?\\}", "%s"); } final JSONArray subdomains = a_jsonObject.getJSONArray(IMAGE_URL_SUBDOMAINS); if(subdomains!=null && subdomains.length()>=1) { result.m_imageUrlSubdomains = new String[subdomains.length()]; for(int i=0;i<subdomains.length();i++) { result.m_imageUrlSubdomains[i] = subdomains.getString(i); } } result.m_isInitialised = true; return result; }
java
public synchronized String getSubDomain() { if(m_imageUrlSubdomains==null || m_imageUrlSubdomains.length<=0) { return null; } final String result = m_imageUrlSubdomains[m_subdomainsCounter]; if(m_subdomainsCounter<m_imageUrlSubdomains.length-1) { m_subdomainsCounter++; } else { m_subdomainsCounter=0; } return result; }
java
public static ITileSource getTileSource(final String aName) throws IllegalArgumentException { for (final ITileSource tileSource : mTileSources) { if (tileSource.name().equals(aName)) { return tileSource; } } throw new IllegalArgumentException("No such tile source: " + aName); }
java