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