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 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(getClass().getSimpleName(),"https://"+Config.AAF_LOCATE_URL_TAG,null,null);
77 if(aaf_locator_host.endsWith("/locate")) {
78 aaf_locator_uri = new URI(aaf_locator_host);
80 aaf_locator_uri = new URI(aaf_locator_host+"/locate");
83 access.printf(Level.INFO, "AbsAAFLocator AAF URI is %s",aaf_locator_uri);
84 } catch (URISyntaxException e) {
85 throw new LocatorException(e);
88 name = rph.replacements(getClass().getSimpleName(),name, null,null);
89 access.printf(Level.INFO, "AbsAAFLocator name is %s",aaf_locator_uri);
91 epList = new LinkedList<>();
92 refreshWait = refreshMin;
95 String lat = access.getProperty(Config.CADI_LATITUDE,null);
96 String lng = access.getProperty(Config.CADI_LONGITUDE,null);
97 if (lat==null || lng==null) {
98 throw new LocatorException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " properties are required.");
100 latitude = Double.parseDouble(lat);
101 longitude = Double.parseDouble(lng);
105 if (name.startsWith("http")) { // simple URL
107 this.version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
109 String[] split = Split.split(':', name);
110 this.name = split[0];
111 this.version = (split.length > 1) ? split[1] : access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION);
117 * This is the way to setup specialized AAFLocators ahead of time.
120 public static void setCreator(LocatorCreator lc) {
124 public static Locator<URI> create(final String name, final String version) throws LocatorException {
125 if(locatorCreator==null) {
126 throw new LocatorException("LocatorCreator is not set");
128 return locatorCreator.create(name, version);
131 public interface LocatorCreator {
132 public AbsAAFLocator<?> create(String key, String version) throws LocatorException;
133 public void setSelf(String hostname, int port);
136 protected static String nameFromLocatorURI(URI locatorURI) {
137 String[] path = Split.split('/', locatorURI.getPath());
138 if (path.length>1 && "locate".equals(path[1])) {
140 } else if(path.length>1) {
143 return locatorURI.toString();
148 * Setting "self" excludes this service from the list. Critical for contacting peers.
150 public void setSelf(final String hostname, final int port) {
156 public static void setCreatorSelf(final String hostname, final int port) {
157 if (locatorCreator!=null) {
158 locatorCreator.setSelf(hostname,port);
162 protected final synchronized void replace(List<EP> list) {
167 * Call _refresh as needed during calls, but actual refresh will not occur if there
168 * are existing entities or if it has been called in the last 10 (settable) seconds.
169 * Timed Refreshes happen by Scheduled Thread
171 private final boolean _refresh() {
173 long now=System.currentTimeMillis();
176 synchronized(epList) {
178 earliest = now + refreshWait; // call only up to 10 seconds.
181 access.log(Level.ERROR, "Must wait at least " + refreshWait/1000 + " seconds for Locator Refresh");
187 private boolean noEntries() {
188 return epList.isEmpty();
192 public URI get(Item item) throws LocatorException {
195 } else if (item instanceof AAFLItem) {
196 return getURI(((AAFLItem)item).uri);
198 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
203 public boolean hasItems() {
204 boolean isEmpty = epList.isEmpty();
206 for (Iterator<EP> iter = epList.iterator(); iter.hasNext(); ) {
214 if (_refresh()) { // is refreshed... check again
215 isEmpty = epList.isEmpty();
221 public void invalidate(Item item) throws LocatorException {
223 if (item instanceof AAFLItem) {
224 AAFLItem ali =(AAFLItem)item;
226 synchronized(epList) {
230 ali.iter = getIterator(); // for next guy... fresh iterator
232 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
238 public Item best() throws LocatorException {
240 throw new LocatorException("No Entries found for '" + aaf_locator_uri.toString() + '/' + name + ':' + version + '\'');
242 List<EP> lep = new ArrayList<>();
244 // Note: Deque is sorted on the way by closest distance
245 Iterator<EP> iter = getIterator();
247 while (iter.hasNext()) {
254 if (Math.abs(ep.distance-first.distance)<.1) { // allow for nearby/precision issues.
266 return new AAFLItem(iter,first);
268 int rand = sr.nextInt(); // Sonar chokes without.
269 int i = Math.abs(rand)%lep.size();
273 return new AAFLItem(iter,lep.get(i));
279 private Iterator<EP> getIterator() {
280 Object[] epa = epList.toArray();
283 epa = epList.toArray();
285 return new EPIterator(epa, epList);
288 public class EPIterator implements Iterator<EP> {
289 private final Object[] epa;
290 private final List<EP> epList;
293 public EPIterator(Object[] epa, List<EP> epList) {
295 this.epList = epList;
296 idx = epa.length>0?0:-1;
300 public boolean hasNext() {
305 while (idx<epa.length) {
306 if ((obj=epa[idx])==null || !((EP)obj).valid) {
312 return idx<epa.length;
319 throw new NoSuchElementException();
321 return (EP)epa[idx++];
325 public void remove() {
326 if (idx>=0 && idx<epa.length) {
327 synchronized(epList) {
328 epList.remove(epa[idx]);
335 public Item first() {
336 Iterator<EP> iter = getIterator();
337 EP ep = AAFLItem.next(iter);
341 return new AAFLItem(iter,ep);
345 public Item next(Item prev) throws LocatorException {
347 StringBuilder sb = new StringBuilder("Locator Item passed in next(item) is null.");
349 for (StackTraceElement st : Thread.currentThread().getStackTrace()) {
351 sb.append(st.toString());
353 sb.append("\n\t...");
357 access.log(Level.ERROR, sb);
359 if (prev instanceof AAFLItem) {
360 AAFLItem ali = (AAFLItem)prev;
361 EP ep = AAFLItem.next(ali.iter);
363 return new AAFLItem(ali.iter,ep);
366 throw new LocatorException(prev.getClass().getName() + " does not belong to AAFLocator");
372 protected static class AAFLItem implements Item {
373 private Iterator<EP> iter;
377 public AAFLItem(Iterator<EP> iter, EP ep) {
383 private static EP next(Iterator<EP> iter) {
385 while (iter.hasNext() && (ep==null || !ep.valid)) {
391 public String toString() {
392 return ep==null?"Locator Item Invalid":ep.toString();
396 protected static class EP implements Comparable<EP> {
398 private final double distance;
399 private boolean valid;
401 public EP(final Endpoint ep, double latitude, double longitude) throws URISyntaxException {
402 uri = new URI(ep.getProtocol(),null,ep.getHostname(),ep.getPort(),null,null,null);
403 distance = GreatCircle.calc(latitude, longitude, ep.getLatitude(), ep.getLongitude());
407 public void invalid() {
412 public int compareTo(EP o) {
413 if (distance<o.distance) {
415 } else if (distance>o.distance) {
423 public String toString() {
424 return distance + ": " + uri + (valid?" valid":" invalidate");
429 * @see org.onap.aaf.cadi.Locator#destroy()
432 public void destroy() {
437 public String toString() {
438 return "AAFLocator for " + name + " on " + getURI();
441 public AbsAAFLocator<TRANS> setPathInfo(String pathInfo) {
442 this.pathInfo = pathInfo;
447 public AbsAAFLocator<TRANS> setQuery(String query) {
453 public AbsAAFLocator<TRANS> setFragment(String fragment) {
454 this.fragment = fragment;
459 // Core URI, for reporting purposes
460 protected abstract URI getURI();
462 protected URI getURI(URI rv) throws LocatorException {
465 return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment);
466 } catch (URISyntaxException e) {
467 throw new LocatorException("Error copying URL", e);
473 protected void clear() {