Clean up and enhancement of Actor re-design
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / main / java / org / onap / policy / controlloop / actorserviceprovider / Util.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
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  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.actorserviceprovider;
22
23 import java.util.Arrays;
24 import java.util.LinkedHashMap;
25 import java.util.Map;
26 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
27 import org.onap.policy.common.endpoints.utils.NetLoggerUtil;
28 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
29 import org.onap.policy.common.utils.coder.Coder;
30 import org.onap.policy.common.utils.coder.CoderException;
31 import org.onap.policy.common.utils.coder.StandardCoder;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 /**
36  * Actor utilities.
37  */
38 public class Util {
39     private static final Logger logger = LoggerFactory.getLogger(Util.class);
40
41     private Util() {
42         // do nothing
43     }
44
45     /**
46      * Extracts an object's identity by invoking {@link Object#toString()} and returning
47      * the portion starting with "@". Extraction is done on-demand, when toString() is
48      * called on the result. This is typically used when logging.
49      *
50      * @param object object whose identity is to be extracted
51      * @return an object that will extract the source object's identity when this object's
52      *         toString() method is called
53      */
54     public static Object ident(Object object) {
55         return new DelayedIdentString(object);
56     }
57
58     /**
59      * Logs a REST request. If the request is not of type, String, then it attempts to
60      * pretty-print it into JSON before logging.
61      *
62      * @param url request URL
63      * @param request request to be logged
64      */
65     public static <T> void logRestRequest(String url, T request) {
66         logRestRequest(new StandardCoder(), url, request);
67     }
68
69     /**
70      * Logs a REST request. If the request is not of type, String, then it attempts to
71      * pretty-print it into JSON before logging.
72      *
73      * @param coder coder to be used to pretty-print the request
74      * @param url request URL
75      * @param request request to be logged
76      */
77     protected static <T> void logRestRequest(Coder coder, String url, T request) {
78         String json;
79         try {
80             if (request instanceof String) {
81                 json = request.toString();
82             } else {
83                 json = coder.encode(request, true);
84             }
85
86         } catch (CoderException e) {
87             logger.warn("cannot pretty-print request", e);
88             json = request.toString();
89         }
90
91         NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, url, json);
92         logger.info("[OUT|{}|{}|]{}{}", CommInfrastructure.REST, url, NetLoggerUtil.SYSTEM_LS, json);
93     }
94
95     /**
96      * Logs a REST response. If the response is not of type, String, then it attempts to
97      * pretty-print it into JSON before logging.
98      *
99      * @param url request URL
100      * @param response response to be logged
101      */
102     public static <T> void logRestResponse(String url, T response) {
103         logRestResponse(new StandardCoder(), url, response);
104     }
105
106     /**
107      * Logs a REST response. If the request is not of type, String, then it attempts to
108      * pretty-print it into JSON before logging.
109      *
110      * @param coder coder to be used to pretty-print the response
111      * @param url request URL
112      * @param response response to be logged
113      */
114     protected static <T> void logRestResponse(Coder coder, String url, T response) {
115         String json;
116         try {
117             if (response == null) {
118                 json = null;
119             } else if (response instanceof String) {
120                 json = response.toString();
121             } else {
122                 json = coder.encode(response, true);
123             }
124
125         } catch (CoderException e) {
126             logger.warn("cannot pretty-print response", e);
127             json = response.toString();
128         }
129
130         NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, url, json);
131         logger.info("[IN|{}|{}|]{}{}", CommInfrastructure.REST, url, NetLoggerUtil.SYSTEM_LS, json);
132     }
133
134     /**
135      * Runs a function and logs a message if it throws an exception. Does <i>not</i>
136      * re-throw the exception.
137      *
138      * @param function function to be run
139      * @param exceptionMessage message to log if an exception is thrown
140      * @param exceptionArgs arguments to be passed to the logger
141      */
142     public static void runFunction(Runnable function, String exceptionMessage, Object... exceptionArgs) {
143         try {
144             function.run();
145
146         } catch (RuntimeException ex) {
147             // create a new array containing the original arguments plus the exception
148             Object[] allArgs = Arrays.copyOf(exceptionArgs, exceptionArgs.length + 1);
149             allArgs[exceptionArgs.length] = ex;
150
151             logger.warn(exceptionMessage, allArgs);
152         }
153     }
154
155     /**
156      * Translates parameters from one class to another, typically from a Map to a POJO or
157      * vice versa.
158      *
159      * @param identifier identifier of the actor/operation being translated; used to build
160      *        an exception message
161      * @param source source object to be translated
162      * @param clazz target class
163      * @return the translated object
164      */
165     public static <T> T translate(String identifier, Object source, Class<T> clazz) {
166         Coder coder = new StandardCoder();
167
168         try {
169             String json = coder.encode(source);
170             return coder.decode(json, clazz);
171
172         } catch (CoderException | RuntimeException e) {
173             throw new IllegalArgumentException("cannot translate parameters for " + identifier, e);
174         }
175     }
176
177     /**
178      * Translates parameters to a Map.
179      *
180      * @param identifier identifier of the actor/operation being translated; used to build
181      *        an exception message
182      * @param source source parameters
183      * @return the parameters, as a Map
184      */
185     @SuppressWarnings("unchecked")
186     public static Map<String, Object> translateToMap(String identifier, Object source) {
187         if (source == null) {
188             return null;
189         }
190
191         return translate(identifier, source, LinkedHashMap.class);
192     }
193 }