3d9470ee9c330475c558f5d35e42e47cdd09cc35
[aaf/cadi.git] / client / src / main / java / org / onap / aaf / cadi / locator / PropertyLocator.java
1 /*******************************************************************************\r
2  * ============LICENSE_START====================================================\r
3  * * org.onap.aaf\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * * \r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * * \r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 package org.onap.aaf.cadi.locator;\r
24 \r
25 import java.io.IOException;\r
26 import java.net.InetAddress;\r
27 import java.net.InetSocketAddress;\r
28 import java.net.Socket;\r
29 import java.net.URI;\r
30 import java.net.URISyntaxException;\r
31 import java.net.UnknownHostException;\r
32 import java.util.ArrayList;\r
33 import java.util.List;\r
34 import java.security.SecureRandom;\r
35 import java.util.Timer;\r
36 import java.util.TimerTask;\r
37 \r
38 import org.onap.aaf.cadi.Locator;\r
39 import org.onap.aaf.cadi.LocatorException;\r
40 \r
41 import org.onap.aaf.inno.env.util.Split;\r
42 \r
43 public class PropertyLocator implements Locator<URI> {\r
44         private final URI [] orig;\r
45         private PLItem[] current;\r
46         private int end;\r
47         private final SecureRandom random;\r
48         private URI[] resolved;\r
49         private long lastRefreshed=0L;\r
50         private long minRefresh;\r
51         private long backgroundRefresh;\r
52 \r
53         public PropertyLocator(String locList) throws LocatorException {\r
54                 this(locList,10000L, 1000*60*20); // defaults, do not refresh more than once in 10 seconds, Refresh Locator every 20 mins.\r
55         }\r
56         /**\r
57          * comma delimited root url list\r
58          * \r
59          * @param locList\r
60          * @throws LocatorException\r
61          */\r
62         public PropertyLocator(String locList, long minRefreshMillis, long backgroundRefreshMillis) throws LocatorException {\r
63                 minRefresh = minRefreshMillis;\r
64                 backgroundRefresh = backgroundRefreshMillis;\r
65                 if(locList==null) {\r
66                         throw new LocatorException("No Location List given for PropertyLocator");\r
67                 }\r
68                 String[] locarray = Split.split(',',locList);\r
69                 List<URI> uriList = new ArrayList<URI>();\r
70                 \r
71                 random = new SecureRandom();\r
72                 \r
73                 for(int i=0;i<locarray.length;++i) {\r
74                         try {\r
75                                 int range = locarray[i].indexOf(":[");\r
76                                 if(range<0) {\r
77                                         uriList.add(new URI(locarray[i]));\r
78                                 } else {\r
79                                         int dash = locarray[i].indexOf('-',range+2);\r
80                                         int brac = locarray[i].indexOf(']',dash+1);\r
81                                         int start = Integer.parseInt(locarray[i].substring(range+2, dash));\r
82                                         int end = Integer.parseInt(locarray[i].substring(dash+1, brac));\r
83                                         for(int port=start;port<=end;++port) {\r
84                                                 uriList.add(new URI(locarray[i].substring(0, range+1)+port));\r
85                                         }\r
86                                 }\r
87                         } catch (NumberFormatException nf) {\r
88                                 throw new LocatorException("Invalid URI format: " + locarray[i]);\r
89                         } catch (URISyntaxException e) {\r
90                                 throw new LocatorException(e);\r
91                         }\r
92                 }\r
93                 orig = new URI[uriList.size()];\r
94                 uriList.toArray(orig);\r
95 \r
96                 refresh();\r
97                 new Timer("PropertyLocator Refresh Timer",true).scheduleAtFixedRate(new TimerTask() {\r
98                         @Override\r
99                         public void run() {\r
100                                 refresh();\r
101                         }\r
102                 }, backgroundRefresh,backgroundRefresh);\r
103 \r
104         }\r
105 \r
106         @Override\r
107         public URI get(Item item) throws LocatorException {\r
108                 synchronized(orig) {\r
109                         if(item==null) {\r
110                                 return null;\r
111                         } else {\r
112                                 return resolved[((PLItem)item).idx];\r
113                         }\r
114                 }\r
115         }\r
116 \r
117         @Override\r
118         public Item first() throws LocatorException {\r
119                 return end>0?current[0]:null;\r
120         }\r
121 \r
122         @Override\r
123         public boolean hasItems() {\r
124                 return end>0;\r
125         }\r
126 \r
127         @Override\r
128         public Item next(Item item) throws LocatorException {\r
129                 if(item==null) {\r
130                         return null;\r
131                 } else {\r
132                         int spot;\r
133                         if((spot=(((PLItem)item).order+1))>=end)return null;\r
134                         return current[spot];\r
135                 }\r
136         }\r
137 \r
138         @Override\r
139         public synchronized void invalidate(Item item) throws LocatorException {\r
140                 if(--end<=0) {\r
141                         refresh();\r
142                         return;\r
143                 }\r
144                 PLItem pli = (PLItem)item;\r
145                 int i,order;\r
146                 for(i=0;i<end;++i) {\r
147                         if(pli==current[i])break;\r
148                 }\r
149                 order = current[i].order;\r
150                 for(;i<end;++i) {\r
151                         current[i]=current[i+1];\r
152                         current[i].order=order++;\r
153                 }\r
154                 current[end]=pli;\r
155         }\r
156 \r
157         @Override\r
158         public Item best() throws LocatorException {\r
159                 if(current.length==0) {\r
160                         refresh();\r
161                 }\r
162                 switch(current.length) {\r
163                         case 0:\r
164                                 return null;\r
165                         case 1:\r
166                                 return current[0];\r
167                         default:\r
168                                 return current[Math.abs(random.nextInt())%current.length];\r
169                 }\r
170         }\r
171 \r
172         @Override\r
173         public synchronized boolean refresh() {\r
174                 if(System.currentTimeMillis()>lastRefreshed) {\r
175                         // Build up list\r
176                         List<URI> resolve = new ArrayList<URI>();\r
177                         String realname;\r
178                         for(int i = 0; i < orig.length ; ++i) {\r
179                                 try {\r
180                                         InetAddress ia[] = InetAddress.getAllByName(orig[i].getHost());\r
181 \r
182                                         URI o,n;\r
183                                         for(int j=0;j<ia.length;++j) {\r
184                                                 o = orig[i];\r
185                                                 Socket socket = new Socket();\r
186                                                 try {\r
187                                                         realname=ia[j].getCanonicalHostName();\r
188                                                         socket.connect(new InetSocketAddress(realname,o.getPort()),3000);\r
189                                                         if(socket.isConnected()) {\r
190                                                                 n = new URI(\r
191                                                                                 o.getScheme(),\r
192                                                                                 o.getUserInfo(),\r
193                                                                                 realname,\r
194                                                                                 o.getPort(),\r
195                                                                                 o.getPath(),\r
196                                                                                 o.getQuery(),\r
197                                                                                 o.getFragment()\r
198                                                                                 );\r
199                                                                 resolve.add(n);\r
200                                                         }\r
201                                                 } catch (IOException e) {\r
202                                                 } finally {\r
203                                                         if(!socket.isClosed()) {\r
204                                                                 try {\r
205                                                                         socket.close();\r
206                                                                 } catch (IOException e) {\r
207                                                                         // nothing to do.\r
208                                                                 }\r
209                                                         }\r
210                                                 }\r
211                                         }\r
212                                 } catch (UnknownHostException | URISyntaxException e) {\r
213                                         // Note: Orig Name already known as valid, based on constructor\r
214                                 }\r
215                         }\r
216                         end=resolve.size();\r
217                         PLItem[] newCurrent;\r
218                         if(current==null || current.length!=end) {\r
219                                 newCurrent = new PLItem[end];\r
220                         } else {\r
221                                 newCurrent = current;\r
222                         }\r
223         \r
224                         for(int i=0; i< end; ++i) {\r
225                                 if(newCurrent[i]==null){\r
226                                         newCurrent[i]=new PLItem(i);\r
227                                 } else {\r
228                                         newCurrent[i].idx=newCurrent[i].order=i;\r
229                                 }\r
230                         }\r
231                         synchronized(orig) {\r
232                                 resolved = new URI[end];\r
233                                 resolve.toArray(resolved);\r
234                                 current = newCurrent;\r
235                         }\r
236                         lastRefreshed = System.currentTimeMillis()+minRefresh;\r
237                         return !resolve.isEmpty();\r
238                 } else {\r
239                         return false;\r
240                 }\r
241         }\r
242         \r
243         private class PLItem implements Item {\r
244                 public int idx,order;\r
245                 \r
246                 public PLItem(int i) {\r
247                         idx = order =i;\r
248                 }\r
249                 \r
250                 public String toString() {\r
251                         return "Item: " + idx + " order: " + order;\r
252                 }\r
253         }\r
254 \r
255         public String toString() {\r
256                 StringBuilder sb = new StringBuilder();\r
257                 boolean first = true;\r
258                 for(URI uri : orig) {\r
259                         boolean isResolved=false;\r
260                         if(uri!=null) {\r
261                                 if(first) {\r
262                                         first = false;\r
263                                 } else {\r
264                                         sb.append(", ");\r
265                                 }\r
266                                 sb.append(uri.toString());\r
267                                 sb.append(" [");\r
268                                 for(URI u2 : resolved) {\r
269                                         if(uri.equals(u2)) {\r
270                                                 isResolved = true;\r
271                                                 break;\r
272                                         }\r
273                                 }\r
274                                 sb.append(isResolved?"X]\n":" ]");\r
275                         }\r
276                 }\r
277                 return sb.toString();\r
278         }\r
279         \r
280         public void destroy() {\r
281         }\r
282 }\r