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.aaf.Defaults;
36 import org.onap.aaf.cadi.Locator;
37 import org.onap.aaf.cadi.LocatorException;
38 import org.onap.aaf.cadi.config.Config;
39 import org.onap.aaf.cadi.locator.PropertyLocator;
40 import org.onap.aaf.cadi.routing.GreatCircle;
41 import org.onap.aaf.misc.env.Trans;
42 import org.onap.aaf.misc.env.util.Split;
44 import locate.v1_0.Endpoint;
46 public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> {
47 protected static final SecureRandom sr = new SecureRandom();
48 private static LocatorCreator locatorCreator;
49 protected final Access access;
51 protected final double latitude;
52 protected final double longitude;
53 protected List<EP> epList;
54 protected final String name, version;
55 private String pathInfo = null;
56 private String query = null;
57 private String fragment = null;
58 private boolean additional = false;
59 protected String myhostname;
61 protected final String aaf_locator_host;
62 protected final URI aaf_locator_uri;
63 private long earliest;
64 private final long refreshWait;
67 public AbsAAFLocator(Access access, String name, final long refreshMin) throws LocatorException {
68 aaf_locator_host = access.getProperty(Config.AAF_LOCATE_URL, null);
69 if(aaf_locator_host==null) {
70 aaf_locator_uri = null;
73 aaf_locator_uri = new URI(aaf_locator_host);
74 } catch (URISyntaxException e) {
75 throw new LocatorException(e);
79 epList = new LinkedList<>();
80 refreshWait = refreshMin;
83 String lat = access.getProperty(Config.CADI_LATITUDE,null);
84 String lng = access.getProperty(Config.CADI_LONGITUDE,null);
85 if(lat==null || lng==null) {
86 throw new LocatorException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " properties are required.");
88 latitude = Double.parseDouble(lat);
89 longitude = Double.parseDouble(lng);
91 if(name.startsWith(Defaults.AAF_NS)) {
92 String root_ns = access.getProperty(Config.AAF_ROOT_NS, null);
94 name=name.replace(Defaults.AAF_NS, root_ns);
97 if(name.startsWith("http")) { // simple URL
99 this.version = Config.AAF_DEFAULT_VERSION;
101 String[] split = Split.split(':', name);
102 this.name = split[0];
103 this.version = (split.length > 1) ? split[1] : Config.AAF_DEFAULT_VERSION;
109 * This is the way to setup specialized AAFLocators ahead of time.
112 public static void setCreator(LocatorCreator lc) {
116 public static Locator<URI> create(String key) throws LocatorException {
118 String version = Config.AAF_DEFAULT_VERSION;
119 String pathInfo = null;
120 int prev = key.indexOf("/locate");
122 prev = key.indexOf('/',prev+6);
124 int next = key.indexOf('/',++prev);
126 name = key.substring(prev, next);
127 pathInfo=key.substring(next);
129 name = key.substring(prev);
131 String[] split = Split.split(':', name);
132 switch(split.length) {
142 if(key.startsWith("http")) {
144 if(locatorCreator != null) {
145 AbsAAFLocator<?> aal = locatorCreator.create(name, version);
147 aal.setPathInfo(pathInfo);
152 return new PropertyLocator(key);
158 public static Locator<URI> create(final String name, final String version) throws LocatorException {
159 return locatorCreator.create(name, version);
162 public interface LocatorCreator {
163 public AbsAAFLocator<?> create(String key, String version) throws LocatorException;
164 public void setSelf(String hostname, int port);
167 protected static String nameFromLocatorURI(URI locatorURI) {
168 String[] path = Split.split('/', locatorURI.getPath());
169 if(path.length>2 && "locate".equals(path[1])) {
172 return locatorURI.toString();
177 * Setting "self" excludes this service from the list. Critical for contacting peers.
179 public void setSelf(final String hostname, final int port) {
185 public static void setCreatorSelf(final String hostname, final int port) {
186 if(locatorCreator!=null) {
187 locatorCreator.setSelf(hostname,port);
191 protected final synchronized void replace(List<EP> list) {
196 * Call _refresh as needed during calls, but actual refresh will not occur if there
197 * are existing entities or if it has been called in the last 10 (settable) seconds.
198 * Timed Refreshes happen by Scheduled Thread
200 private final boolean _refresh() {
202 long now=System.currentTimeMillis();
205 synchronized(epList) {
207 earliest = now + refreshWait; // call only up to 10 seconds.
210 access.log(Level.ERROR, "Must wait at least " + refreshWait/1000 + " seconds for Locator Refresh");
216 private boolean noEntries() {
217 return epList.size()<=0;
221 public URI get(Item item) throws LocatorException {
224 } else if(item instanceof AAFLItem) {
225 return getURI(((AAFLItem)item).uri);
227 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
232 public boolean hasItems() {
233 boolean isEmpty = epList.isEmpty();
235 for(Iterator<EP> iter = epList.iterator(); iter.hasNext(); ) {
243 if(_refresh()) { // is refreshed... check again
244 isEmpty = epList.isEmpty();
250 public void invalidate(Item item) throws LocatorException {
252 if(item instanceof AAFLItem) {
253 AAFLItem ali =(AAFLItem)item;
255 synchronized(epList) {
259 ali.iter = getIterator(); // for next guy... fresh iterator
261 throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator");
267 public Item best() throws LocatorException {
269 throw new LocatorException("No Entries found for '" + aaf_locator_uri.toString() + "/locate/" + name + ':' + version + '\'');
271 List<EP> lep = new ArrayList<>();
273 // Note: Deque is sorted on the way by closest distance
274 Iterator<EP> iter = getIterator();
276 while(iter.hasNext()) {
283 if(Math.abs(ep.distance-first.distance)<.1) { // allow for nearby/precision issues.
295 return new AAFLItem(iter,first);
297 int rand = sr.nextInt(); // Sonar chokes without.
298 int i = Math.abs(rand)%lep.size();
302 return new AAFLItem(iter,lep.get(i));
308 private Iterator<EP> getIterator() {
309 Object[] epa = epList.toArray();
312 epa = epList.toArray();
314 return new EPIterator(epa, epList);
317 public class EPIterator implements Iterator<EP> {
318 private final Object[] epa;
319 private final List<EP> epList;
322 public EPIterator(Object[] epa, List<EP> epList) {
324 this.epList = epList;
325 idx = epa.length>0?0:-1;
329 public boolean hasNext() {
334 while(idx<epa.length) {
335 if((obj=epa[idx])==null || !((EP)obj).valid) {
341 return idx<epa.length;
348 throw new NoSuchElementException();
350 return (EP)epa[idx++];
354 public void remove() {
355 if(idx>=0 && idx<epa.length) {
356 synchronized(epList) {
357 epList.remove(epa[idx]);
364 public Item first() {
365 Iterator<EP> iter = getIterator();
366 EP ep = AAFLItem.next(iter);
370 return new AAFLItem(iter,ep);
374 public Item next(Item prev) throws LocatorException {
376 StringBuilder sb = new StringBuilder("Locator Item passed in next(item) is null.");
378 for(StackTraceElement st : Thread.currentThread().getStackTrace()) {
380 sb.append(st.toString());
382 sb.append("\n\t...");
386 access.log(Level.ERROR, sb);
388 if(prev instanceof AAFLItem) {
389 AAFLItem ali = (AAFLItem)prev;
390 EP ep = AAFLItem.next(ali.iter);
392 return new AAFLItem(ali.iter,ep);
395 throw new LocatorException(prev.getClass().getName() + " does not belong to AAFLocator");
401 protected static class AAFLItem implements Item {
402 private Iterator<EP> iter;
406 public AAFLItem(Iterator<EP> iter, EP ep) {
412 private static EP next(Iterator<EP> iter) {
414 while(iter.hasNext() && (ep==null || !ep.valid)) {
420 public String toString() {
421 return ep==null?"Locator Item Invalid":ep.toString();
425 protected static class EP implements Comparable<EP> {
427 public final double distance;
428 private boolean valid;
430 public EP(final Endpoint ep, double latitude, double longitude) throws URISyntaxException {
431 uri = new URI(ep.getProtocol(),null,ep.getHostname(),ep.getPort(),null,null,null);
432 distance = GreatCircle.calc(latitude, longitude, ep.getLatitude(), ep.getLongitude());
436 public void invalid() {
441 public int compareTo(EP o) {
442 if(distance<o.distance) {
444 } else if(distance>o.distance) {
452 public String toString() {
453 return distance + ": " + uri + (valid?" valid":" invalidate");
458 * @see org.onap.aaf.cadi.Locator#destroy()
461 public void destroy() {
466 public String toString() {
467 return "AAFLocator for " + name + " on " + getURI();
470 public AbsAAFLocator<TRANS> setPathInfo(String pathInfo) {
471 this.pathInfo = pathInfo;
476 public AbsAAFLocator<TRANS> setQuery(String query) {
482 public AbsAAFLocator<TRANS> setFragment(String fragment) {
483 this.fragment = fragment;
488 // Core URI, for reporting purposes
489 protected abstract URI getURI();
491 protected URI getURI(URI rv) throws LocatorException {
494 return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment);
495 } catch (URISyntaxException e) {
496 throw new LocatorException("Error copying URL");