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.net.UnknownHostException;
27 import java.security.SecureRandom;
28 import java.util.ArrayList;
29 import java.util.Iterator;
30 import java.util.LinkedList;
31 import java.util.List;
32 import java.util.NoSuchElementException;
34 import org.onap.aaf.cadi.Access;
35 import org.onap.aaf.cadi.Access.Level;
36 import org.onap.aaf.cadi.CadiException;
37 import org.onap.aaf.cadi.Locator;
38 import org.onap.aaf.cadi.LocatorException;
39 import org.onap.aaf.cadi.config.Config;
40 import org.onap.aaf.cadi.config.RegistrationPropHolder;
41 import org.onap.aaf.cadi.routing.GreatCircle;
42 import org.onap.aaf.misc.env.Trans;
43 import org.onap.aaf.misc.env.util.Split;
45 import locate.v1_0.Endpoint;
47 public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> {
48 protected static final SecureRandom sr = new SecureRandom();
49 private static LocatorCreator locatorCreator;
50 protected final Access access;
52 protected final double latitude;
53 protected final double longitude;
54 protected List<EP> epList;
55 protected final String name, version;
56 private String pathInfo = null;
57 private String query = null;
58 private String fragment = null;
59 private boolean additional = false;
60 protected String myhostname;
62 protected final String aaf_locator_host;
63 protected final URI aaf_locator_uri;
64 private long earliest;
65 private final long refreshWait;
68 public AbsAAFLocator(Access access, String name, final long refreshMin) throws LocatorException {
69 RegistrationPropHolder rph;
71 rph = new RegistrationPropHolder(access, 0);
72 } catch (UnknownHostException | CadiException e1) {
73 throw new LocatorException(e1);
76 aaf_locator_host = rph.replacements("https://"+Config.AAF_LOCATE_URL_TAG,null,null);
77 aaf_locator_uri = new URI(aaf_locator_host);
78 access.printf(Level.INFO, "AbsAAFLocator AAF URI is %s",aaf_locator_uri);
79 } catch (URISyntaxException e) {
80 throw new LocatorException(e);
83 name = rph.replacements(name, null,null);
84 access.printf(Level.INFO, "AbsAAFLocator name is %s",aaf_locator_uri);
86 epList = new LinkedList<>();
87 refreshWait = refreshMin;
90 String lat = access.getProperty(Config.CADI_LATITUDE,null);
91 String lng = access.getProperty(Config.CADI_LONGITUDE,null);
92 if (lat==null || lng==null) {
93 throw new LocatorException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " properties are required.");
95 latitude = Double.parseDouble(lat);
96 longitude = Double.parseDouble(lng);
100 if (name.startsWith("http")) { // simple URL
102 this.version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
104 String[] split = Split.split(':', name);
105 this.name = split[0];
106 this.version = (split.length > 1) ? split[1] : access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
112 * This is the way to setup specialized AAFLocators ahead of time.
115 public static void setCreator(LocatorCreator lc) {
119 public static Locator<URI> create(final String name, final String version) throws LocatorException {
120 return locatorCreator.create(name, version);
123 public interface LocatorCreator {
124 public AbsAAFLocator<?> create(String key, String version) throws LocatorException;
125 public void setSelf(String hostname, int port);
128 protected static String nameFromLocatorURI(URI locatorURI) {
129 String[] path = Split.split('/', locatorURI.getPath());
130 if (path.length>1 && "locate".equals(path[1])) {
132 } else if(path.length>1) {
135 return locatorURI.toString();
140 * Setting "self" excludes this service from the list. Critical for contacting peers.
142 public void setSelf(final String hostname, final int port) {
148 public static void setCreatorSelf(final String hostname, final int port) {
149 if (locatorCreator!=null) {
150 locatorCreator.setSelf(hostname,port);
154 protected final synchronized void replace(List<EP> list) {
159 * Call _refresh as needed during calls, but actual refresh will not occur if there
160 * are existing entities or if it has been called in the last 10 (settable) seconds.
161 * Timed Refreshes happen by Scheduled Thread
163 private final boolean _refresh() {
165 long now=System.currentTimeMillis();
168 synchronized(epList) {
170 earliest = now + refreshWait; // call only up to 10 seconds.
173 access.log(Level.ERROR, "Must wait at least " + refreshWait/1000 + " seconds for Locator Refresh");
179 private boolean noEntries() {
180 return epList.isEmpty();
184 public URI get(Item item) throws LocatorException {
187 } else if (item instanceof AAFLItem) {
188 return getURI(((AAFLItem)item).uri);
190 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
195 public boolean hasItems() {
196 boolean isEmpty = epList.isEmpty();
198 for (Iterator<EP> iter = epList.iterator(); iter.hasNext(); ) {
206 if (_refresh()) { // is refreshed... check again
207 isEmpty = epList.isEmpty();
213 public void invalidate(Item item) throws LocatorException {
215 if (item instanceof AAFLItem) {
216 AAFLItem ali =(AAFLItem)item;
218 synchronized(epList) {
222 ali.iter = getIterator(); // for next guy... fresh iterator
224 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
230 public Item best() throws LocatorException {
232 throw new LocatorException("No Entries found for '" + aaf_locator_uri.toString() + "/locate/" + name + ':' + version + '\'');
234 List<EP> lep = new ArrayList<>();
236 // Note: Deque is sorted on the way by closest distance
237 Iterator<EP> iter = getIterator();
239 while (iter.hasNext()) {
246 if (Math.abs(ep.distance-first.distance)<.1) { // allow for nearby/precision issues.
258 return new AAFLItem(iter,first);
260 int rand = sr.nextInt(); // Sonar chokes without.
261 int i = Math.abs(rand)%lep.size();
265 return new AAFLItem(iter,lep.get(i));
271 private Iterator<EP> getIterator() {
272 Object[] epa = epList.toArray();
275 epa = epList.toArray();
277 return new EPIterator(epa, epList);
280 public class EPIterator implements Iterator<EP> {
281 private final Object[] epa;
282 private final List<EP> epList;
285 public EPIterator(Object[] epa, List<EP> epList) {
287 this.epList = epList;
288 idx = epa.length>0?0:-1;
292 public boolean hasNext() {
297 while (idx<epa.length) {
298 if ((obj=epa[idx])==null || !((EP)obj).valid) {
304 return idx<epa.length;
311 throw new NoSuchElementException();
313 return (EP)epa[idx++];
317 public void remove() {
318 if (idx>=0 && idx<epa.length) {
319 synchronized(epList) {
320 epList.remove(epa[idx]);
327 public Item first() {
328 Iterator<EP> iter = getIterator();
329 EP ep = AAFLItem.next(iter);
333 return new AAFLItem(iter,ep);
337 public Item next(Item prev) throws LocatorException {
339 StringBuilder sb = new StringBuilder("Locator Item passed in next(item) is null.");
341 for (StackTraceElement st : Thread.currentThread().getStackTrace()) {
343 sb.append(st.toString());
345 sb.append("\n\t...");
349 access.log(Level.ERROR, sb);
351 if (prev instanceof AAFLItem) {
352 AAFLItem ali = (AAFLItem)prev;
353 EP ep = AAFLItem.next(ali.iter);
355 return new AAFLItem(ali.iter,ep);
358 throw new LocatorException(prev.getClass().getName() + " does not belong to AAFLocator");
364 protected static class AAFLItem implements Item {
365 private Iterator<EP> iter;
369 public AAFLItem(Iterator<EP> iter, EP ep) {
375 private static EP next(Iterator<EP> iter) {
377 while (iter.hasNext() && (ep==null || !ep.valid)) {
383 public String toString() {
384 return ep==null?"Locator Item Invalid":ep.toString();
388 protected static class EP implements Comparable<EP> {
390 private final double distance;
391 private boolean valid;
393 public EP(final Endpoint ep, double latitude, double longitude) throws URISyntaxException {
394 uri = new URI(ep.getProtocol(),null,ep.getHostname(),ep.getPort(),null,null,null);
395 distance = GreatCircle.calc(latitude, longitude, ep.getLatitude(), ep.getLongitude());
399 public void invalid() {
404 public int compareTo(EP o) {
405 if (distance<o.distance) {
407 } else if (distance>o.distance) {
415 public String toString() {
416 return distance + ": " + uri + (valid?" valid":" invalidate");
421 * @see org.onap.aaf.cadi.Locator#destroy()
424 public void destroy() {
429 public String toString() {
430 return "AAFLocator for " + name + " on " + getURI();
433 public AbsAAFLocator<TRANS> setPathInfo(String pathInfo) {
434 this.pathInfo = pathInfo;
439 public AbsAAFLocator<TRANS> setQuery(String query) {
445 public AbsAAFLocator<TRANS> setFragment(String fragment) {
446 this.fragment = fragment;
451 // Core URI, for reporting purposes
452 protected abstract URI getURI();
454 protected URI getURI(URI rv) throws LocatorException {
457 return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment);
458 } catch (URISyntaxException e) {
459 throw new LocatorException("Error copying URL", e);