2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
7 * Modifications Copyright (c) 2019 Samsung
8 * ===================================================================
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
15 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
28 * https://creativecommons.org/licenses/by/4.0/
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.
36 * ============LICENSE_END============================================
41 package org.onap.portal.scheduler.scheduleraux;
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;
74 public class SchedulerAuxRestInterface {
77 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class);
80 private static Client client = null;
82 /** The common headers. */
83 private MultivaluedHashMap<String, Object> commonHeaders;
85 public SchedulerAuxRestInterface() {
91 private final ObjectMapper mapper = new ObjectMapper();
94 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
95 GsonBuilder builder = new GsonBuilder();
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());
105 gson = builder.create();
108 public void initRestClient() {
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);
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)));
131 if (client == null) {
134 client = HttpBasicClient.getClient();
135 } catch (Exception e) {
136 logger.debug(EELFLoggerDelegate.debugLogger, " Unable to get the SSL client", methodname);
142 @SuppressWarnings("unchecked")
143 public <T> void Get(T t, String sourceId, String path, RestObject<T> restObject) throws Exception {
144 String methodName = "Get";
146 logger.debug(EELFLoggerDelegate.debugLogger, " start", methodName);
147 SimpleDateFormat dateFormat = DateUtil.getDateFormat();
152 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
153 logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url: ", dateFormat.format(new Date()),
158 final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get();
160 int status = cres.getStatus();
161 restObject.setStatusCode(status);
164 t = (T) cres.readEntity(t.getClass());
166 logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!",
167 dateFormat.format(new Date()), methodName);
170 throw new Exception(methodName + " with status=" + status + ", url= " + url);
173 logger.debug(EELFLoggerDelegate.debugLogger, " received status", methodName, status);
178 @SuppressWarnings("unchecked")
179 public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) {
181 String methodName = "Delete";
183 Response cres = null;
184 SimpleDateFormat dateFormat = DateUtil.getDateFormat();
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);
193 cres = client.target(url).request().accept("application/json").headers(commonHeaders)
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));
199 int status = cres.getStatus();
200 restObject.setStatusCode(status);
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()),
208 } else if (status == 202) {
209 String msg = "Delete in progress: " + status;
210 logger.debug(EELFLoggerDelegate.debugLogger, "msg ", dateFormat.format(new Date()), msg);
212 String msg = "Deleting Resource failed: " + status;
213 logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg);
217 t = (T) cres.readEntity(t.getClass());
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,
226 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
230 } catch (HttpClientErrorException e) {
231 logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception with the URL", methodName,
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());
244 @SuppressWarnings("unchecked")
245 public <T> void post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject)
246 throws HttpClientErrorException, Exception {
248 String methodName = "Post";
250 Response cres = null;
251 logger.debug(EELFLoggerDelegate.debugLogger, "POST policy rest interface");
252 // logRequest (requestDetails);
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
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));
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);
272 if(t.getClass().getName().equals(String.class.getName())){
276 t = (T) gson.fromJson(str, t.getClass());
279 } catch (Exception e) {
280 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
283 //t = (T) cres.readEntity(t.getClass());
285 restObject.setT(null);
290 int status = cres.getStatus();
292 restObject.setStatusCode(status);
294 if (status >= 200 && status <= 299) {
295 logger.debug(EELFLoggerDelegate.debugLogger, " REST api POST was successful!", methodName);
298 logger.debug(EELFLoggerDelegate.debugLogger, "methodname with Status and URL", methodName, status, url);
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());
316 public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
317 return clazz.newInstance();