2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.sparky.util;
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;
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;
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;
51 * Proxy Client Service
53 * @param endpointConfig the configuration for the endpoints to call
55 public ProxyClient(RestEndpointConfig endpointConfig)
56 throws IOException, RestClientConstructionException {
58 this.endpointConfig = endpointConfig;
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));
67 this.restClient = RestClientFactory.buildClient(endpointConfig);
71 public RestEndpointConfig getEndpointConfig() {
72 return endpointConfig;
75 protected String getBasicAuthenticationCredentials() {
77 String usernameAndPassword = String.join(":", endpointConfig.getBasicAuthUserName(),
78 endpointConfig.getBasicAuthPassword());
79 return "Basic " + java.util.Base64.getEncoder().encodeToString(usernameAndPassword.getBytes());
83 * Method to set common headers
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());
98 * Method to set headers from request
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));
111 this.headers.put("X-DslApiVersion",Arrays.asList("V2"));
115 * Method to get rest client
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;
124 return this.restClient;
129 * Get server string from config
131 * @return the server url as a string
133 public String getServer(RestEndpointConfig epc) {
134 switch (epc.getRestAuthenticationMode()) {
137 return String.format("https://%s:%s", epc.getEndpointIpAddress(),
138 epc.getEndpointServerPort());
141 return String.format("http://%s:%s", epc.getEndpointIpAddress(),
142 epc.getEndpointServerPort());
149 * Get the request body from a request for use on the proxy call
152 * @return the request's body in string form
154 private String getRequestBody(final HttpServletRequest request) {
155 final StringBuilder builder = new StringBuilder();
156 try (BufferedReader reader = request.getReader()) {
157 if (reader == null) {
161 while ((line = reader.readLine()) != null) {
162 builder.append(line);
164 return builder.toString();
165 } catch (final Exception e) {
171 * Get whether the incoming call was a history call or not
174 * @return true or false if it is a history traversal call
176 private Boolean isHistory(String uri){
177 String[] tokens = uri.split("/");
178 return tokens.length >= 3 && tokens[2].equals("history-traversal");
182 * Get whether the incoming call was a aperture call or not
185 * @return true or false if it is a aperture traversal call
187 private Boolean isAperture(String uri){
188 String[] tokens = uri.split("/");
189 return tokens[2].equals("aperture");
194 * Build Url, builds the full url to call
197 * @return the string of the endpoint to call
199 public String buildUrl(HttpServletRequest request) {
200 RestEndpointConfig epc = endpointConfig;
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());
207 return String.format("%s%s", server, uri);
211 * Method to make the get call to proxy
214 * @return the operation result object from the call
216 public OperationResult get(HttpServletRequest request) {
217 OperationResult resp = null;
218 String url = buildUrl(request);
219 this.populateHeadersFromRequest(request);
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);
229 * Method to make the post call to proxy
232 * @return the operation result object from the call
234 public OperationResult post(HttpServletRequest request) {
235 OperationResult resp = null;
236 String url = buildUrl(request);
237 this.populateHeadersFromRequest(request);
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);
248 * Method to make the patch call to proxy
251 * @return the operation result object from the call
253 public OperationResult bulkSingleTransaction(HttpServletRequest request, String attuid) {
254 OperationResult resp = null;
255 Map<String, List<String>> updatedHeaders = this.headers;
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());
263 url = String.format("%s%s", server, uri);
264 this.populateHeadersFromRequest(request);
265 updatedHeaders.put("X-FromAppId", Arrays.asList("AAI-UI-" + attuid));
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);
276 * Method to make the put call to proxy
279 * @return the operation result object from the call
281 public OperationResult put(HttpServletRequest request) {
282 OperationResult resp = null;
283 String url = buildUrl(request);
284 this.populateHeadersFromRequest(request);
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);