Update Fixes from testing
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / aaf / v2_0 / AAFLocator.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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====================================================
19  *
20  */
21
22 package org.onap.aaf.cadi.aaf.v2_0;
23
24 import java.net.HttpURLConnection;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.util.Collections;
28 import java.util.LinkedList;
29 import java.util.List;
30
31 import org.onap.aaf.cadi.Access;
32 import org.onap.aaf.cadi.Access.Level;
33 import org.onap.aaf.cadi.CadiException;
34 import org.onap.aaf.cadi.LocatorException;
35 import org.onap.aaf.cadi.SecuritySetter;
36 import org.onap.aaf.cadi.client.Future;
37 import org.onap.aaf.cadi.config.Config;
38 import org.onap.aaf.cadi.config.SecurityInfoC;
39 import org.onap.aaf.cadi.http.HClient;
40 import org.onap.aaf.cadi.locator.DNSLocator;
41 import org.onap.aaf.cadi.util.FixURIinfo;
42 import org.onap.aaf.cadi.util.Split;
43 import org.onap.aaf.misc.env.APIException;
44 import org.onap.aaf.misc.env.Data.TYPE;
45 import org.onap.aaf.misc.env.impl.BasicTrans;
46 import org.onap.aaf.misc.rosetta.env.RosettaDF;
47 import org.onap.aaf.misc.rosetta.env.RosettaEnv;
48
49 import locate.v1_0.Endpoint;
50 import locate.v1_0.Endpoints;
51
52 public class AAFLocator extends AbsAAFLocator<BasicTrans>  {
53     private static RosettaEnv env;
54     private HClient client;
55     private HClient lclient;
56     private RosettaDF<Endpoints> epsDF;
57     private DNSLocator locatorLocator;
58     private Item locatorItem;
59
60
61     public AAFLocator(SecurityInfoC<HttpURLConnection> si, URI locatorURI) throws LocatorException {
62         super(si.access, nameFromLocatorURI(locatorURI), 10000L /* Wait at least 10 seconds between refreshes */);
63         synchronized(sr) {
64             if (env==null) {
65                 env = new RosettaEnv(access.getProperties());
66             }
67         }
68         
69         int connectTimeout = Integer.parseInt(si.access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF));
70         try {
71             String[] path = Split.split('/',locatorURI.getPath());
72             FixURIinfo fui = new FixURIinfo(locatorURI);
73             if ("AAF_LOCATE_URL".equals(fui.getHost())) {
74                 client = createClient(si.defSS, locatorURI, connectTimeout);
75             } else if (path.length>1 && "locate".equals(path[1])) {
76                 StringBuilder sb = new StringBuilder();
77                 for (int i=3;i<path.length;++i) {
78                     sb.append('/');
79                     sb.append(path[i]);
80                 }
81                 setPathInfo(sb.toString());
82                 client = createClient(si.defSS, locatorURI, connectTimeout);
83             } else {
84                 client = new HClient(si.defSS, locatorURI, connectTimeout);
85             }
86             epsDF = env.newDataFactory(Endpoints.class);
87             
88         } catch (APIException /*| URISyntaxException*/ e) {
89             throw new LocatorException(e);
90         }
91         lclient = new HClient(si.defSS, locatorURI, connectTimeout);
92         
93         if(si.access.willLog(Access.Level.DEBUG)) {
94             si.access.log(Access.Level.DEBUG, "Root URI:",client.getURI());
95         }
96         
97         String dnsString;
98         if(locatorURI.getPort()<0) {
99                 dnsString=locatorURI.getScheme() + "://" + locatorURI.getHost();
100         } else {
101                 dnsString=locatorURI.getScheme() + "://" +locatorURI.getHost()+':'+locatorURI.getPort();
102         }
103         if(dnsString.contains("null")) { // for Testing Purposes, mostly.
104                 locatorLocator = null;
105         } else {
106                 locatorLocator = new DNSLocator(access, dnsString);
107                 locatorItem = locatorLocator.best();
108         }
109     }
110
111     private URI locatorFail(URI uri) throws LocatorException, URISyntaxException {
112         locatorLocator.invalidate(locatorItem);
113         locatorItem = locatorLocator.best();
114         URI newURI = locatorLocator.get(locatorItem);
115         return new URI(uri.getScheme(),
116                        uri.getUserInfo(),
117                        newURI.getHost(),
118                        newURI.getPort(),
119                        uri.getPath(),
120                        uri.getQuery(),
121                        uri.getFragment());
122     }
123
124     protected final int maxIters() {
125         return locatorLocator.size();
126     }
127
128
129     @Override
130     public boolean refresh() {
131         try {
132             int max = locatorLocator.size();
133             for(int i=0;i<max;) {
134                 ++i;
135                 try {
136                     lclient.setMethod("GET");
137                     lclient.send();
138                     break;
139                 } catch (APIException connectE) {
140                     Throwable ce = connectE.getCause();
141                     if(ce!=null && ce instanceof java.net.ConnectException && i< maxIters()) {
142                         try {
143                             URI old = client.getURI();
144                             lclient.setURI(locatorFail(old));
145                             access.printf(Level.INFO, "AAF Locator changed from %s to %s",old, lclient.getURI());
146                             continue;
147                         } catch (LocatorException e) {
148                             throw connectE;
149                         }
150                     }
151                     // last one, just throw
152                     throw connectE;
153                 }
154             }
155             Future<Endpoints> fr = lclient.futureRead(epsDF, TYPE.JSON);
156             if (fr.get(lclient.timeout())) {
157                 List<EP> epl = new LinkedList<>();
158                 for (Endpoint endpoint : fr.value.getEndpoint()) {
159                     epl.add(new EP(endpoint,latitude,longitude));
160                 }
161                 
162                 Collections.sort(epl);
163                 replace(epl);
164                 return true;
165             } else {
166                 env.error().printf("Error reading location information from %s: %d %s\n",client.getURI().toString(),fr.code(),fr.body());
167             }
168         } catch (CadiException | URISyntaxException | APIException e) {
169             env.error().log(e,"Error connecting " + client.getURI() + " for location.");
170         }
171         return false;
172     }
173
174     /* (non-Javadoc)
175      * @see org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator#getURI()
176      */
177     @Override
178     protected URI getURI() {
179         return client.getURI();
180     }
181     
182     protected HClient createClient(SecuritySetter<HttpURLConnection> ss, URI uri, int connectTimeout) throws LocatorException {
183         return new HClient(ss, uri, connectTimeout);
184     }
185     
186 }