2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6 * ===========================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
22 package org.onap.aaf.cadi.aaf.v2_0;
25 import java.net.URISyntaxException;
26 import java.security.SecureRandom;
27 import java.util.ArrayList;
28 import java.util.Iterator;
29 import java.util.LinkedList;
30 import java.util.List;
31 import java.util.NoSuchElementException;
33 import org.onap.aaf.cadi.Access;
34 import org.onap.aaf.cadi.Access.Level;
35 import org.onap.aaf.cadi.Locator;
36 import org.onap.aaf.cadi.LocatorException;
37 import org.onap.aaf.cadi.config.Config;
38 import org.onap.aaf.cadi.locator.PropertyLocator;
39 import org.onap.aaf.cadi.routing.GreatCircle;
40 import org.onap.aaf.misc.env.Trans;
41 import org.onap.aaf.misc.env.util.Split;
43 import locate.v1_0.Endpoint;
45 public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> {
46 protected static final SecureRandom sr = new SecureRandom();
47 private static LocatorCreator locatorCreator;
48 protected final Access access;
50 protected final double latitude;
51 protected final double longitude;
52 protected List<EP> epList;
53 protected final String name, version;
54 private String pathInfo = null;
55 private String query = null;
56 private String fragment = null;
57 private boolean additional = false;
58 protected String myhostname;
60 protected final String aaf_locator_host;
61 protected final URI aaf_locator_uri;
62 private long earliest;
63 private final long refreshWait;
66 public AbsAAFLocator(Access access, String name, final long refreshMin) throws LocatorException {
67 aaf_locator_host = access.getProperty(Config.AAF_LOCATE_URL, null);
68 if(aaf_locator_host==null) {
69 aaf_locator_uri = null;
72 aaf_locator_uri = new URI(aaf_locator_host);
73 } catch (URISyntaxException e) {
74 throw new LocatorException(e);
78 epList = new LinkedList<>();
79 refreshWait = refreshMin;
82 String lat = access.getProperty(Config.CADI_LATITUDE,null);
83 String lng = access.getProperty(Config.CADI_LONGITUDE,null);
84 if(lat==null || lng==null) {
85 throw new LocatorException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " properties are required.");
87 latitude = Double.parseDouble(lat);
88 longitude = Double.parseDouble(lng);
90 if(name.startsWith("http")) { // simple URL
92 this.version = Config.AAF_DEFAULT_VERSION;
94 String[] split = Split.split(':', name);
96 this.version = (split.length > 1) ? split[1] : Config.AAF_DEFAULT_VERSION;
102 * This is the way to setup specialized AAFLocators ahead of time.
105 public static void setCreator(LocatorCreator lc) {
109 public static Locator<URI> create(String key) throws LocatorException {
111 String version = Config.AAF_DEFAULT_VERSION;
112 String pathInfo = null;
113 int prev = key.indexOf("/locate");
115 prev = key.indexOf('/',prev+6);
117 int next = key.indexOf('/',++prev);
119 name = key.substring(prev, next);
120 pathInfo=key.substring(next);
122 name = key.substring(prev);
124 String[] split = Split.split(':', name);
125 switch(split.length) {
137 if(key.startsWith("http")) {
139 if(locatorCreator != null) {
140 AbsAAFLocator<?> aal = locatorCreator.create(name, version);
142 aal.setPathInfo(pathInfo);
147 return new PropertyLocator(key);
153 public static Locator<URI> create(final String name, final String version) throws LocatorException {
154 return locatorCreator.create(name, version);
157 public interface LocatorCreator {
158 public AbsAAFLocator<?> create(String key, String version) throws LocatorException;
159 public void setSelf(String hostname, int port);
162 protected static String nameFromLocatorURI(URI locatorURI) {
163 String[] path = Split.split('/', locatorURI.getPath());
164 if(path.length>2 && "locate".equals(path[1])) {
167 return locatorURI.toString();
172 * Setting "self" excludes this service from the list. Critical for contacting peers.
174 public void setSelf(final String hostname, final int port) {
180 public static void setCreatorSelf(final String hostname, final int port) {
181 if(locatorCreator!=null) {
182 locatorCreator.setSelf(hostname,port);
186 protected final synchronized void replace(List<EP> list) {
191 * Call _refresh as needed during calls, but actual refresh will not occur if there
192 * are existing entities or if it has been called in the last 10 (settable) seconds.
193 * Timed Refreshes happen by Scheduled Thread
195 private final boolean _refresh() {
197 long now=System.currentTimeMillis();
200 synchronized(epList) {
202 earliest = now + refreshWait; // call only up to 10 seconds.
205 access.log(Level.ERROR, "Must wait at least " + refreshWait/1000 + " seconds for Locator Refresh");
211 private boolean noEntries() {
212 return epList.isEmpty();
216 public URI get(Item item) throws LocatorException {
219 } else if(item instanceof AAFLItem) {
220 return getURI(((AAFLItem)item).uri);
222 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
227 public boolean hasItems() {
228 boolean isEmpty = epList.isEmpty();
230 for(Iterator<EP> iter = epList.iterator(); iter.hasNext(); ) {
238 if(_refresh()) { // is refreshed... check again
239 isEmpty = epList.isEmpty();
245 public void invalidate(Item item) throws LocatorException {
247 if(item instanceof AAFLItem) {
248 AAFLItem ali =(AAFLItem)item;
250 synchronized(epList) {
254 ali.iter = getIterator(); // for next guy... fresh iterator
256 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
262 public Item best() throws LocatorException {
264 throw new LocatorException("No Entries found" + (pathInfo==null?"":(" for " + pathInfo)));
266 List<EP> lep = new ArrayList<>();
268 // Note: Deque is sorted on the way by closest distance
269 Iterator<EP> iter = getIterator();
271 while(iter.hasNext()) {
278 if(Math.abs(ep.distance-first.distance)<.1) { // allow for nearby/precision issues.
290 return new AAFLItem(iter,first);
292 int rand = sr.nextInt(); // Sonar chokes without.
293 int i = Math.abs(rand)%lep.size();
297 return new AAFLItem(iter,lep.get(i));
303 private Iterator<EP> getIterator() {
304 Object[] epa = epList.toArray();
307 epa = epList.toArray();
309 return new EPIterator(epa, epList);
312 public class EPIterator implements Iterator<EP> {
313 private final Object[] epa;
314 private final List<EP> epList;
317 public EPIterator(Object[] epa, List<EP> epList) {
319 this.epList = epList;
320 idx = epa.length>0?0:-1;
324 public boolean hasNext() {
329 while(idx<epa.length) {
330 if((obj=epa[idx])==null || !((EP)obj).valid) {
336 return idx<epa.length;
343 throw new NoSuchElementException();
345 return (EP)epa[idx++];
349 public void remove() {
350 if(idx>=0 && idx<epa.length) {
351 synchronized(epList) {
352 epList.remove(epa[idx]);
359 public Item first() {
360 Iterator<EP> iter = getIterator();
361 EP ep = AAFLItem.next(iter);
365 return new AAFLItem(iter,ep);
369 public Item next(Item prev) throws LocatorException {
371 StringBuilder sb = new StringBuilder("Locator Item passed in next(item) is null.");
373 for(StackTraceElement st : Thread.currentThread().getStackTrace()) {
375 sb.append(st.toString());
377 sb.append("\n\t...");
381 access.log(Level.ERROR, sb);
383 if(prev instanceof AAFLItem) {
384 AAFLItem ali = (AAFLItem)prev;
385 EP ep = AAFLItem.next(ali.iter);
387 return new AAFLItem(ali.iter,ep);
390 throw new LocatorException(prev.getClass().getName() + " does not belong to AAFLocator");
396 protected static class AAFLItem implements Item {
397 private Iterator<EP> iter;
401 public AAFLItem(Iterator<EP> iter, EP ep) {
407 private static EP next(Iterator<EP> iter) {
409 while(iter.hasNext() && (ep==null || !ep.valid)) {
415 public String toString() {
416 return ep==null?"Locator Item Invalid":ep.toString();
420 protected static class EP implements Comparable<EP> {
422 private final double distance;
423 private boolean valid;
425 public EP(final Endpoint ep, double latitude, double longitude) throws URISyntaxException {
426 uri = new URI(ep.getProtocol(),null,ep.getHostname(),ep.getPort(),null,null,null);
427 distance = GreatCircle.calc(latitude, longitude, ep.getLatitude(), ep.getLongitude());
431 public void invalid() {
436 public int compareTo(EP o) {
437 if(distance<o.distance) {
439 } else if(distance>o.distance) {
447 public String toString() {
448 return distance + ": " + uri + (valid?" valid":" invalidate");
453 * @see org.onap.aaf.cadi.Locator#destroy()
456 public void destroy() {
461 public String toString() {
462 return "AAFLocator for " + name + " on " + getURI();
465 public AbsAAFLocator<TRANS> setPathInfo(String pathInfo) {
466 this.pathInfo = pathInfo;
471 public AbsAAFLocator<TRANS> setQuery(String query) {
477 public AbsAAFLocator<TRANS> setFragment(String fragment) {
478 this.fragment = fragment;
483 // Core URI, for reporting purposes
484 protected abstract URI getURI();
486 protected URI getURI(URI rv) throws LocatorException {
489 return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment);
490 } catch (URISyntaxException e) {
491 throw new LocatorException("Error copying URL", e);