Merge "Add withTrustLevel condition to CmHandle Query API"
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / events / mapper / CloudEventMapper.java
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (c) 2023 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *         http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.api.impl.events.mapper;
22
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import io.cloudevents.CloudEvent;
25 import io.cloudevents.core.CloudEventUtils;
26 import io.cloudevents.core.data.PojoCloudEventData;
27 import io.cloudevents.jackson.PojoCloudEventDataMapper;
28 import lombok.AccessLevel;
29 import lombok.NoArgsConstructor;
30 import lombok.extern.slf4j.Slf4j;
31
32 @Slf4j
33 @NoArgsConstructor(access = AccessLevel.PRIVATE)
34 public class CloudEventMapper {
35
36     private static final ObjectMapper objectMapper = new ObjectMapper();
37
38     /**
39      * Generic method to map cloud event data to target event class object.
40      *
41      * @param cloudEvent       input cloud event
42      * @param targetEventClass target event class
43      * @param <T>              target event class type
44      * @return mapped target event
45      */
46     public static <T> T toTargetEvent(final CloudEvent cloudEvent, final Class<T> targetEventClass) {
47         PojoCloudEventData<T> mappedCloudEvent = null;
48
49         try {
50             mappedCloudEvent =
51                     CloudEventUtils.mapData(cloudEvent, PojoCloudEventDataMapper.from(objectMapper, targetEventClass));
52
53         } catch (final RuntimeException runtimeException) {
54             log.error("Unable to map cloud event to target event class type : {} with cause : {}", targetEventClass,
55                     runtimeException.getMessage());
56         }
57
58         return mappedCloudEvent == null ? null : mappedCloudEvent.getValue();
59     }
60
61 }