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