Bulk upload changes and music health check apis
[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  * 
37  */
38 package org.onap.portalapp.portal.scheduleraux;
39
40 import java.lang.reflect.Type;
41 import java.text.DateFormat;
42 import java.text.SimpleDateFormat;
43 import java.util.Collections;
44 import java.util.Date;
45
46 import javax.annotation.PostConstruct;
47 import javax.ws.rs.client.Client;
48 import javax.ws.rs.client.Entity;
49 import javax.ws.rs.core.MediaType;
50 import javax.ws.rs.core.MultivaluedHashMap;
51 import javax.ws.rs.core.Response;
52
53 import org.apache.commons.codec.binary.Base64;
54 import org.apache.cxf.jaxrs.impl.ResponseImpl;
55 import org.eclipse.jetty.util.security.Password;
56 import org.json.simple.JSONObject;
57 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
58 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
59 import org.onap.portalapp.portal.scheduler.SchedulerProperties;
60 import org.onap.portalapp.portal.scheduler.client.HttpBasicClient;
61 import org.onap.portalapp.portal.scheduler.policy.rest.RequestDetails;
62 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
63 import org.springframework.http.HttpStatus;
64 import org.springframework.web.client.HttpClientErrorException;
65
66 import com.fasterxml.jackson.databind.ObjectMapper;
67 import com.google.gson.Gson;
68 import com.google.gson.GsonBuilder;
69 import com.google.gson.JsonDeserializationContext;
70 import com.google.gson.JsonDeserializer;
71 import com.google.gson.JsonElement;
72 import com.google.gson.JsonParseException;
73
74 public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements SchedulerAuxRestInterfaceIfc {
75
76         /** The logger. */
77         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class);
78
79         /** The Constant dateFormat. */
80         final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
81
82         /** The client. */
83         private static Client client = null;
84
85         /** The common headers. */
86         private MultivaluedHashMap<String, Object> commonHeaders;
87
88         public SchedulerAuxRestInterface() {
89                 super();
90         }
91
92         Gson gson = null;
93
94         private final ObjectMapper mapper = new ObjectMapper();
95
96         private void init() {
97                 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
98                 GsonBuilder builder = new GsonBuilder();
99
100                 // Register an adapter to manage the date types as long values
101                 builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
102                         public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
103                                         throws JsonParseException {
104                                 return new Date(json.getAsJsonPrimitive().getAsLong());
105                         }
106                 });
107
108                 gson = builder.create();
109         }
110         
111         public void initRestClient() {
112                 init();
113                 final String methodname = "initRestClient()";
114                 final String mechId = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_MECHID_VAL);
115                 final String clientPassword = SchedulerProperties
116                                 .getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_PASSWORD_VAL);
117                 final String username = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_USERNAME_VAL);
118                 final String password = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_PASSWORD_VAL);
119                 final String environment = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_ENVIRONMENT_VAL);
120                 final String clientAuth = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENTAUTH_VAL);
121                 final String decrypted_client_password = Password.deobfuscate(clientPassword);
122                 String mechAuthString = mechId + ":" + decrypted_client_password;
123                 byte[] mechAuthEncBytes = Base64.encodeBase64(mechAuthString.getBytes());
124                 final String decrypted_password = Password.deobfuscate(password);
125                 String authString = username + ":" + decrypted_password;
126                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
127                 String authorization = new String(authEncBytes);
128
129                 commonHeaders = new MultivaluedHashMap<String, Object>();
130                 commonHeaders.put("ClientAuth", Collections.singletonList((Object) ("Basic " + clientAuth)));
131                 commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authorization)));
132                 commonHeaders.put("Environment", Collections.singletonList((Object) (environment)));
133
134                 if (client == null) {
135
136                         try {
137                                 client = HttpBasicClient.getClient();
138                         } catch (Exception e) {
139                                 logger.debug(EELFLoggerDelegate.debugLogger, " Unable to get the SSL client", methodname);
140
141                         }
142                 }
143         }
144
145         @SuppressWarnings("unchecked")
146         public <T> void Get(T t, String sourceId, String path, RestObject<T> restObject) throws Exception {
147                 String methodName = "Get";
148
149                 logger.debug(EELFLoggerDelegate.debugLogger, " start", methodName);
150
151                 String url = "";
152                 restObject.set(t);
153
154                 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
155                 logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url: ", dateFormat.format(new Date()),
156                                 methodName, url);
157
158                 initRestClient();
159
160                 final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get();
161
162                 int status = cres.getStatus();
163                 restObject.setStatusCode(status);
164
165                 if (status == 200) {
166                         t = (T) cres.readEntity(t.getClass());
167                         restObject.set(t);
168                         logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!", dateFormat.format(new Date()),
169                                         methodName);
170
171                 } else {
172                         throw new Exception(methodName + " with status=" + status + ", url= " + url);
173                 }
174
175                 logger.debug(EELFLoggerDelegate.debugLogger, " received status", methodName, status);
176
177                 return;
178         }
179
180         @SuppressWarnings("unchecked")
181         public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) {
182
183                 String methodName = "Delete";
184                 String url = "";
185                 Response cres = null;
186
187                 logRequest(r);
188
189                 try {
190                         initRestClient();
191
192                         url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
193                         logger.debug(EELFLoggerDelegate.debugLogger, " methodName sending request to: ",
194                                         dateFormat.format(new Date()), url, methodName);
195
196                         cres = client.target(url).request().accept("application/json").headers(commonHeaders)
197                                         // .entity(r)
198                                         .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke();
199                         // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
200                         // .delete(Entity.entity(r, MediaType.APPLICATION_JSON));
201
202                         int status = cres.getStatus();
203                         restObject.setStatusCode(status);
204
205                         if (status == 404) { // resource not found
206                                 String msg = "Resource does not exist...: " + cres.getStatus();
207                                 logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg);
208                         } else if (status == 200 || status == 204) {
209                                 logger.debug(EELFLoggerDelegate.debugLogger, "Resource--deleted:url", dateFormat.format(new Date()),
210                                                 url);
211                         } else if (status == 202) {
212                                 String msg = "Delete in progress: " + status;
213                                 logger.debug(EELFLoggerDelegate.debugLogger, "msg ", dateFormat.format(new Date()), msg);
214                         } else {
215                                 String msg = "Deleting Resource failed: " + status;
216                                 logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg);
217                         }
218
219                         try {
220                                 t = (T) cres.readEntity(t.getClass());
221                                 restObject.set(t);
222                         } catch (HttpClientErrorException e) {
223                                 logger.error(EELFLoggerDelegate.errorLogger,
224                                                 " HttpClientErrorException:No response entity, this is probably ok, e=", methodName, e);
225                                 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
226                         } catch (Exception e) {
227                                 logger.error(EELFLoggerDelegate.errorLogger, "No response entity, this is probably ok, e=", methodName,
228                                                 e);
229                                 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
230
231                         }
232
233                 } catch (HttpClientErrorException e) {
234                         logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception with the URL", methodName,
235                                         url, e);
236                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
237                 } catch (Exception e) {
238                         logger.error(EELFLoggerDelegate.errorLogger, "Exception with the URL ", dateFormat.format(new Date()),
239                                         methodName, url, e);
240                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
241
242                         throw e;
243
244                 }
245         }
246
247         @SuppressWarnings("unchecked")
248         public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject)
249                         throws HttpClientErrorException, Exception {
250
251                 String methodName = "Post";
252                 String url = "";
253                 Response cres = null;
254                 logger.debug(EELFLoggerDelegate.debugLogger, "POST policy rest interface");
255                 // logRequest (requestDetails);
256                 try {
257
258                         initRestClient();
259
260                         url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
261                         logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url= ", methodName, url);
262                         // Change the content length
263
264                         cres = client.target(url).request().accept("application/json").headers(commonHeaders)
265                                         // .header("content-length", 201)
266                                         // .header("X-FromAppId", sourceID)
267                                         .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
268
269                         /* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code, 
270                         but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which 
271                         doesn't work as expected. Created Portal-253 for tracking */
272                         String str = ((ResponseImpl)cres).readEntity(String.class);
273                         
274                         try {
275                                 if(t.getClass().getName().equals(String.class.getName())){
276                                         t=(T) str;
277                                         
278                                 }else{
279                                         t = (T) gson.fromJson(str, t.getClass());
280                                 }
281                                 
282                         } catch (Exception e) {
283                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
284                         }
285                         
286                         //t = (T) cres.readEntity(t.getClass());
287                         if (t.equals("")) {
288                                 restObject.set(null);
289                         } else {
290                                 restObject.set(t);
291                         }
292
293                         int status = cres.getStatus();
294
295                         restObject.setStatusCode(status);
296
297                         if (status >= 200 && status <= 299) {
298                                 logger.debug(EELFLoggerDelegate.debugLogger, " REST api POST was successful!", methodName);
299
300                         } else {
301                                 logger.debug(EELFLoggerDelegate.debugLogger, "methodname with Status and URL", methodName, status, url);
302                         }
303
304                 } catch (HttpClientErrorException e) {
305                         String message = String.format(
306                                         " HttpClientErrorException:Exception with the URL . MethodName: %s, Url: %s", methodName,url);
307                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
308                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
309                 } catch (Exception e) {
310                         String message = String.format(
311                                         " Exception with the URL . MethodName: %s, Url: %s", methodName,url);
312                         logger.error(EELFLoggerDelegate.errorLogger, message, e);                       
313                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.BAD_REQUEST.value());
314                         throw e;
315
316                 }
317         }
318
319         public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
320                 return clazz.newInstance();
321         }
322
323         @Override
324         public void logRequest(RequestDetails r) {
325                 // TODO Auto-generated method stub
326         }
327 }