4b057d86684ef97078d3c5b6b8c41e9930303f0f
[aai/sparky-be.git] / sparkybe-onap-service / src / main / java / org / onap / aai / sparky / util / ProxyClient.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.sparky.util;
22
23 import org.onap.aai.cl.mdc.MdcContext;
24 import org.onap.aai.restclient.client.OperationResult;
25 import org.onap.aai.restclient.client.RestClient;
26 import org.onap.aai.restclient.enums.RestAuthenticationMode;
27 import org.onap.aai.sparky.dal.rest.RestClientConstructionException;
28 import org.onap.aai.sparky.dal.rest.RestClientFactory;
29 import org.onap.aai.sparky.dal.rest.config.RestEndpointConfig;
30 import org.onap.aai.sparky.util.Encryptor;
31 import org.onap.aai.sparky.viewandinspect.config.SparkyConstants;
32 import org.onap.aai.sparky.exception.ProxyServiceException;
33 import org.slf4j.MDC;
34
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.MultivaluedMap;
37 import javax.servlet.http.HttpServletRequest;
38 import java.io.BufferedReader;
39 import java.io.IOException;
40 import java.util.*;
41
42 public class ProxyClient {
43   private RestEndpointConfig endpointConfig;
44   private RestClient restClient;
45   private RestClient historyRestClient;
46   private RestClient apertureRestClient;
47   private static final String HEADER_AUTHORIZATION = "Authorization";
48   Map<String, List<String>> headers;
49
50   /**
51    * Proxy Client Service
52    *
53    * @param endpointConfig the configuration for the endpoints to call
54    */
55   public ProxyClient(RestEndpointConfig endpointConfig)
56       throws IOException, RestClientConstructionException {
57
58     this.endpointConfig = endpointConfig;
59
60     if (endpointConfig.getRestAuthenticationMode() == RestAuthenticationMode.SSL_BASIC) {
61       String basicAuthPassword = endpointConfig.getBasicAuthPassword();
62       if (basicAuthPassword != null && basicAuthPassword.startsWith("OBF:")) {
63         org.onap.aai.sparky.util.Encryptor enc = new Encryptor();
64         endpointConfig.setBasicAuthPassword(enc.decryptValue(basicAuthPassword));
65       }
66     }
67     this.restClient = RestClientFactory.buildClient(endpointConfig);
68     setHeaders();
69   }
70
71   public RestEndpointConfig getEndpointConfig() {
72     return endpointConfig;
73   }
74
75   protected String getBasicAuthenticationCredentials() {
76
77     String usernameAndPassword = String.join(":", endpointConfig.getBasicAuthUserName(),
78             endpointConfig.getBasicAuthPassword());
79     return "Basic " + java.util.Base64.getEncoder().encodeToString(usernameAndPassword.getBytes());
80   }
81
82   /**
83    * Method to set common headers
84    *
85    */
86   public void setHeaders() {
87     this.headers = new HashMap<>();
88     headers.put("X-FromAppId", Arrays.asList("AAI-UI"));
89     headers.put("X-TransactionId", Arrays.asList(MDC.get(MdcContext.MDC_REQUEST_ID)));
90     //headers.put("X-FromAppId", Arrays.asList(MDC.get(MdcContext.MDC_PARTNER_NAME)));
91     if (endpointConfig.getRestAuthenticationMode() == RestAuthenticationMode.SSL_BASIC) {
92       headers.putIfAbsent(HEADER_AUTHORIZATION, new ArrayList<String>());
93       headers.get(HEADER_AUTHORIZATION).add(getBasicAuthenticationCredentials());
94     }
95   }
96
97   /**
98    * Method to set headers from request
99    *
100    */
101   public void populateHeadersFromRequest(HttpServletRequest request) {
102     List<String> includeList = Arrays.asList("X-DslApiVersion");
103     Enumeration<String> names = request.getHeaderNames();
104     while (names.hasMoreElements()) {
105       String name = names.nextElement();
106       String value = request.getHeader(name);
107       if(includeList.contains(name)) {
108         this.headers.put(name, Arrays.asList(value));
109       }
110     }
111     this.headers.put("X-DslApiVersion",Arrays.asList("V2"));
112   }
113
114   /**
115    * Method to get rest client
116    *
117    */
118   public RestClient getRestClient(HttpServletRequest request) {
119     if(isHistory(request.getRequestURL().substring(request.getRequestURL().lastIndexOf("/proxy") + 6))){
120       return this.historyRestClient;
121     }else if(isAperture(request.getRequestURL().substring(request.getRequestURL().lastIndexOf("/proxy") + 6))) {
122         return this.apertureRestClient;
123     }else{
124       return this.restClient;
125     }
126   }
127
128   /**
129    * Get server string from config
130    *
131    * @return the server url as a string
132    */
133   public String getServer(RestEndpointConfig epc) {
134     switch (epc.getRestAuthenticationMode()) {
135       case SSL_BASIC:
136       case SSL_CERT: {
137         return String.format("https://%s:%s", epc.getEndpointIpAddress(),
138             epc.getEndpointServerPort());
139       }
140       default: {
141         return String.format("http://%s:%s", epc.getEndpointIpAddress(),
142             epc.getEndpointServerPort());
143       }
144     }
145
146   }
147
148   /**
149    * Get the request body from a request for use on the proxy call
150    *
151    * @param request
152    * @return the request's body in string form
153    */
154   private String getRequestBody(final HttpServletRequest request) {
155     final StringBuilder builder = new StringBuilder();
156     try (BufferedReader reader = request.getReader()) {
157       if (reader == null) {
158         return null;
159       }
160       String line;
161       while ((line = reader.readLine()) != null) {
162         builder.append(line);
163       }
164       return builder.toString();
165     } catch (final Exception e) {
166       return null;
167     }
168   }
169
170   /**
171    * Get whether the incoming call was a history call or not
172    *
173    * @param uri
174    * @return true or false if it is a history traversal call
175    */
176   private Boolean isHistory(String uri){
177     String[] tokens = uri.split("/");
178     return tokens.length >= 3 && tokens[2].equals("history-traversal");
179   }
180
181   /**
182    * Get whether the incoming call was a aperture call or not
183    *
184    * @param uri
185    * @return true or false if it is a aperture traversal call
186    */
187   private Boolean isAperture(String uri){
188     String[] tokens = uri.split("/");
189     return tokens[2].equals("aperture");
190   }
191
192
193   /**
194    * Build Url, builds the full url to call
195    *
196    * @param request
197    * @return the string of the endpoint to call
198    */
199   public String buildUrl(HttpServletRequest request) {
200     RestEndpointConfig epc = endpointConfig;
201     String uri =
202         request.getRequestURL().substring(request.getRequestURL().lastIndexOf("/proxy") + 6);
203     String server = getServer(epc);
204     if (request.getQueryString() != null) {
205       uri = String.format("%s?%s", uri, request.getQueryString());
206     }
207     return String.format("%s%s", server, uri);
208   }
209
210   /**
211    * Method to make the get call to proxy
212    *
213    * @param request
214    * @return the operation result object from the call
215    */
216   public OperationResult get(HttpServletRequest request) {
217     OperationResult resp = null;
218     String url = buildUrl(request);
219     this.populateHeadersFromRequest(request);
220     try {
221       resp = (getRestClient(request)).get(url, this.headers, MediaType.APPLICATION_JSON_TYPE);
222     } catch (Exception e) {
223       throw new ProxyServiceException("Exception while processing GET request- " + e);
224     }
225     return resp;
226   }
227
228   /**
229    * Method to make the post call to proxy
230    *
231    * @param request
232    * @return the operation result object from the call
233    */
234   public OperationResult post(HttpServletRequest request) {
235     OperationResult resp = null;
236     String url = buildUrl(request);
237     this.populateHeadersFromRequest(request);
238     try {
239       resp = (getRestClient(request)).post(url, getRequestBody(request), this.headers,
240           MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
241     } catch (Exception e) {
242       throw new ProxyServiceException("Exception while processing POST request- " + e);
243     }
244     return resp;
245   }
246
247   /**
248    * Method to make the patch call to proxy
249    *
250    * @param request
251    * @return the operation result object from the call
252    */
253   public OperationResult bulkSingleTransaction(HttpServletRequest request, String attuid) {
254     OperationResult resp = null;
255     Map<String, List<String>> updatedHeaders = this.headers;
256     String url;
257     RestEndpointConfig epc = endpointConfig;
258     String uri = request.getRequestURL().substring(request.getRequestURL().lastIndexOf("/aai"));
259     String server = getServer(epc);
260     if (request.getQueryString() != null) {
261       uri = String.format("%s?%s", uri, request.getQueryString());
262     }
263     url = String.format("%s%s", server, uri);
264     this.populateHeadersFromRequest(request);
265     updatedHeaders.put("X-FromAppId", Arrays.asList("AAI-UI-" + attuid));
266     try {
267       resp = (getRestClient(request)).post(url, getRequestBody(request), updatedHeaders,
268               MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
269     } catch (Exception e) {
270       throw new ProxyServiceException("Exception while processing PATCH request- " + e);
271     }
272     return resp;
273   }
274
275   /**
276    * Method to make the put call to proxy
277    *
278    * @param request
279    * @return the operation result object from the call
280    */
281   public OperationResult put(HttpServletRequest request) {
282     OperationResult resp = null;
283     String url = buildUrl(request);
284     this.populateHeadersFromRequest(request);
285     try {
286       resp = (getRestClient(request)).put(url, getRequestBody(request), this.headers,
287           MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
288     } catch (Exception e) {
289       throw new ProxyServiceException("Exception while processing PUT request- " + e);
290     }
291     return resp;
292   }
293 }