91f4652a45a51b04114ec58045672233e1956f42
[portal/sdk.git] /
1 /*-
2  * ================================================================================
3  * eCOMP Portal SDK
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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  * ================================================================================
19  */
20 package org.openecomp.portalsdk.core.restful.client;
21
22 import java.net.URI;
23 import java.util.HashMap;
24 import java.util.List;
25
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;
34
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;
40
41 /**
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):
45  * <OL>
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.
51  * </OL>
52  */
53 @Component
54 public class SharedContextRestClient extends PortalRestClientBase {
55
56         @Autowired
57         SystemProperties systemProperties;
58
59         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestClient.class);
60
61         /**
62          * Reusable JSON (de)serializer
63          */
64         private final ObjectMapper mapper = new ObjectMapper();
65
66         /**
67          * Builds the URl for the shared context service using the portal.properties
68          * value for the AUXAPI endpoint.
69          * 
70          * @throws Exception
71          *             if the ECOMP_REST_URL property is not found 
72          */
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/";
78                 return contextUrl;
79         }
80
81         /**
82          * Gets the shared-context value for the specified context ID and key.
83          * 
84          * @param contextId
85          *            An Ecomp Portal session ID
86          * @param key
87          *            Key for the shared-context entry; e.g., "lastName"
88          * @return SharedContext object; null if not found.
89          * @throws Exception
90          */
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);
94                 if (hsr == null) {
95                         logger.error(EELFLoggerDelegate.applicationLogger, "getContextValue: unexpected null response");
96                         return null;
97                 }
98                 SharedContext jsonObj = null;
99                 try {
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());
107                 }
108                 if (jsonObj != null && jsonObj.getResponse() != null)
109                         return null;
110                 return jsonObj;
111         }
112
113         /**
114          * Gets user information for the specified context ID.
115          * 
116          * @param contextId
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
121          *         happens.
122          * @throws Exception
123          */
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);
127                 if (hsr == null) {
128                         logger.error(EELFLoggerDelegate.applicationLogger, "getUserContext: unexpected null response");
129                         return null;
130                 }
131                 List<SharedContext> jsonList = null;
132                 try {
133                         TypeReference<List<SharedContext>> typeRef = new TypeReference<List<SharedContext>>() {
134                         };
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());
142                 }
143                 return jsonList;
144         }
145
146         /**
147          * Checks whether a shared-context entry exists for the specified context ID
148          * and key.
149          * 
150          * @param contextId
151          *            An Ecomp Portal session ID
152          * @param key
153          *            Key for the shared-context entry; e.g., "lastName"
154          * @return True if the object exists, false otherwise; null on error.
155          * @throws Exception
156          */
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);
160                 if (hsr == null) {
161                         logger.error(EELFLoggerDelegate.applicationLogger, "checkSharedContext: unexpected null response");
162                         return null;
163                 }
164                 String response = null;
165                 try {
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());
174                 }
175                 if (response == null)
176                         return null;
177                 return ("exists".equals(response));
178         }
179
180         /**
181          * Removes a shared-context entry with the specified context ID and key.
182          * 
183          * @param contextId
184          *            An Ecomp Portal session ID
185          * @param key
186          *            Key for the shared-context entry; e.g., "lastName"
187          * @return True if the entry was removed, false otherwise; null on error.
188          * @throws Exception
189          */
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);
193                 if (hsr == null) {
194                         logger.error(EELFLoggerDelegate.applicationLogger, "removeSharedContext: unexpected null response");
195                         return null;
196                 }
197                 SharedContext jsonObj = null;
198                 try {
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());
206                 }
207                 if (jsonObj == null)
208                         return null;
209                 String response = jsonObj.getResponse();
210                 return ("removed".equals(response));
211         }
212
213         /**
214          * Clears the shared context for the specified context ID; i.e., removes all
215          * key-value pairs.
216          * 
217          * @param contextId
218          *            An Ecomp Portal session ID
219          * @return Number of key-value pairs removed; -1 if not found or any
220          *         problems occur.
221          * @throws Exception
222          */
223         public int clearSharedContext(String contextId) throws Exception {
224                 HttpStatusAndResponse hsr = getContext("remove", contextId, null);
225                 logger.info(EELFLoggerDelegate.debugLogger, "clearSharedContext: resp is " + hsr);
226                 if (hsr == null) {
227                         logger.error(EELFLoggerDelegate.applicationLogger, "clearSharedContext: unexpected null response");
228                         return -1;
229                 }
230                 SharedContext jsonObj = null;
231                 try {
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());
239                 }
240                 if (jsonObj == null)
241                         return -1;
242                 String response = jsonObj.getResponse();
243                 if (response == null)
244                         return -1;
245                 return Integer.parseInt(response);
246         }
247
248         /**
249          * Creates a shared-context entry.
250          * 
251          * @param contextId
252          *            An Ecomp Portal session ID
253          * @param key
254          *            Key for the shared-context entry; e.g., "lastName"
255          * @param value
256          *            Value for the entry
257          * @throws Exception
258          * @return True if the object previously existed, false otherwise; null if
259          *         any problem happened.
260          */
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);
265                 if (hsr == null) {
266                         logger.error(EELFLoggerDelegate.applicationLogger, "setSharedContext: unexpected null response");
267                         return null;
268                 }
269                 SharedContext jsonObj = null;
270                 try {
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());
278                 }
279                 if (jsonObj == null)
280                         return null;
281                 String response = jsonObj.getResponse();
282                 return ("replaced".equals(response));
283         }
284
285         /**
286          * Builds the full URL with the specified parameters, then calls the method
287          * that adds credentials and GETs.
288          * 
289          * @param requestPath
290          * @param contextId
291          * @param contextKey
292          * @return HttpStatusAndResponse object; may be null.
293          * @throws Exception
294          */
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);
302         }
303
304         /**
305          * Builds the full URL, then calls the method that adds credentials and
306          * POSTs.
307          * 
308          * @param requestPath
309          * @param contextId
310          * @param contextKey
311          * @return HttpStatusAndResponse object; may be null.
312          * @throws Exception
313          */
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);
318         }
319
320         /**
321          * Builds a JSON block with a single shared-context entry.
322          * 
323          * @param cxid
324          *            Context ID
325          * @param ckey
326          *            Context Key
327          * @param cvalue
328          *            Context value
329          * @return JSON block
330          */
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);
338                 return json;
339         }
340
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());
349         }
350
351 }