Bulk upload changes and music health check apis
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / scheduler / SchedulerRestInterface.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.scheduler;
39
40 import java.util.Collections;
41
42 import javax.security.auth.login.CredentialException;
43 import javax.ws.rs.client.Client;
44 import javax.ws.rs.client.Entity;
45 import javax.ws.rs.core.MediaType;
46 import javax.ws.rs.core.MultivaluedHashMap;
47 import javax.ws.rs.core.Response;
48
49 import org.apache.commons.codec.binary.Base64;
50 import org.apache.commons.lang.StringUtils;
51 import org.eclipse.jetty.util.security.Password;
52 import org.json.simple.JSONObject;
53 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
54 import org.onap.portalapp.portal.scheduler.client.HttpBasicClient;
55 import org.onap.portalapp.portal.scheduler.client.HttpsBasicClient;
56 import org.onap.portalapp.portal.scheduler.restobjects.RestObject;
57 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
58 import org.springframework.http.HttpStatus;
59 import org.springframework.stereotype.Service;
60 import org.springframework.web.client.HttpClientErrorException;
61
62 @Service
63 public class SchedulerRestInterface implements SchedulerRestInterfaceIfc {
64
65         private static final String PASSWORD_IS_EMPTY = "Password is Empty";
66
67         private static Client client = null;
68
69         private MultivaluedHashMap<String, Object> commonHeaders;
70
71         /** The logger. */
72         static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class);
73
74         public SchedulerRestInterface() {
75                 super();
76         }
77
78         public void initRestClient() {
79                 logger.debug(EELFLoggerDelegate.debugLogger, "Starting to initialize rest client");
80
81                 final String username;
82                 final String password;
83
84                 String methodName = "initRestClient";
85                 /* Setting user name based on properties */
86                 String retrievedUsername = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_USER_NAME_VAL);
87                 if (retrievedUsername.isEmpty()) {
88                         username = "";
89                 } else {
90                         username = retrievedUsername;
91                 }
92
93                 /* Setting password based on properties */
94                 String retrievedPassword = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_PASSWORD_VAL);
95                 if (retrievedPassword.isEmpty()) {
96                         password = StringUtils.EMPTY;
97                 } else {
98                         if (retrievedPassword.contains("OBF:")) {
99                                 password = Password.deobfuscate(retrievedPassword);
100                         } else {
101                                 password = retrievedPassword;
102                         }
103                 }
104                 try {
105                         if (StringUtils.isBlank(password)) {
106                                 throw new CredentialException(PASSWORD_IS_EMPTY); 
107                         }
108                 } catch (Exception ex) {
109                         logger.error(EELFLoggerDelegate.errorLogger, "Unable to initialize rest client", ex);
110                 }
111                 String authString = username + ":" + password;
112                 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
113                 String authStringEnc = new String(authEncBytes);
114
115                 commonHeaders = new MultivaluedHashMap<String, Object>();
116                 commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authStringEnc)));
117
118                 try {
119                         if (!username.isEmpty()) {
120
121                                 client = HttpBasicClient.getClient();
122                         } else {
123
124                                 client = HttpsBasicClient.getClient();
125                         }
126                 } catch (Exception e) {
127                         logger.debug(EELFLoggerDelegate.debugLogger, "Unable to initialize rest client");
128
129                 }
130                 logger.debug(EELFLoggerDelegate.debugLogger, "Client Initialized");
131
132         }
133
134         @SuppressWarnings("unchecked")
135         public <T> void Get(T t, String sourceId, String path,
136                         org.onap.portalapp.portal.scheduler.restobjects.RestObject<T> restObject) throws Exception {
137
138                 String methodName = "Get";
139                 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
140
141                 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR GET : ", url);
142                 try {
143                         initRestClient();
144
145                         final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get();
146
147                         int status = cres.getStatus();
148                         restObject.setStatusCode(status);
149
150                         t = (T) cres.readEntity(t.getClass());
151                         if (t.equals("")) {
152                                 restObject.set(null);
153                         } else {
154                                 restObject.set(t);
155                         }
156                 } catch (HttpClientErrorException e) {
157                         String message = String.format(
158                                         " HttpClientErrorException: Exception For the POST  . MethodName: %s, Url: %s", methodName,url);
159                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
160                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
161                 } catch (Exception e) {
162                         String message = String.format(
163                                         "Exception For the POST . MethodName: %s, Url: %s", methodName,url);
164
165                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
166                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
167
168                         throw e;
169
170                 }
171
172         }
173
174         @SuppressWarnings("unchecked")
175         public <T> void Post(T t, JSONObject requestDetails, String path, RestObject<T> restObject) throws Exception {
176
177                 String methodName = "Post";
178                 String url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
179                 logger.debug(EELFLoggerDelegate.debugLogger, "URL FOR POST : "+ url);
180
181                 try {
182
183                         initRestClient();
184
185                         // Change the content length
186                         final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders)
187                                         .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
188
189                         if (cres.getEntity() != null) {
190                                 t = (T) cres.readEntity(t.getClass());
191                                 restObject.set(t);
192                         } else {
193                                 t = null;
194                                 restObject.set(t);
195                         }
196
197                         int status = cres.getStatus();
198                         restObject.setStatusCode(status);
199
200                         if (status >= 200 && status <= 299) {
201                                 String message = String.format(
202                                                 " REST api POST was successful!", methodName);
203                                 logger.debug(EELFLoggerDelegate.debugLogger, message);
204
205                         } else {
206                                 String message = String.format(
207                                                 " FAILED with http status  . MethodName: %s, Status: %s, Url: %s", methodName,status,url);
208                                 logger.debug(EELFLoggerDelegate.debugLogger, message);
209                         }
210
211                 } catch (HttpClientErrorException e) {
212                         String message = String.format(
213                                         " HttpClientErrorException: Exception For the POST  . MethodName: %s, Url: %s", methodName,url);
214                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
215                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
216                 } catch (Exception e) {
217                         String message = String.format(
218                                         " HttpClientErrorException: Exception For the POST  . MethodName: %s, Url: %s", methodName,url);
219                         logger.error(EELFLoggerDelegate.errorLogger, message, e);
220                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
221                         throw e;
222                 }
223         }
224
225         @Override
226         public void logRequest(JSONObject requestDetails) {
227         }
228
229         @SuppressWarnings("unchecked")
230         public <T> void Delete(T t, JSONObject requestDetails, String sourceID, String path, RestObject<T> restObject) {
231
232                 String methodName = "Delete";
233                 String url = "";
234                 Response cres = null;
235
236                 try {
237                         initRestClient();
238
239                         url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULER_SERVER_URL_VAL) + path;
240
241                         cres = client.target(url).request().accept("application/json").headers(commonHeaders)
242                                         // .entity(r)
243                                         .build("DELETE", Entity.entity(requestDetails, MediaType.APPLICATION_JSON)).invoke();
244                         // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
245                         // .delete(Entity.entity(r, MediaType.APPLICATION_JSON));
246
247                         int status = cres.getStatus();
248                         restObject.setStatusCode(status);
249                         if (cres.getEntity() != null) {
250                                 t = (T) cres.readEntity(t.getClass());
251                                 restObject.set(t);
252                         }
253
254                 } catch (HttpClientErrorException e) {
255                         logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception For the Delete",
256                                         methodName, url, e);
257                         EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
258                 } catch (Exception e) {
259                         logger.error(EELFLoggerDelegate.errorLogger, "Exception For the Delete", methodName, url, e);
260                         EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
261                         throw e;
262                 }
263         }
264
265         public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
266                 return clazz.newInstance();
267         }
268
269 }