2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.scheduleraux;
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;
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;
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;
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;
74 public class SchedulerAuxRestInterface extends SchedulerAuxRestInt implements SchedulerAuxRestInterfaceIfc {
77 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerAuxRestInterface.class);
79 /** The Constant dateFormat. */
80 final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
83 private static Client client = null;
85 /** The common headers. */
86 private MultivaluedHashMap<String, Object> commonHeaders;
88 public SchedulerAuxRestInterface() {
94 private final ObjectMapper mapper = new ObjectMapper();
97 logger.debug(EELFLoggerDelegate.debugLogger, "initializing");
98 GsonBuilder builder = new GsonBuilder();
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());
108 gson = builder.create();
111 public void initRestClient() {
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);
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)));
134 if (client == null) {
137 client = HttpBasicClient.getClient();
138 } catch (Exception e) {
139 logger.debug(EELFLoggerDelegate.debugLogger, " Unable to get the SSL client", methodname);
145 @SuppressWarnings("unchecked")
146 public <T> void Get(T t, String sourceId, String path, RestObject<T> restObject) throws Exception {
147 String methodName = "Get";
149 logger.debug(EELFLoggerDelegate.debugLogger, " start", methodName);
154 url = SchedulerProperties.getProperty(SchedulerProperties.SCHEDULERAUX_SERVER_URL_VAL) + path;
155 logger.debug(EELFLoggerDelegate.debugLogger, " sending request to url: ", dateFormat.format(new Date()),
160 final Response cres = client.target(url).request().accept("application/json").headers(commonHeaders).get();
162 int status = cres.getStatus();
163 restObject.setStatusCode(status);
166 t = (T) cres.readEntity(t.getClass());
168 logger.debug(EELFLoggerDelegate.debugLogger, " REST api was successfull!", dateFormat.format(new Date()),
172 throw new Exception(methodName + " with status=" + status + ", url= " + url);
175 logger.debug(EELFLoggerDelegate.debugLogger, " received status", methodName, status);
180 @SuppressWarnings("unchecked")
181 public <T> void Delete(T t, RequestDetails r, String sourceID, String path, RestObject<T> restObject) {
183 String methodName = "Delete";
185 Response cres = null;
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);
196 cres = client.target(url).request().accept("application/json").headers(commonHeaders)
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));
202 int status = cres.getStatus();
203 restObject.setStatusCode(status);
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()),
211 } else if (status == 202) {
212 String msg = "Delete in progress: " + status;
213 logger.debug(EELFLoggerDelegate.debugLogger, "msg ", dateFormat.format(new Date()), msg);
215 String msg = "Deleting Resource failed: " + status;
216 logger.debug(EELFLoggerDelegate.debugLogger, "msg", dateFormat.format(new Date()), msg);
220 t = (T) cres.readEntity(t.getClass());
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,
229 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
233 } catch (HttpClientErrorException e) {
234 logger.error(EELFLoggerDelegate.errorLogger, " HttpClientErrorException:Exception with the URL", methodName,
236 EPLogUtil.schedulerAccessAlarm(logger, e.getStatusCode().value());
237 } catch (Exception e) {
238 logger.error(EELFLoggerDelegate.errorLogger, "Exception with the URL ", dateFormat.format(new Date()),
240 EPLogUtil.schedulerAccessAlarm(logger, HttpStatus.INTERNAL_SERVER_ERROR.value());
247 @SuppressWarnings("unchecked")
248 public <T> void Post(T t, JSONObject requestDetails, String uuid, String path, RestObject<T> restObject)
249 throws HttpClientErrorException, Exception {
251 String methodName = "Post";
253 Response cres = null;
254 logger.debug(EELFLoggerDelegate.debugLogger, "POST policy rest interface");
255 // logRequest (requestDetails);
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
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));
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);
275 if(t.getClass().getName().equals(String.class.getName())){
279 t = (T) gson.fromJson(str, t.getClass());
282 } catch (Exception e) {
283 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInvalidJsonInput, e);
286 //t = (T) cres.readEntity(t.getClass());
288 restObject.set(null);
293 int status = cres.getStatus();
295 restObject.setStatusCode(status);
297 if (status >= 200 && status <= 299) {
298 logger.debug(EELFLoggerDelegate.debugLogger, " REST api POST was successful!", methodName);
301 logger.debug(EELFLoggerDelegate.debugLogger, "methodname with Status and URL", methodName, status, url);
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());
319 public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
320 return clazz.newInstance();
324 public void logRequest(RequestDetails r) {
325 // TODO Auto-generated method stub