bf0fa5153cd0fcd88253bf266d55b6bbadb7426b
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / scheduleraux / SchedulerAuxRestInterface.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.onap.portalapp.portal.scheduleraux;
39
40 import java.text.DateFormat;
41 import java.text.SimpleDateFormat;
42 import java.util.Collections;
43 import java.util.Date;
44
45 import javax.ws.rs.client.Client;
46 import javax.ws.rs.client.Entity;
47 import javax.ws.rs.core.MediaType;
48 import javax.ws.rs.core.MultivaluedHashMap;
49 import javax.ws.rs.core.Response;
50
51 import org.apache.commons.codec.binary.Base64;
52 import org.eclipse.jetty.util.security.Password;
53 import org.json.simple.JSONObject;
54 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
55 import org.onap.portalapp.portal.scheduler.SchedulerProperties;
56 import org.onap.portalapp.portal.scheduler.client.HttpBasicClient;
57 import org.onap.portalapp.portal.scheduler.policy.rest.RequestDetails;
58 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
59 import org.springframework.http.HttpStatus;
60 import org.springframework.web.client.HttpClientErrorException;
61
62 public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements SchedulerAuxRestInterfaceIfc {
63
64         /** The logger. */
65         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class);
66
67         /** The Constant dateFormat. */
68         final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
69
70         /** The client. */
71         private static Client client = null;
72
73         /** The common headers. */
74         private MultivaluedHashMap<String, Object> commonHeaders;
75
76         public SchedulerAuxRestInterface() {
77                 super();
78         }
79
80         public void initRestClient() {
81                 final String methodname = "initRestClient()";
82                 final String mechId = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_MECHID_VAL);
83                 final String clientPassword = SchedulerProperties
84                                 .getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_PASSWORD_VAL);
85                 final String username = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_USERNAME_VAL);
86                 final String password = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_PASSWORD_VAL);
87                 final String environment = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_ENVIRONMENT_VAL);
88                 final String clientAuth = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENTAUTH_VAL);
89                 final String decrypted_client_password = Password.deobfuscate(clientPassword);
90                 String mechAuthString = mechId + ":" + decrypted_client_password;
91                 byte[] mechAuthEncBytes = Base64.encodeBase64(mechAuthString.getBytes());
92                 final String decrypted_password = Password.deobfuscate(password);
93                 String authString = username + ":" + decrypted_password;
94                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
95                 String authorization = new String(authEncBytes);
96
97                 commonHeaders = new MultivaluedHashMap<String, Object>();
98                 commonHeaders.put("ClientAuth", Collections.singletonList((Object) ("Basic " + clientAuth)));
99                 commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authorization)));
100                 commonHeaders.put("Environment", Collections.singletonList((Object) (environment)));
101
102                 if (client == null) {
103
104                         try {
105                                 client = HttpBasicClient.getClient();
106                         } catch (Exception e) {
107                                 logger.debug(EELFLoggerDelegate.debugLogger, " Unable to get the SSL client", methodname);
108
109                         }
110                 }
111         }
112
113         @SuppressWarnings("unchecked")
114         public <T> void Get(T t, String sourceId, String path, RestObject<T> restObject) throws Exception {
115                 String methodName = "Get";
116
117                 logger.debug(EELFLoggerDelegate.debugLogger, " start", methodName);
118
119                 String url = "";
120                 restObject.set(t);
121
122                 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
123                 logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url: ", dateFormat.format(new Date()),
124                                 methodName, url);
125
126                 initRestClient();
127
128                 final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get();
129
130                 int status = cres.getStatus();
131                 restObject.setStatusCode(status);
132
133                 if (status == 200) {
134                         t = (T) cres.readEntity(t.getClass());
135                         restObject.set(t);
136                         logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!", dateFormat.format(new Date()),
137                                         methodName);
138
139                 } else {
140                         throw new Exception(methodName + " with status=" + status + ", url= " + url);
141                 }
142
143                 logger.debug(EELFLoggerDelegate.debugLogger, " received status", methodName, status);
144
145                 return;
146         }
147
148         @SuppressWarnings("unchecked")
149         public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) {
150
151                 String methodName = "Delete";
152                 String url = "";
153                 Response cres = null;
154
155                 logRequest(r);
156
157                 try {
158                         initRestClient();
159
160                         url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
161                         logger.debug(EELFLoggerDelegate.debugLogger, " methodName sending request to: ",
162                                         dateFormat.format(new Date()), url, methodName);
163
164                         cres = client.target(url).request().accept("application/json").headers(commonHeaders)
165                                         // .entity(r)
166                                         .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke();
167                         // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
168                         // .delete(Entity.entity(r, MediaType.APPLICATION_JSON));
169
170                         int status = cres.getStatus();
171                         restObject.setStatusCode(status);
172
173                         if (status == 404) { // resource not found
174                                 String msg = "Resource does not exist...: " + cres.getStatus();
175                                 logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg);
176                         } else if (status == 200 || status == 204) {
177                                 logger.debug(EELFLoggerDelegate.debugLogger, "Resource--deleted:url", dateFormat.format(new Date()),
178                                                 url);
179                         } else if (status == 202) {
180                                 String msg = "Delete in progress: " + status;
181                                 logger.debug(EELFLoggerDelegate.debugLogger, "msg ", dateFormat.format(new Date()), msg);
182                         } else {
183                                 String msg = "Deleting Resource failed: " + status;
184                                 logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg);
185                         }
186
187                         try {
188                                 t = (T) cres.readEntity(t.getClass());
189                                 restObject.set(t);
190                         } catch (HttpClientErrorException e) {
191                                 logger.error(EELFLoggerDelegate.errorLogger,
192                                                 " HttpClientErrorException:No response entity, this is probably ok, e=", methodName, e);
193                                 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
194                         } catch (Exception e) {
195                                 logger.error(EELFLoggerDelegate.errorLogger, "No response entity, this is probably ok, e=", methodName,
196                                                 e);
197                                 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
198
199                         }
200
201                 } catch (HttpClientErrorException e) {
202                         logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception with the URL", methodName,
203                                         url, e);
204                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
205                 } catch (Exception e) {
206                         logger.error(EELFLoggerDelegate.errorLogger, "Exception with the URL ", dateFormat.format(new Date()),
207                                         methodName, url, e);
208                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
209
210                         throw e;
211
212                 }
213         }
214
215         @SuppressWarnings("unchecked")
216         public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject)
217                         throws HttpClientErrorException, Exception {
218
219                 String methodName = "Post";
220                 String url = "";
221                 Response cres = null;
222                 logger.debug(EELFLoggerDelegate.debugLogger, "POST policy rest interface");
223                 // logRequest (requestDetails);
224                 try {
225
226                         initRestClient();
227
228                         url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
229                         logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url= ", methodName, url);
230                         // Change the content length
231
232                         cres = client.target(url).request().accept("application/json").headers(commonHeaders)
233                                         // .header("content-length", 201)
234                                         // .header("X-FromAppId", sourceID)
235                                         .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
236
237                         t = (T) cres.readEntity(t.getClass());
238                         if (t.equals("")) {
239                                 restObject.set(null);
240                         } else {
241                                 restObject.set(t);
242                         }
243
244                         int status = cres.getStatus();
245
246                         restObject.setStatusCode(status);
247
248                         if (status >= 200 && status <= 299) {
249                                 logger.debug(EELFLoggerDelegate.debugLogger, " REST api POST was successful!", methodName);
250
251                         } else {
252                                 logger.debug(EELFLoggerDelegate.debugLogger, "methodname with Status and URL", methodName, status, url);
253                         }
254
255                 } catch (HttpClientErrorException e) {
256                         String message = String.format(
257                                         " HttpClientErrorException:Exception with the URL . MethodName: %s, Url: %s", methodName,url);
258                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
259                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
260                 } catch (Exception e) {
261                         String message = String.format(
262                                         " Exception with the URL . MethodName: %s, Url: %s", methodName,url);
263                         logger.error(EELFLoggerDelegate.errorLogger, message, e);                       
264                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.BAD_REQUEST.value());
265                         throw e;
266
267                 }
268         }
269
270         public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
271                 return clazz.newInstance();
272         }
273
274         @Override
275         public void logRequest(RequestDetails r) {
276                 // TODO Auto-generated method stub
277         }
278 }