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 private long earliest;
62 private final long refreshWait;
65 public AbsAAFLocator(Access access, String name, final long refreshMin) throws LocatorException {
66 aaf_locator_host = access.getProperty(Config.AAF_LOCATE_URL, null);
68 epList = new LinkedList<EP>();
69 refreshWait = refreshMin;
72 String lat = access.getProperty(Config.CADI_LATITUDE,null);
73 String lng = access.getProperty(Config.CADI_LONGITUDE,null);
74 if(lat==null || lng==null) {
75 throw new LocatorException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " properties are required.");
77 latitude = Double.parseDouble(lat);
78 longitude = Double.parseDouble(lng);
80 if(name.startsWith("http")) { // simple URL
82 this.version = Config.AAF_DEFAULT_VERSION;
84 String[] split = Split.split(':', name);
86 this.version = (split.length > 1) ? split[1] : Config.AAF_DEFAULT_VERSION;
92 * This is the way to setup specialized AAFLocators ahead of time.
95 public static void setCreator(LocatorCreator lc) {
99 public static Locator<URI> create(String key) throws LocatorException {
101 String version = Config.AAF_DEFAULT_VERSION;
102 String pathInfo = null;
103 int prev = key.indexOf("/locate");
105 prev = key.indexOf('/',prev+6);
107 int next = key.indexOf('/',++prev);
109 name = key.substring(prev, next);
110 pathInfo=key.substring(next);
112 name = key.substring(prev);
114 String[] split = Split.split(':', name);
115 switch(split.length) {
125 if(key.startsWith("http")) {
127 if(locatorCreator != null) {
128 AbsAAFLocator<?> aal = locatorCreator.create(name, version);
130 aal.setPathInfo(pathInfo);
135 return new PropertyLocator(key);
141 public static Locator<URI> create(final String name, final String version) throws LocatorException {
142 return locatorCreator.create(name, version);
145 public interface LocatorCreator {
146 public AbsAAFLocator<?> create(String key, String version) throws LocatorException;
147 public void setSelf(String hostname, int port);
150 protected static String nameFromLocatorURI(URI locatorURI) {
151 String[] path = Split.split('/', locatorURI.getPath());
152 if(path.length>2 && "locate".equals(path[1])) {
155 return locatorURI.toString();
160 * Setting "self" excludes this service from the list. Critical for contacting peers.
162 public void setSelf(final String hostname, final int port) {
168 public static void setCreatorSelf(final String hostname, final int port) {
169 if(locatorCreator!=null) {
170 locatorCreator.setSelf(hostname,port);
174 protected final synchronized void replace(List<EP> list) {
179 * Call _refresh as needed during calls, but actual refresh will not occur if there
180 * are existing entities or if it has been called in the last 10 (settable) seconds.
181 * Timed Refreshes happen by Scheduled Thread
183 private final boolean _refresh() {
185 long now=System.currentTimeMillis();
188 synchronized(epList) {
190 earliest = now + refreshWait; // call only up to 10 seconds.
193 access.log(Level.ERROR, "Must wait at least " + refreshWait/1000 + " seconds for Locator Refresh");
199 private boolean noEntries() {
200 return epList.size()<=0;
204 public URI get(Item item) throws LocatorException {
207 } else if(item instanceof AAFLItem) {
208 return getURI(((AAFLItem)item).uri);
210 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
215 public boolean hasItems() {
216 boolean isEmpty = epList.isEmpty();
218 for(Iterator<EP> iter = epList.iterator(); iter.hasNext(); ) {
226 if(_refresh()) { // is refreshed... check again
227 isEmpty = epList.isEmpty();
233 public void invalidate(Item item) throws LocatorException {
235 if(item instanceof AAFLItem) {
236 AAFLItem ali =(AAFLItem)item;
238 synchronized(epList) {
242 ali.iter = getIterator(); // for next guy... fresh iterator
244 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
250 public Item best() throws LocatorException {
252 throw new LocatorException("No Entries found" + (pathInfo==null?"":(" for " + pathInfo)));
254 List<EP> lep = new ArrayList<EP>();
256 // Note: Deque is sorted on the way by closest distance
257 Iterator<EP> iter = getIterator();
259 while(iter.hasNext()) {
266 if(Math.abs(ep.distance-first.distance)<.1) { // allow for nearby/precision issues.
278 return new AAFLItem(iter,first);
280 int rand = sr.nextInt(); // Sonar chokes without.
281 int i = Math.abs(rand)%lep.size();
285 return new AAFLItem(iter,lep.get(i));
291 private Iterator<EP> getIterator() {
292 Object[] epa = epList.toArray();
295 epa = epList.toArray();
297 return new EPIterator(epa, epList);
300 public class EPIterator implements Iterator<EP> {
301 private final Object[] epa;
302 private final List<EP> epList;
305 public EPIterator(Object[] epa, List<EP> epList) {
307 this.epList = epList;
308 idx = epa.length>0?0:-1;
312 public boolean hasNext() {
317 while(idx<epa.length) {
318 if((obj=epa[idx])==null || !((EP)obj).valid) {
324 return idx<epa.length;
331 throw new NoSuchElementException();
333 return (EP)epa[idx++];
337 public void remove() {
338 if(idx>=0 && idx<epa.length) {
339 synchronized(epList) {
340 epList.remove(epa[idx]);
347 public Item first() {
348 Iterator<EP> iter = getIterator();
349 EP ep = AAFLItem.next(iter);
353 return new AAFLItem(iter,ep);
357 public Item next(Item prev) throws LocatorException {
359 StringBuilder sb = new StringBuilder("Locator Item passed in next(item) is null.");
361 for(StackTraceElement st : Thread.currentThread().getStackTrace()) {
363 sb.append(st.toString());
365 sb.append("\n\t...");
369 access.log(Level.ERROR, sb);
371 if(prev instanceof AAFLItem) {
372 AAFLItem ali = (AAFLItem)prev;
373 EP ep = AAFLItem.next(ali.iter);
375 return new AAFLItem(ali.iter,ep);
378 throw new LocatorException(prev.getClass().getName() + " does not belong to AAFLocator");
384 protected static class AAFLItem implements Item {
385 private Iterator<EP> iter;
389 public AAFLItem(Iterator<EP> iter, EP ep) {
395 private static EP next(Iterator<EP> iter) {
397 while(iter.hasNext() && (ep==null || !ep.valid)) {
403 public String toString() {
404 return ep==null?"Locator Item Invalid":ep.toString();
408 protected static class EP implements Comparable<EP> {
410 public final double distance;
411 private boolean valid;
413 public EP(final Endpoint ep, double latitude, double longitude) throws URISyntaxException {
414 uri = new URI(ep.getProtocol(),null,ep.getHostname(),ep.getPort(),null,null,null);
415 distance = GreatCircle.calc(latitude, longitude, ep.getLatitude(), ep.getLongitude());
419 public void invalid() {
424 public int compareTo(EP o) {
425 if(distance<o.distance) {
427 } else if(distance>o.distance) {
435 public String toString() {
436 return distance + ": " + uri + (valid?" valid":" invalidate");
441 * @see org.onap.aaf.cadi.Locator#destroy()
444 public void destroy() {
449 public String toString() {
450 return "AAFLocator for " + name + " on " + getURI();
453 public AbsAAFLocator<TRANS> setPathInfo(String pathInfo) {
454 this.pathInfo = pathInfo;
459 public AbsAAFLocator<TRANS> setQuery(String query) {
465 public AbsAAFLocator<TRANS> setFragment(String fragment) {
466 this.fragment = fragment;
471 // Core URI, for reporting purposes
472 protected abstract URI getURI();
474 protected URI getURI(URI rv) throws LocatorException {
477 return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment);
478 } catch (URISyntaxException e) {
479 throw new LocatorException("Error copying URL");