2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 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============================================
36 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
38 package org.onap.portalsdk.core.restful.client;
40 import java.io.IOException;
42 import java.net.URISyntaxException;
43 import java.util.ArrayList;
44 import java.util.HashMap;
45 import java.util.List;
47 import org.apache.http.client.utils.URIBuilder;
48 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
49 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
50 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
51 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
52 import org.onap.portalsdk.core.restful.domain.SharedContext;
53 import org.springframework.stereotype.Component;
55 import com.fasterxml.jackson.core.JsonProcessingException;
56 import com.fasterxml.jackson.core.type.TypeReference;
57 import com.fasterxml.jackson.databind.ObjectMapper;
60 * Provides convenience methods to use the shared-context service at Portal.
61 * This hides all JSON; instead it accepts and returns Java objects. Usage
62 * caveats (repeated from superclass):
64 * <LI>Must be auto-wired by Spring, because this in turn auto-wires a data
65 * access service to read application credentials from the FN_APP table.
66 * <LI>If HTTP access is used and the server uses a self-signed certificate, the
67 * local trust store must be extended appropriately. The HTTP client throws
68 * exceptions if the JVM cannot validate the server certificate.
72 public class SharedContextRestClient extends PortalRestClientBase {
74 private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SharedContextRestClient.class);
77 * Reusable JSON (de)serializer
79 private final ObjectMapper mapper = new ObjectMapper();
82 * Builds the URl for the shared context service using the portal.properties
83 * value for the AUXAPI endpoint.
85 * @throws IllegalArgumentException
86 * if the ECOMP_REST_URL property is not found
88 private String getSharedContextUrl() throws IllegalArgumentException {
89 String restUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL);
90 if (restUrl == null || restUrl.length() == 0)
91 throw new IllegalArgumentException("getSharedContextUrl: no property " + PortalApiConstants.ECOMP_REST_URL);
92 String contextUrl = restUrl + (restUrl.endsWith("/") ? "" : "/") + "context/";
97 * Gets the shared-context value for the specified context ID and key.
100 * An Ecomp Portal session ID
102 * Key for the shared-context entry; e.g., "lastName"
103 * @return SharedContext object; null if not found.
105 * If URI cannot be built, host cannot be reached, etc.
107 public SharedContext getContextValue(String contextId, String key) throws Exception {
108 HttpStatusAndResponse hsr = getContext("get", contextId, key);
109 logger.info(EELFLoggerDelegate.debugLogger, "getSharedContext: resp is " + hsr);
111 logger.error(EELFLoggerDelegate.applicationLogger, "getContextValue: unexpected null response");
114 SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
115 // Response means no data.
116 if (jsonObj != null && jsonObj.getResponse() != null)
122 * Gets user information for the specified context ID.
125 * An Ecomp Portal session ID
126 * @return List of SharedContext objects corresponding to the following keys:
127 * USER_FIRST_NAME, USER_LAST_NAME, USER_EMAIL and USER_ORGUSERID; empty
128 * if none were found; null if an error happens.
130 * If URI cannot be built, host cannot be reached, etc.
132 public List<SharedContext> getUserContext(String contextId) throws Exception {
133 HttpStatusAndResponse hsr = getContext("get_user", contextId, null);
134 logger.info(EELFLoggerDelegate.debugLogger, "getUserContext: resp is " + hsr);
136 logger.error(EELFLoggerDelegate.applicationLogger, "getUserContext: unexpected null response");
137 return new ArrayList<>();
139 TypeReference<List<SharedContext>> typeRef = new TypeReference<List<SharedContext>>() {
141 List<SharedContext> jsonList = mapper.readValue(hsr.getResponse(), typeRef);
146 * Checks whether a shared-context entry exists for the specified context ID and
150 * An Ecomp Portal session ID
152 * Key for the shared-context entry; e.g., "lastName"
153 * @return True if the object exists, false otherwise; null on error.
155 * If URI cannot be built, host cannot be reached, etc.
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 SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
165 String response = jsonObj.getResponse();
166 if (response == null)
168 return "exists".equals(response);
172 * Removes a shared-context entry with the specified context ID and key.
175 * An Ecomp Portal session ID
177 * Key for the shared-context entry; e.g., "lastName"
178 * @return True if the entry was removed, false otherwise; null on error.
180 * If URI cannot be built, host cannot be reached, etc.
182 public Boolean removeSharedContext(String contextId, String key) throws Exception {
183 HttpStatusAndResponse hsr = getContext("remove", contextId, key);
184 logger.info(EELFLoggerDelegate.debugLogger, "removeSharedContext: resp is " + hsr);
186 logger.error(EELFLoggerDelegate.applicationLogger, "removeSharedContext: unexpected null response");
189 SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
192 String response = jsonObj.getResponse();
193 return "removed".equals(response);
197 * Clears the shared context for the specified context ID; i.e., removes all
201 * An Ecomp Portal session ID
202 * @return Number of key-value pairs removed; -1 if not found or any problems
205 * If URI cannot be built, host cannot be reached, etc.
207 public int clearSharedContext(String contextId) throws Exception {
208 HttpStatusAndResponse hsr = getContext("remove", contextId, null);
209 logger.info(EELFLoggerDelegate.debugLogger, "clearSharedContext: resp is " + hsr);
211 logger.error(EELFLoggerDelegate.applicationLogger, "clearSharedContext: unexpected null response");
214 SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
217 String response = jsonObj.getResponse();
218 if (response == null)
220 return Integer.parseInt(response);
224 * Creates a shared-context entry.
227 * An Ecomp Portal session ID
229 * Key for the shared-context entry; e.g., "lastName"
231 * Value for the entry
232 * @return True if the object previously existed, false otherwise; null if any
235 * If URI cannot be built, host cannot be reached, etc.
237 public Boolean setSharedContext(String contextId, String key, String value) throws Exception {
238 String body = buildContext(contextId, key, value);
239 HttpStatusAndResponse hsr = postContext("set", body);
240 logger.info(EELFLoggerDelegate.debugLogger, "setSharedContext: resp is " + hsr);
242 logger.error(EELFLoggerDelegate.applicationLogger, "setSharedContext: unexpected null response");
245 SharedContext jsonObj = mapper.readValue(hsr.getResponse(), SharedContext.class);
248 String response = jsonObj.getResponse();
249 return "replaced".equals(response);
253 * Builds the full URL with the specified parameters, then calls the method that
254 * adds credentials and GETs.
259 * @return HttpStatusAndResponse object; may be null.
260 * @throws URISyntaxException
261 * @throws IllegalArgumentException
262 * @throws IOException
263 * @throws CipherUtilException
265 private HttpStatusAndResponse getContext(String requestPath, String contextId, String contextKey)
266 throws IllegalArgumentException, URISyntaxException, CipherUtilException, IOException {
267 URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath);
268 uriBuilder.addParameter("context_id", contextId);
269 if (contextKey != null)
270 uriBuilder.addParameter("ckey", contextKey);
271 final URI uri = uriBuilder.build();
272 return getRestWithCredentials(uri);
276 * Builds the full URL, then calls the method that adds credentials and POSTs.
281 * @return HttpStatusAndResponse object; may be null.
282 * @throws IOException
283 * @throws CipherUtilException
284 * @throws URISyntaxException
285 * @throws IllegalArgumentException
287 private HttpStatusAndResponse postContext(String requestPath, String json)
288 throws CipherUtilException, IOException, IllegalArgumentException, URISyntaxException {
289 URIBuilder uriBuilder = new URIBuilder(getSharedContextUrl() + requestPath);
290 URI uri = uriBuilder.build();
291 return postRestWithCredentials(uri, json);
295 * Builds a JSON block with a single shared-context entry.
305 private String buildContext(String cxid, String ckey, String cvalue) throws JsonProcessingException {
306 HashMap<String, String> stringMap = new HashMap<>();
307 stringMap.put("context_id", cxid);
308 stringMap.put("ckey", ckey);
309 stringMap.put("cvalue", cvalue);
310 String json = mapper.writeValueAsString(stringMap);
314 // Simple test scaffold
315 public static void main(String[] args) throws Exception {
316 SharedContextRestClient client = new SharedContextRestClient();
317 SharedContext get = client.getContextValue("abc", "123");
318 System.out.println("Get yields " + get.toString());