2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 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============================================
40 package org.onap.portalapp.portal.scheduleraux;
42 import com.fasterxml.jackson.databind.ObjectMapper;
43 import com.google.gson.Gson;
44 import com.google.gson.GsonBuilder;
45 import com.google.gson.JsonDeserializationContext;
46 import com.google.gson.JsonDeserializer;
47 import com.google.gson.JsonElement;
48 import com.google.gson.JsonParseException;
49 import org.apache.commons.codec.binary.Base64;
50 import org.apache.cxf.jaxrs.impl.ResponseImpl;
51 import org.eclipse.jetty.util.security.Password;
52 import org.json.simple.JSONObject;
53 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
54 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
55 import org.onap.portalapp.portal.scheduler.SchedulerProperties;
56 import org.onap.portalapp.portal.scheduler.client.HttpBasicClient;
57 import org.onap.portalapp.portal.scheduler.policy.rest.RequestDetails;
58 import org.onap.portalapp.util.DateUtil;
59 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
60 import org.springframework.http.HttpStatus;
61 import org.springframework.web.client.HttpClientErrorException;
63 import javax.ws.rs.client.Client;
64 import javax.ws.rs.client.Entity;
65 import javax.ws.rs.core.MediaType;
66 import javax.ws.rs.core.MultivaluedHashMap;
67 import javax.ws.rs.core.Response;
68 import java.lang.reflect.Type;
69 import java.text.SimpleDateFormat;
70 import java.util.Collections;
71 import java.util.Date;
73 public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements SchedulerAuxRestInterfaceIfc {
76 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class);
79 private static Client client = null;
81 /** The common headers. */
82 private MultivaluedHashMap<String, Object> commonHeaders;
84 public SchedulerAuxRestInterface() {
90 private final ObjectMapper mapper = new ObjectMapper();
93 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
94 GsonBuilder builder = new GsonBuilder();
96 // Register an adapter to manage the date types as long values
97 builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
98 public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
99 throws JsonParseException {
100 return new Date(json.getAsJsonPrimitive().getAsLong());
104 gson = builder.create();
107 public void initRestClient() {
109 final String methodname = "initRestClient()";
110 final String mechId = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_MECHID_VAL);
111 final String clientPassword = SchedulerProperties
112 .getProperty(SchedulerProperties.SCHEDULERAUX_CLIENT_PASSWORD_VAL);
113 final String username = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_USERNAME_VAL);
114 final String password = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_PASSWORD_VAL);
115 final String environment = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_ENVIRONMENT_VAL);
116 final String clientAuth = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_CLIENTAUTH_VAL);
117 final String decrypted_client_password = Password.deobfuscate(clientPassword);
118 String mechAuthString = mechId + ":" + decrypted_client_password;
119 byte[] mechAuthEncBytes = Base64.encodeBase64(mechAuthString.getBytes());
120 final String decrypted_password = Password.deobfuscate(password);
121 String authString = username + ":" + decrypted_password;
122 byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
123 String authorization = new String(authEncBytes);
125 commonHeaders = new MultivaluedHashMap<String, Object>();
126 commonHeaders.put("ClientAuth", Collections.singletonList((Object) ("Basic " + clientAuth)));
127 commonHeaders.put("Authorization", Collections.singletonList((Object) ("Basic " + authorization)));
128 commonHeaders.put("Environment", Collections.singletonList((Object) (environment)));
130 if (client == null) {
133 client = HttpBasicClient.getClient();
134 } catch (Exception e) {
135 logger.debug(EELFLoggerDelegate.debugLogger, " Unable to get the SSL client", methodname);
141 @SuppressWarnings("unchecked")
142 public <T> void Get(T t, String sourceId, String path, RestObject<T> restObject) throws Exception {
143 String methodName = "Get";
145 logger.debug(EELFLoggerDelegate.debugLogger, " start", methodName);
146 SimpleDateFormat dateFormat = DateUtil.getDateFormat();
151 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
152 logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url: ", dateFormat.format(new Date()),
157 final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get();
159 int status = cres.getStatus();
160 restObject.setStatusCode(status);
163 t = (T) cres.readEntity(t.getClass());
165 logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!",
166 dateFormat.format(new Date()), methodName);
169 throw new Exception(methodName + " with status=" + status + ", url= " + url);
172 logger.debug(EELFLoggerDelegate.debugLogger, " received status", methodName, status);
177 @SuppressWarnings("unchecked")
178 public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) {
180 String methodName = "Delete";
182 Response cres = null;
183 SimpleDateFormat dateFormat = DateUtil.getDateFormat();
190 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
191 logger.debug(EELFLoggerDelegate.debugLogger, " methodName sending request to: ",
192 dateFormat.format(new Date()), url, methodName);
194 cres = client.target(url).request().accept("application/json").headers(commonHeaders)
196 .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)).invoke();
197 // .method("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON));
198 // .delete(Entity.entity(r, MediaType.APPLICATION_JSON));
200 int status = cres.getStatus();
201 restObject.setStatusCode(status);
203 if (status == 404) { // resource not found
204 String msg = "Resource does not exist...: " + cres.getStatus();
205 logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg);
206 } else if (status == 200 || status == 204) {
207 logger.debug(EELFLoggerDelegate.debugLogger, "Resource--deleted:url", dateFormat.format(new Date()),
209 } else if (status == 202) {
210 String msg = "Delete in progress: " + status;
211 logger.debug(EELFLoggerDelegate.debugLogger, "msg ", dateFormat.format(new Date()), msg);
213 String msg = "Deleting Resource failed: " + status;
214 logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg);
218 t = (T) cres.readEntity(t.getClass());
220 } catch (HttpClientErrorException e) {
221 logger.error(EELFLoggerDelegate.errorLogger,
222 " HttpClientErrorException:No response entity, this is probably ok, e=", methodName, e);
223 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
224 } catch (Exception e) {
225 logger.error(EELFLoggerDelegate.errorLogger, "No response entity, this is probably ok, e=", methodName,
227 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
231 } catch (HttpClientErrorException e) {
232 logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception with the URL", methodName,
234 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
235 } catch (Exception e) {
236 logger.error(EELFLoggerDelegate.errorLogger, "Exception with the URL ",
237 dateFormat.format(new Date()), methodName, url, e);
238 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
245 @SuppressWarnings("unchecked")
246 public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject)
247 throws HttpClientErrorException, Exception {
249 String methodName = "Post";
251 Response cres = null;
252 logger.debug(EELFLoggerDelegate.debugLogger, "POST policy rest interface");
253 // logRequest (requestDetails);
258 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
259 logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url= ", methodName, url);
260 // Change the content length
262 cres = client.target(url).request().accept("application/json").headers(commonHeaders)
263 // .header("content-length", 201)
264 // .header("X-FromAppId", sourceID)
265 .post(Entity.entity(requestDetails, MediaType.APPLICATION_JSON));
267 /* It is not recommendable to use the implementation class org.apache.cxf.jaxrs.impl.ResponseImpl in the code,
268 but had to force this in-order to prevent conflict with the ResponseImpl class of Jersey Client which
269 doesn't work as expected. Created Portal-253 for tracking */
270 String str = ((ResponseImpl)cres).readEntity(String.class);
273 if(t.getClass().getName().equals(String.class.getName())){
277 t = (T) gson.fromJson(str, t.getClass());
280 } catch (Exception e) {
281 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
284 //t = (T) cres.readEntity(t.getClass());
286 restObject.set(null);
291 int status = cres.getStatus();
293 restObject.setStatusCode(status);
295 if (status >= 200 && status <= 299) {
296 logger.debug(EELFLoggerDelegate.debugLogger, " REST api POST was successful!", methodName);
299 logger.debug(EELFLoggerDelegate.debugLogger, "methodname with Status and URL", methodName, status, url);
302 } catch (HttpClientErrorException e) {
303 String message = String.format(
304 " HttpClientErrorException:Exception with the URL . MethodName: %s, Url: %s", methodName,url);
305 logger.error(EELFLoggerDelegate.errorLogger, message, e);
306 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
307 } catch (Exception e) {
308 String message = String.format(
309 " Exception with the URL . MethodName: %s, Url: %s", methodName,url);
310 logger.error(EELFLoggerDelegate.errorLogger, message, e);
311 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.BAD_REQUEST.value());
317 public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
318 return clazz.newInstance();
322 public void logRequest(RequestDetails r) {
323 // TODO Auto-generated method stub