2 * ================================================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ================================================================================
20 package org.openecomp.portalsdk.core.restful.client;
23 import java.util.HashMap;
24 import java.util.List;
26 import org.apache.http.client.utils.URIBuilder;
27 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
28 import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants;
29 import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties;
30 import org.openecomp.portalsdk.core.restful.domain.SharedContext;
31 import org.openecomp.portalsdk.core.util.SystemProperties;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.stereotype.Component;
35 import com.fasterxml.jackson.core.JsonParseException;
36 import com.fasterxml.jackson.core.JsonProcessingException;
37 import com.fasterxml.jackson.core.type.TypeReference;
38 import com.fasterxml.jackson.databind.JsonMappingException;
39 import com.fasterxml.jackson.databind.ObjectMapper;
42 * Provides convenience methods to use the shared-context service at Portal.
43 * This hides all JSON; instead it accepts and returns Java objects. Usage
44 * caveats (repeated from superclass):
46 * <LI>Must be auto-wired by Spring, because this in turn auto-wires a data
47 * access service to read application credentials from the FN_APP table.
48 * <LI>If HTTP access is used and the server uses a self-signed certificate, the
49 * local trust store must be extended appropriately. The HTTP client throws
50 * exceptions if the JVM cannot validate the server certificate.
54 public class SharedContextRestClient extends PortalRestClientBase {
57 SystemProperties systemProperties;
59 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestClient.class);
62 * Reusable JSON (de)serializer
64 private final ObjectMapper mapper = new ObjectMapper();
67 * Builds the URl for the shared context service using the portal.properties
68 * value for the AUXAPI endpoint.
71 * if the ECOMP_REST_URL property is not found
73 private String getSharedContextUrl() throws Exception {
74 String restUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
75 if (restUrl == null || restUrl.length() == 0)
76 throw new Exception("getSharedContextUrl: no property " + PortalApiConstants.ECOMP_REST_URL);
77 String contextUrl = restUrl + (restUrl.endsWith("/") ? "" : "/") + "context/";
82 * Gets the shared-context value for the specified context ID and key.
85 * An Ecomp Portal session ID
87 * Key for the shared-context entry; e.g., "lastName"
88 * @return SharedContext object; null if not found.
91 public SharedContext getContextValue(String contextId, String key) throws Exception {
92 HttpStatusAndResponse hsr = getContext("get", contextId, key);
93 logger.info(EELFLoggerDelegate.debugLogger, "getSharedContext: resp is " + hsr);
95 logger.error(EELFLoggerDelegate.applicationLogger, "getContextValue: unexpected null response");
98 SharedContext jsonObj = null;
100 jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
101 } catch (JsonMappingException ex) {
102 logger.error(EELFLoggerDelegate.applicationLogger,
103 "getContextValue: failed to map response onto object" + ex.getMessage());
104 } catch (JsonParseException ex) {
105 logger.info(EELFLoggerDelegate.applicationLogger,
106 "getContextValue: failed to parse response" + ex.getMessage());
108 if (jsonObj != null && jsonObj.getResponse() != null)
114 * Gets user information for the specified context ID.
117 * An Ecomp Portal session ID
118 * @return List of SharedContext objects corresponding to the following
119 * keys: USER_FIRST_NAME, USER_LAST_NAME, USER_EMAIL and
120 * USER_ORGUSERID; empty if none were found; null if an error
124 public List<SharedContext> getUserContext(String contextId) throws Exception {
125 HttpStatusAndResponse hsr = getContext("get_user", contextId, null);
126 logger.info(EELFLoggerDelegate.debugLogger, "getUserContext: resp is " + hsr);
128 logger.error(EELFLoggerDelegate.applicationLogger, "getUserContext: unexpected null response");
131 List<SharedContext> jsonList = null;
133 TypeReference<List<SharedContext>> typeRef = new TypeReference<List<SharedContext>>() {
135 jsonList = mapper.readValue(hsr.getResponse(), typeRef);
136 } catch (JsonMappingException ex) {
137 logger.error(EELFLoggerDelegate.applicationLogger,
138 "getUserContext: failed to map response onto object" + ex.getMessage());
139 } catch (JsonParseException ex) {
140 logger.error(EELFLoggerDelegate.applicationLogger,
141 "getUserContext: failed to parse response" + ex.getMessage());
147 * Checks whether a shared-context entry exists for the specified context ID
151 * An Ecomp Portal session ID
153 * Key for the shared-context entry; e.g., "lastName"
154 * @return True if the object exists, false otherwise; null on error.
157 public Boolean checkSharedContext(String contextId, String key) throws Exception {
158 HttpStatusAndResponse hsr = getContext("check", contextId, key);
159 logger.info(EELFLoggerDelegate.debugLogger, "checkSharedContext: resp is " + hsr);
161 logger.error(EELFLoggerDelegate.applicationLogger, "checkSharedContext: unexpected null response");
164 String response = null;
166 SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
167 response = jsonObj.getResponse();
168 } catch (JsonMappingException ex) {
169 logger.error(EELFLoggerDelegate.applicationLogger,
170 "checkSharedContext: failed to map response onto object" + ex.getMessage());
171 } catch (JsonParseException ex) {
172 logger.error(EELFLoggerDelegate.applicationLogger,
173 "checkSharedContext: failed to parse response" + ex.getMessage());
175 if (response == null)
177 return ("exists".equals(response));
181 * Removes a shared-context entry with the specified context ID and key.
184 * An Ecomp Portal session ID
186 * Key for the shared-context entry; e.g., "lastName"
187 * @return True if the entry was removed, false otherwise; null on error.
190 public Boolean removeSharedContext(String contextId, String key) throws Exception {
191 HttpStatusAndResponse hsr = getContext("remove", contextId, key);
192 logger.info(EELFLoggerDelegate.debugLogger, "removeSharedContext: resp is " + hsr);
194 logger.error(EELFLoggerDelegate.applicationLogger, "removeSharedContext: unexpected null response");
197 SharedContext jsonObj = null;
199 jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
200 } catch (JsonMappingException ex) {
201 logger.error(EELFLoggerDelegate.applicationLogger,
202 "removeSharedContext: failed to map response onto object" + ex.getMessage());
203 } catch (JsonParseException ex) {
204 logger.error(EELFLoggerDelegate.applicationLogger,
205 "removeSharedContext: failed to parse response" + ex.getMessage());
209 String response = jsonObj.getResponse();
210 return ("removed".equals(response));
214 * Clears the shared context for the specified context ID; i.e., removes all
218 * An Ecomp Portal session ID
219 * @return Number of key-value pairs removed; -1 if not found or any
223 public int clearSharedContext(String contextId) throws Exception {
224 HttpStatusAndResponse hsr = getContext("remove", contextId, null);
225 logger.info(EELFLoggerDelegate.debugLogger, "clearSharedContext: resp is " + hsr);
227 logger.error(EELFLoggerDelegate.applicationLogger, "clearSharedContext: unexpected null response");
230 SharedContext jsonObj = null;
232 jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
233 } catch (JsonMappingException ex) {
234 logger.error(EELFLoggerDelegate.applicationLogger,
235 "clearSharedContext: failed to map response onto object" + ex.getMessage());
236 } catch (JsonParseException ex) {
237 logger.error(EELFLoggerDelegate.applicationLogger,
238 "clearSharedContext: failed to parse response" + ex.getMessage());
242 String response = jsonObj.getResponse();
243 if (response == null)
245 return Integer.parseInt(response);
249 * Creates a shared-context entry.
252 * An Ecomp Portal session ID
254 * Key for the shared-context entry; e.g., "lastName"
256 * Value for the entry
258 * @return True if the object previously existed, false otherwise; null if
259 * any problem happened.
261 public Boolean setSharedContext(String contextId, String key, String value) throws Exception {
262 String body = buildContext(contextId, key, value);
263 HttpStatusAndResponse hsr = postContext("set", body);
264 logger.info(EELFLoggerDelegate.debugLogger, "setSharedContext: resp is " + hsr);
266 logger.error(EELFLoggerDelegate.applicationLogger, "setSharedContext: unexpected null response");
269 SharedContext jsonObj = null;
271 jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
272 } catch (JsonMappingException ex) {
273 logger.error(EELFLoggerDelegate.applicationLogger,
274 "setSharedContext: failed to map response onto object" + ex.getMessage());
275 } catch (JsonParseException ex) {
276 logger.error(EELFLoggerDelegate.applicationLogger,
277 "setSharedContext: failed to parse response" + ex.getMessage());
281 String response = jsonObj.getResponse();
282 return ("replaced".equals(response));
286 * Builds the full URL with the specified parameters, then calls the method
287 * that adds credentials and GETs.
292 * @return HttpStatusAndResponse object; may be null.
295 private HttpStatusAndResponse getContext(String requestPath, String contextId, String contextKey) throws Exception {
296 URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath);
297 uriBuilder.addParameter("context_id", contextId);
298 if (contextKey != null)
299 uriBuilder.addParameter("ckey", contextKey);
300 final URI uri = uriBuilder.build();
301 return getRestWithCredentials(uri);
305 * Builds the full URL, then calls the method that adds credentials and
311 * @return HttpStatusAndResponse object; may be null.
314 private HttpStatusAndResponse postContext(String requestPath, String json) throws Exception {
315 URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath);
316 URI uri = uriBuilder.build();
317 return postRestWithCredentials(uri, json);
321 * Builds a JSON block with a single shared-context entry.
331 private String buildContext(String cxid, String ckey, String cvalue) throws JsonProcessingException {
332 ObjectMapper mapper = new ObjectMapper();
333 HashMap<String, String> stringMap = new HashMap<String, String>();
334 stringMap.put("context_id", cxid);
335 stringMap.put("ckey", ckey);
336 stringMap.put("cvalue", cvalue);
337 String json = mapper.writeValueAsString(stringMap);
341 // Simple test scaffold
342 public static void main(String[] args) throws Exception {
343 // ObjectMapper mapper = new ObjectMapper();
344 // SharedContext cxt = mapper.readValue("{ \"response\":\"foo\" }",
345 // SharedContext.class);
346 SharedContextRestClient client = new SharedContextRestClient();
347 SharedContext get = client.getContextValue("abc", "123");
348 System.out.println("Get yields " + get.toString());