summaryrefslogtreecommitdiffstats
path: root/client/src/main/java/org/onap/aaf/cadi/locator
diff options
context:
space:
mode:
Diffstat (limited to 'client/src/main/java/org/onap/aaf/cadi/locator')
-rw-r--r--client/src/main/java/org/onap/aaf/cadi/locator/DME2Locator.java347
-rw-r--r--client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java163
-rw-r--r--client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java61
-rw-r--r--client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java304
-rw-r--r--client/src/main/java/org/onap/aaf/cadi/locator/PropertyLocator.java282
5 files changed, 1157 insertions, 0 deletions
diff --git a/client/src/main/java/org/onap/aaf/cadi/locator/DME2Locator.java b/client/src/main/java/org/onap/aaf/cadi/locator/DME2Locator.java
new file mode 100644
index 0000000..656fd19
--- /dev/null
+++ b/client/src/main/java/org/onap/aaf/cadi/locator/DME2Locator.java
@@ -0,0 +1,347 @@
+/*******************************************************************************
+ * ============LICENSE_START====================================================
+ * * org.onap.aaf
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ * * ============LICENSE_END====================================================
+ * *
+ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * *
+ ******************************************************************************/
+package org.onap.aaf.cadi.locator;
+
+
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Properties;
+import java.util.Random;
+
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.Locator;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.aaf.cadi.Access.Level;
+
+import java.security.SecureRandom;
+
+//import com.att.aft.dme2.api.DME2Endpoint;
+import com.att.aft.dme2.api.DME2Exception;
+import com.att.aft.dme2.api.DME2Manager;
+import com.att.aft.dme2.api.DME2Server;
+import com.att.aft.dme2.manager.registry.DME2Endpoint;
+
+public class DME2Locator implements Locator<URI> {
+ private DME2Manager dm;
+ private DME2Endpoint[] endpoints;
+ private Access access;
+ private String service;
+ private String version;
+ private String routeOffer;
+ private String envContext;
+ private String thisMachine;
+ private String pathInfo;
+ private int thisPort;
+ private boolean removeSelf;
+ private final static SecureRandom random = new SecureRandom();
+
+ // Default is to not bother trying to remove self
+ public DME2Locator(Access access, DME2Manager dm, String service, String version, String envContext, String routeOffer) throws DME2Exception, UnknownHostException, LocatorException {
+ this(access,dm,service,version,envContext,routeOffer,false);
+ }
+
+ public DME2Locator(Access access, DME2Manager dm, String service, String version, String envContext, String routeOffer, boolean removeSelf) throws DME2Exception, UnknownHostException, LocatorException {
+ this.access = access;
+ if(dm==null) {
+ this.dm = new DME2Manager("DME2Locator created DME2Manager",System.getProperties());
+ } else {
+ this.dm = dm;
+ }
+ this.service = service;
+ this.version = version;
+ this.envContext = envContext;
+ this.routeOffer = routeOffer;
+ refresh();
+ if(thisMachine==null) {
+ // Can't get from dm...
+ thisMachine = InetAddress.getLocalHost().getHostName();
+ thisPort = 0;
+ } else {
+ thisPort = dm.getPort();
+ }
+
+ this.removeSelf = removeSelf;
+ }
+
+ // Default is to not bother trying to remove self
+ public DME2Locator(Access access, DME2Manager dm, String aafurl) throws DME2Exception, UnknownHostException, LocatorException {
+ this(access,dm,aafurl,false);
+ }
+
+ public DME2Locator(Access access, DME2Manager dm, String aafurl, boolean removeSelf) throws DME2Exception, UnknownHostException, LocatorException {
+ if(aafurl==null) {
+ throw new LocatorException("URL is null");
+ }
+ this.access = access;
+ if(dm==null) {
+ Properties dprops;
+ if(access instanceof PropAccess) {
+ dprops = ((PropAccess)access).getDME2Properties();
+ } else {
+ dprops = System.getProperties();
+ }
+ dm = this.dm = new DME2Manager("DME2Locator created DME2Manager",dprops);
+ } else {
+ this.dm = dm;
+ }
+ String[] split = aafurl.split("/");
+ StringBuilder sb = new StringBuilder();
+ boolean dme2Entered = false;
+ for(String s : split) {
+ if(s.startsWith("service=")) {
+ this.service = s.substring(8);
+ } else if(s.startsWith("version=")) {
+ this.version = s.substring(8);
+ } else if(s.startsWith("envContext=")) {
+ this.envContext = s.substring(11);
+ } else if(s.startsWith("routeOffer=")) {
+ this.routeOffer = s.substring(11);
+ dme2Entered = true;
+ } else if(dme2Entered) {
+ sb.append('/');
+ sb.append(s);
+ }
+ }
+ pathInfo = sb.toString();
+ thisMachine = dm.getHostname();
+ if(thisMachine==null) {
+ // Can't get from dm...
+ thisMachine = InetAddress.getLocalHost().getHostName();
+ thisPort = 0;
+ } else {
+ thisPort = dm.getPort();
+ }
+ this.removeSelf=removeSelf;
+ refresh();
+ }
+
+ @Override
+ public boolean refresh() {
+ try {
+ dm.refresh();
+ //endpoints = dm.findEndpoints(service, version, envContext, routeOffer, true);
+ if(removeSelf) {
+// for(int i=0;i<endpoints.length;++i) {
+// if(endpoints[i].getPort()==thisPort && endpoints[i].getHost().equals(thisMachine))
+// endpoints[i]=null;
+ }
+ //}
+ //return endpoints.length!=0;
+ } catch (Exception e) {
+ access.log(Level.ERROR, e.getMessage());
+ }
+ return false;
+ }
+
+ private String noEndpointsString() {
+ StringBuilder sb = new StringBuilder("No DME2 Endpoints found for ");
+ sb.append(service);
+ sb.append('/');
+ sb.append(version);
+ sb.append('/');
+ sb.append(envContext);
+ sb.append('/');
+ sb.append(routeOffer);
+ return sb.toString();
+ }
+
+ @Override
+ public URI get(Locator.Item item) throws LocatorException {
+ if(!hasItems())
+ throw new LocatorException(noEndpointsString());
+ if(item == null)
+ return null;
+
+ DME2Item li = ((DME2Item)item);
+ // if URI has been created, use it
+ if(li.uri!=null)return li.uri;
+
+ // URI not created, create it
+// if(li.idx<endpoints.length) {
+// DME2Endpoint de = endpoints[li.idx];
+// if(de!=null) {
+// try {
+// return li.uri=new URI(de.getProtocol().toLowerCase(),null,de.getHost(),de.getPort(),pathInfo,null,null);
+// } catch (URISyntaxException e) {
+// throw new LocatorException(e);
+// }
+// }
+// }
+ return null;
+ }
+
+ @Override
+ public boolean hasItems() {
+ //return endpoints!=null && endpoints.length>0;
+ return true;
+ }
+
+ @Override
+ public void invalidate(Locator.Item item) throws LocatorException {
+ if(item instanceof DME2Item) {
+ int idx = ((DME2Item)item).idx;
+// if(idx<endpoints.length) {
+// DME2Endpoint uhoh = endpoints[idx]; // Sometimes, DME2Endpoint, at least on File system, returns bogus entries.
+// endpoints[idx]=null;
+// boolean noneLeft=true;
+// for(int i=0;i<endpoints.length && noneLeft;++i) {
+// noneLeft = endpoints[i]==null;
+// }
+// if(noneLeft && refresh()) { // make sure DME2 isn't giving us the same invalidated entry...
+// for(int i=0;i<endpoints.length && noneLeft;++i) {
+// DME2Endpoint ep = endpoints[i];
+// if(ep != null &&
+// ep.getHost().equals(uhoh.getHost()) &&
+// ep.getPort()==uhoh.getPort()) {
+// endpoints[i]=null;
+// }
+// }
+// }
+//
+// }
+ }
+ }
+
+ public class DME2Item implements Locator.Item {
+ private final int idx;
+ private URI uri;
+ private DME2Item(int i) {
+ idx = i;
+ uri = null;
+ }
+ }
+
+ @Override
+ public DME2Item best() throws LocatorException {
+ if(!hasItems()) // checks endpoints
+ if(!refresh()) throw new LocatorException("No DME2 Endpoints Available");
+
+ // Some endpoints in Array are null. Need sub array of usable endpoints
+ //int usable[] = new int[endpoints.length];
+ int count=0;
+int[] usable = null;
+ // for(int i=0;i<endpoints.length;++i) {
+// if(endpoints[i]!=null) {
+// usable[count++] = i;
+// }
+// }
+ switch(count) {
+ case 0: refresh(); return null;
+ case 1: return new DME2Item(usable[0]);
+ default:
+ int samemach[] = new int[count];
+ int samecount = 0,closecount=0;
+ // has to be sortable
+ Integer closemach[] = new Integer[count];
+
+ // Analyze for Same Machine or Remote machines
+// for(int i=0;i<count;++i) {
+// DME2Endpoint ep = endpoints[usable[i]];
+// String host = ep.getHost();
+// if(thisMachine.equalsIgnoreCase(host)) {
+// samemach[samecount++] = usable[i];
+// } else {
+// closemach[closecount++] = usable[i];
+// }
+// }
+
+ switch(samecount) {
+ case 0: break;
+ case 1: return new DME2Item(samemach[0]);
+ default: // return randomized is multiple Endpoints on local machine.
+ int i = random.nextInt();
+ return new DME2Item(usable[Math.abs(i%samecount)]);
+ }
+
+ // Analyze for closest remote
+ switch(closecount) {
+ case 0: return null;
+ case 1: return new DME2Item(closemach[0]);
+ default: // return closest machine
+ DoubIndex remote[] = new DoubIndex[closecount];
+ int remotecount = 0;
+ for(int i=0;i<closecount;++i) {
+ //DME2Endpoint de = endpoints[usable[i]];
+ // remote[remotecount++] = new DoubIndex(de.getDistance(),i);
+ }
+ Arrays.sort(remote,new Comparator<DoubIndex> () {
+ @Override
+ public int compare(DoubIndex a, DoubIndex b) {
+ if(a.d<b.d) return -1;
+ if(a.d>b.d) return 1;
+ return (random.nextInt()%1)==0?1:0;// randomize if the same
+ }
+
+ });
+ return new DME2Item(remote[0].idx);
+ }
+ }
+ }
+
+ private static class DoubIndex {
+ public final double d;
+ public final int idx;
+
+ public DoubIndex(double doub, int i) {
+ d = doub;
+ idx = i;
+ }
+ }
+ @Override
+ public DME2Item first() {
+// if(endpoints==null)return null;
+// for(int i=0;i<endpoints.length;++i) {
+// if(endpoints[i]!=null)
+// return new DME2Item(i);
+// }
+ return null;
+ }
+
+ @Override
+ public DME2Item next(Locator.Item item) throws LocatorException {
+ //if(endpoints==null || endpoints.length==0 || !(item instanceof DME2Item))return null;
+ int idx = ((DME2Item)item).idx +1;
+// for(int i=idx;i<endpoints.length;++i) {
+// if(endpoints[i]!=null)
+// return new DME2Item(i);
+// }
+// This is a mistake.. will start infinite loops
+// // Did not have any at end... try beginning
+// for(int i=0;i<idx-1;++i) {
+// if(endpoints[i]!=null)
+// return new Item(i);
+// }
+// // If still nothing, refresh
+// refresh();
+ return null;
+ }
+
+ @Override
+ public void destroy() {
+ }
+}
diff --git a/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java b/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java
new file mode 100644
index 0000000..9d420d2
--- /dev/null
+++ b/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java
@@ -0,0 +1,163 @@
+/*******************************************************************************
+ * ============LICENSE_START====================================================
+ * * org.onap.aaf
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ * * ============LICENSE_END====================================================
+ * *
+ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * *
+ ******************************************************************************/
+package org.onap.aaf.cadi.locator;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.Locator;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.Access.Level;
+
+public class DNSLocator implements Locator<URI> {
+ private static enum Status {UNTRIED, OK, INVALID, SLOW};
+ private static final int CHECK_TIME = 3000;
+
+ private String host, protocol;
+ private Access access;
+ private Host[] hosts;
+ private int startPort, endPort;
+ private String suffix;
+
+ public DNSLocator(Access access, String protocol, String host, String range) {
+ this.host = host;
+ this.protocol = protocol;
+ this.access = access;
+ int dash = range.indexOf('-');
+ if(dash<0) {
+ startPort = endPort = Integer.parseInt(range);
+ } else {
+ startPort = Integer.parseInt(range.substring(0,dash));
+ endPort = Integer.parseInt(range.substring(dash + 1));
+ }
+ refresh();
+ }
+
+ @Override
+ public URI get(Item item) throws LocatorException {
+ return hosts[((DLItem)item).cnt].uri;
+ }
+
+ @Override
+ public boolean hasItems() {
+ for(Host h : hosts) {
+ if(h.status==Status.OK) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void invalidate(Item item) {
+ DLItem di = (DLItem)item;
+ hosts[di.cnt].status = Status.INVALID;
+ }
+
+ @Override
+ public Item best() throws LocatorException {
+ // not a good "best"
+ for(int i=0;i<hosts.length;++i) {
+ switch(hosts[i].status) {
+ case OK:
+ return new DLItem(i);
+ case INVALID:
+ break;
+ case SLOW:
+ break;
+ case UNTRIED:
+ try {
+ if(hosts[i].ia.isReachable(CHECK_TIME)) {
+ hosts[i].status = Status.OK;
+ return new DLItem(i);
+ }
+ } catch (IOException e) {
+ throw new LocatorException(e);
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ throw new LocatorException("No Available URIs for " + host);
+ }
+
+ @Override
+ public Item first() throws LocatorException {
+ return new DLItem(0);
+ }
+
+ @Override
+ public Item next(Item item) throws LocatorException {
+ DLItem di = (DLItem)item;
+ if(++di.cnt<hosts.length) {
+ return di;
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ public boolean refresh() {
+ try {
+ InetAddress[] ias = InetAddress.getAllByName(host);
+ Host[] temp = new Host[ias.length * (1 + endPort - startPort)];
+ int cnt = -1;
+ for(int j=startPort; j<=endPort; ++j) {
+ for(int i=0;i<ias.length;++i) {
+ temp[++cnt] = new Host(ias[i], j, suffix);
+ }
+ }
+ hosts = temp;
+ return true;
+ } catch (Exception e) {
+ access.log(Level.ERROR, e);
+ }
+ return false;
+ }
+
+ private class Host {
+ private URI uri;
+ private InetAddress ia;
+ private Status status;
+
+ public Host(InetAddress inetAddress, int port, String suffix) throws URISyntaxException {
+ ia = inetAddress;
+ uri = new URI(protocol,null,inetAddress.getHostAddress(),port,suffix,null,null);
+ status = Status.UNTRIED;
+ }
+ }
+
+ private class DLItem implements Item {
+ public DLItem(int i) {
+ cnt = i;
+ }
+
+ private int cnt;
+ }
+
+ public void destroy() {}
+}
diff --git a/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java b/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java
new file mode 100644
index 0000000..0aa69a3
--- /dev/null
+++ b/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * ============LICENSE_START====================================================
+ * * org.onap.aaf
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ * * ============LICENSE_END====================================================
+ * *
+ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * *
+ ******************************************************************************/
+package org.onap.aaf.cadi.locator;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.http.HClient;
+import org.onap.aaf.cadi.http.HX509SS;
+
+public class HClientHotPeerLocator extends HotPeerLocator<HClient> {
+ private final HX509SS ss;
+
+ public HClientHotPeerLocator(Access access, String urlstr, long invalidateTime, String localLatitude,
+ String localLongitude, HX509SS ss) throws LocatorException {
+ super(access, urlstr, invalidateTime, localLatitude, localLongitude);
+
+ this.ss = ss;
+ }
+
+ @Override
+ protected HClient _newClient(String clientInfo) throws LocatorException {
+ try {
+ int idx = clientInfo.indexOf('/');
+ return new HClient(ss,new URI("https://"+(idx<0?clientInfo:clientInfo.substring(0, idx))),3000);
+ } catch (URISyntaxException e) {
+ throw new LocatorException(e);
+ }
+ }
+
+ @Override
+ protected HClient _invalidate(HClient client) {
+ return null;
+ }
+
+ @Override
+ protected void _destroy(HClient client) {
+ }
+}
diff --git a/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java b/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java
new file mode 100644
index 0000000..04d2a28
--- /dev/null
+++ b/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java
@@ -0,0 +1,304 @@
+/*******************************************************************************
+ * ============LICENSE_START====================================================
+ * * org.onap.aaf
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ * * ============LICENSE_END====================================================
+ * *
+ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * *
+ ******************************************************************************/
+package org.onap.aaf.cadi.locator;
+
+import org.onap.aaf.cadi.Access;
+import org.onap.aaf.cadi.Locator;
+import org.onap.aaf.cadi.LocatorException;
+import org.onap.aaf.cadi.Access.Level;
+import org.onap.aaf.cadi.routing.GreatCircle;
+
+import org.onap.aaf.inno.env.util.Split;
+
+/**
+ * This Locator is to handle Hot Peer load protection, when the Servers are
+ * 1) Static
+ * 2) Well known client URL
+ *
+ * The intention is to change traffic over to the Hot Peer, if a server goes down, and reinstate
+ * when it is back up.
+ *
+ * Example of this kind of Service is a MS Certificate Server
+ *
+ *
+ *
+ * @param <CLIENT>
+ */
+public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> {
+ private final String[] urlstrs;
+ private final CLIENT[] clients;
+ private final long[] failures;
+ private final double[] distances;
+ private int preferred;
+ private long invalidateTime;
+ private Thread refreshThread;
+ protected Access access;
+
+ /**
+ * Construct: Expect one or more Strings in the form:
+ * 192.555.112.223:39/38.88087/-77.30122
+ * separated by commas
+ *
+ * @param trans
+ * @param urlstr
+ * @param invalidateTime
+ * @param localLatitude
+ * @param localLongitude
+ * @throws LocatorException
+ */
+ @SuppressWarnings("unchecked")
+ protected HotPeerLocator(Access access, final String urlstr, final long invalidateTime, final String localLatitude, final String localLongitude) throws LocatorException {
+ this.access = access;
+ urlstrs = Split.split(',', urlstr);
+ clients = (CLIENT[])new Object[urlstrs.length];
+ failures = new long[urlstrs.length];
+ distances= new double[urlstrs.length];
+ this.invalidateTime = invalidateTime;
+
+ double distance = Double.MAX_VALUE;
+ for(int i=0;i<urlstrs.length;++i) {
+ String[] info = Split.split('/', urlstrs[i]);
+ if(info.length<3) {
+ throw new LocatorException("Configuration needs LAT and LONG, i.e. ip:port/lat/long");
+ }
+ try {
+ clients[i] = _newClient(urlstrs[i]);
+ failures[i] = 0L;
+ } catch(LocatorException le) {
+ failures[i] = System.currentTimeMillis()+invalidateTime;
+ }
+
+ double d = GreatCircle.calc(info[1],info[2],localLatitude,localLongitude);
+ distances[i]=d;
+
+ // find preferred server
+ if(d<distance) {
+ preferred = i;
+ distance=d;
+ }
+ }
+
+ access.printf(Level.INIT,"Preferred Client is %s",urlstrs[preferred]);
+ for(int i=0;i<urlstrs.length;++i) {
+ if(i!=preferred) {
+ access.printf(Level.INIT,"Alternate Client is %s",urlstrs[i]);
+ }
+ }
+ }
+
+ protected abstract CLIENT _newClient(String hostInfo) throws LocatorException;
+ /**
+ * If client can reconnect, then return. Otherwise, destroy and return null;
+ * @param client
+ * @return
+ * @throws LocatorException
+ */
+ protected abstract CLIENT _invalidate(CLIENT client);
+
+ protected abstract void _destroy(CLIENT client);
+
+ @Override
+ public Item best() throws LocatorException {
+ if(failures[preferred]==0L) {
+ return new HPItem(preferred);
+ } else {
+ long now = System.currentTimeMillis();
+ double d = Double.MAX_VALUE;
+ int best = -1;
+ boolean tickle = false;
+ // try for best existing client
+ for(int i=0;i<urlstrs.length;++i) {
+ if(failures[i]<now && distances[i]<d) {
+ if(clients[i]!=null) {
+ best = i;
+ break;
+ } else {
+ tickle = true; // There's some failed clients which can be restored
+ }
+ }
+ }
+ if(best<0 && tickle) {
+ tickle=false;
+ if(refresh()) {
+ // try again
+ for(int i=0;i<urlstrs.length;++i) {
+ if(failures[i]==0L && distances[i]<d) {
+ if(clients[i]!=null) {
+ best = i;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ /*
+ * If a valid client is available, but there are some that can refresh, return the client immediately
+ * but start a Thread to do the background Client setup.
+ */
+ if(tickle) {
+ synchronized(clients) {
+ if(refreshThread==null) {
+ refreshThread = new Thread(new Runnable(){
+ @Override
+ public void run() {
+ refresh();
+ refreshThread = null;
+ }
+ });
+ refreshThread.setDaemon(true);
+ refreshThread.start();
+ }
+ }
+ }
+
+ if(best<0) {
+ throw new LocatorException("No Clients available");
+ }
+
+
+ return new HPItem(best);
+ }
+ }
+
+
+ @Override
+ public CLIENT get(Item item) throws LocatorException {
+ HPItem hpi = (HPItem)item;
+ CLIENT c = clients[hpi.idx];
+ if(c==null) {
+ if(failures[hpi.idx]>System.currentTimeMillis()) {
+ throw new LocatorException("Client requested is invalid");
+ } else {
+ synchronized(clients) {
+ c = _newClient(urlstrs[hpi.idx]);
+ failures[hpi.idx]=0L;
+ }
+ }
+ } else if(failures[hpi.idx]>0){
+ throw new LocatorException("Client requested is invalid");
+ }
+ return c;
+ }
+
+ public String info(Item item) {
+ HPItem hpi = (HPItem)item;
+ if(hpi!=null && hpi.idx<urlstrs.length) {
+ return urlstrs[hpi.idx];
+ } else {
+ return "Invalid Item";
+ }
+ }
+
+ @Override
+ public boolean hasItems() {
+ for(int i=0;i<clients.length;++i) {
+ if(clients[i]!=null && failures[i]==0L) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public synchronized void invalidate(Item item) throws LocatorException {
+ HPItem hpi = (HPItem)item;
+ failures[hpi.idx] = System.currentTimeMillis() + invalidateTime;
+ CLIENT c = clients[hpi.idx];
+ clients[hpi.idx] = _invalidate(c);
+ }
+
+ @Override
+ public Item first() throws LocatorException {
+ return new HPItem(0);
+ }
+
+ @Override
+ public Item next(Item item) throws LocatorException {
+ HPItem hpi = (HPItem)item;
+ if(++hpi.idx>=clients.length) {
+ return null;
+ }
+ return hpi;
+ }
+
+ @Override
+ public boolean refresh() {
+ boolean force = !hasItems(); // If no Items at all, reset
+ boolean rv = true;
+ long now = System.currentTimeMillis();
+ for(int i=0;i<clients.length;++i) {
+ if(failures[i]>0L && (failures[i]<now || force)) { // retry
+ try {
+ synchronized(clients) {
+ if(clients[i]==null) {
+ clients[i]=_newClient(urlstrs[i]);
+ }
+ failures[i]=0L;
+ }
+ } catch (LocatorException e) {
+ failures[i]=now+invalidateTime;
+ rv = false;
+ }
+ }
+ }
+ return rv;
+ }
+
+ @Override
+ public void destroy() {
+ for(int i=0;i<clients.length;++i) {
+ if(clients[i]!=null) {
+ _destroy(clients[i]);
+ clients[i] = null;
+ }
+ }
+ }
+
+ private static class HPItem implements Item {
+ private int idx;
+
+ public HPItem(int i) {
+ idx = i;
+ }
+ }
+
+
+ /*
+ * Convenience Functions
+ */
+ public CLIENT bestClient() throws LocatorException {
+ return get(best());
+ }
+
+ public boolean invalidate(CLIENT client) throws LocatorException {
+ for(int i=0;i<clients.length;++i) {
+ if(clients[i]==client) { // yes, "==" is appropriate here.. Comparing Java Object Reference
+ invalidate(new HPItem(i));
+ return true;
+ }
+ }
+ return false;
+ }
+
+ }
diff --git a/client/src/main/java/org/onap/aaf/cadi/locator/PropertyLocator.java b/client/src/main/java/org/onap/aaf/cadi/locator/PropertyLocator.java
new file mode 100644
index 0000000..3d9470e
--- /dev/null
+++ b/client/src/main/java/org/onap/aaf/cadi/locator/PropertyLocator.java
@@ -0,0 +1,282 @@
+/*******************************************************************************
+ * ============LICENSE_START====================================================
+ * * org.onap.aaf
+ * * ===========================================================================
+ * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * * ===========================================================================
+ * * Licensed under the Apache License, Version 2.0 (the "License");
+ * * you may not use this file except in compliance with the License.
+ * * You may obtain a copy of the License at
+ * *
+ * * http://www.apache.org/licenses/LICENSE-2.0
+ * *
+ * * Unless required by applicable law or agreed to in writing, software
+ * * distributed under the License is distributed on an "AS IS" BASIS,
+ * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * * See the License for the specific language governing permissions and
+ * * limitations under the License.
+ * * ============LICENSE_END====================================================
+ * *
+ * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ * *
+ ******************************************************************************/
+package org.onap.aaf.cadi.locator;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+import java.security.SecureRandom;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import org.onap.aaf.cadi.Locator;
+import org.onap.aaf.cadi.LocatorException;
+
+import org.onap.aaf.inno.env.util.Split;
+
+public class PropertyLocator implements Locator<URI> {
+ private final URI [] orig;
+ private PLItem[] current;
+ private int end;
+ private final SecureRandom random;
+ private URI[] resolved;
+ private long lastRefreshed=0L;
+ private long minRefresh;
+ private long backgroundRefresh;
+
+ public PropertyLocator(String locList) throws LocatorException {
+ this(locList,10000L, 1000*60*20); // defaults, do not refresh more than once in 10 seconds, Refresh Locator every 20 mins.
+ }
+ /**
+ * comma delimited root url list
+ *
+ * @param locList
+ * @throws LocatorException
+ */
+ public PropertyLocator(String locList, long minRefreshMillis, long backgroundRefreshMillis) throws LocatorException {
+ minRefresh = minRefreshMillis;
+ backgroundRefresh = backgroundRefreshMillis;
+ if(locList==null) {
+ throw new LocatorException("No Location List given for PropertyLocator");
+ }
+ String[] locarray = Split.split(',',locList);
+ List<URI> uriList = new ArrayList<URI>();
+
+ random = new SecureRandom();
+
+ for(int i=0;i<locarray.length;++i) {
+ try {
+ int range = locarray[i].indexOf(":[");
+ if(range<0) {
+ uriList.add(new URI(locarray[i]));
+ } else {
+ int dash = locarray[i].indexOf('-',range+2);
+ int brac = locarray[i].indexOf(']',dash+1);
+ int start = Integer.parseInt(locarray[i].substring(range+2, dash));
+ int end = Integer.parseInt(locarray[i].substring(dash+1, brac));
+ for(int port=start;port<=end;++port) {
+ uriList.add(new URI(locarray[i].substring(0, range+1)+port));
+ }
+ }
+ } catch (NumberFormatException nf) {
+ throw new LocatorException("Invalid URI format: " + locarray[i]);
+ } catch (URISyntaxException e) {
+ throw new LocatorException(e);
+ }
+ }
+ orig = new URI[uriList.size()];
+ uriList.toArray(orig);
+
+ refresh();
+ new Timer("PropertyLocator Refresh Timer",true).scheduleAtFixedRate(new TimerTask() {
+ @Override
+ public void run() {
+ refresh();
+ }
+ }, backgroundRefresh,backgroundRefresh);
+
+ }
+
+ @Override
+ public URI get(Item item) throws LocatorException {
+ synchronized(orig) {
+ if(item==null) {
+ return null;
+ } else {
+ return resolved[((PLItem)item).idx];
+ }
+ }
+ }
+
+ @Override
+ public Item first() throws LocatorException {
+ return end>0?current[0]:null;
+ }
+
+ @Override
+ public boolean hasItems() {
+ return end>0;
+ }
+
+ @Override
+ public Item next(Item item) throws LocatorException {
+ if(item==null) {
+ return null;
+ } else {
+ int spot;
+ if((spot=(((PLItem)item).order+1))>=end)return null;
+ return current[spot];
+ }
+ }
+
+ @Override
+ public synchronized void invalidate(Item item) throws LocatorException {
+ if(--end<=0) {
+ refresh();
+ return;
+ }
+ PLItem pli = (PLItem)item;
+ int i,order;
+ for(i=0;i<end;++i) {
+ if(pli==current[i])break;
+ }
+ order = current[i].order;
+ for(;i<end;++i) {
+ current[i]=current[i+1];
+ current[i].order=order++;
+ }
+ current[end]=pli;
+ }
+
+ @Override
+ public Item best() throws LocatorException {
+ if(current.length==0) {
+ refresh();
+ }
+ switch(current.length) {
+ case 0:
+ return null;
+ case 1:
+ return current[0];
+ default:
+ return current[Math.abs(random.nextInt())%current.length];
+ }
+ }
+
+ @Override
+ public synchronized boolean refresh() {
+ if(System.currentTimeMillis()>lastRefreshed) {
+ // Build up list
+ List<URI> resolve = new ArrayList<URI>();
+ String realname;
+ for(int i = 0; i < orig.length ; ++i) {
+ try {
+ InetAddress ia[] = InetAddress.getAllByName(orig[i].getHost());
+
+ URI o,n;
+ for(int j=0;j<ia.length;++j) {
+ o = orig[i];
+ Socket socket = new Socket();
+ try {
+ realname=ia[j].getCanonicalHostName();
+ socket.connect(new InetSocketAddress(realname,o.getPort()),3000);
+ if(socket.isConnected()) {
+ n = new URI(
+ o.getScheme(),
+ o.getUserInfo(),
+ realname,
+ o.getPort(),
+ o.getPath(),
+ o.getQuery(),
+ o.getFragment()
+ );
+ resolve.add(n);
+ }
+ } catch (IOException e) {
+ } finally {
+ if(!socket.isClosed()) {
+ try {
+ socket.close();
+ } catch (IOException e) {
+ // nothing to do.
+ }
+ }
+ }
+ }
+ } catch (UnknownHostException | URISyntaxException e) {
+ // Note: Orig Name already known as valid, based on constructor
+ }
+ }
+ end=resolve.size();
+ PLItem[] newCurrent;
+ if(current==null || current.length!=end) {
+ newCurrent = new PLItem[end];
+ } else {
+ newCurrent = current;
+ }
+
+ for(int i=0; i< end; ++i) {
+ if(newCurrent[i]==null){
+ newCurrent[i]=new PLItem(i);
+ } else {
+ newCurrent[i].idx=newCurrent[i].order=i;
+ }
+ }
+ synchronized(orig) {
+ resolved = new URI[end];
+ resolve.toArray(resolved);
+ current = newCurrent;
+ }
+ lastRefreshed = System.currentTimeMillis()+minRefresh;
+ return !resolve.isEmpty();
+ } else {
+ return false;
+ }
+ }
+
+ private class PLItem implements Item {
+ public int idx,order;
+
+ public PLItem(int i) {
+ idx = order =i;
+ }
+
+ public String toString() {
+ return "Item: " + idx + " order: " + order;
+ }
+ }
+
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ boolean first = true;
+ for(URI uri : orig) {
+ boolean isResolved=false;
+ if(uri!=null) {
+ if(first) {
+ first = false;
+ } else {
+ sb.append(", ");
+ }
+ sb.append(uri.toString());
+ sb.append(" [");
+ for(URI u2 : resolved) {
+ if(uri.equals(u2)) {
+ isResolved = true;
+ break;
+ }
+ }
+ sb.append(isResolved?"X]\n":" ]");
+ }
+ }
+ return sb.toString();
+ }
+
+ public void destroy() {
+ }
+}