Add NCMP Stub documentation to RTD
[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 io.cloudevents.rw.CloudEventRWException;
29 import lombok.AccessLevel;
30 import lombok.NoArgsConstructor;
31 import lombok.extern.slf4j.Slf4j;
32
33 @Slf4j
34 @NoArgsConstructor(access = AccessLevel.PRIVATE)
35 public class CloudEventMapper {
36
37     private static final ObjectMapper objectMapper = new ObjectMapper();
38
39     /**
40      * Generic method to map cloud event data to target event class object.
41      *
42      * @param cloudEvent       input cloud event
43      * @param targetEventClass target event class
44      * @param <T>              target event class type
45      * @return mapped target event
46      */
47     public static <T> T toTargetEvent(final CloudEvent cloudEvent, final Class<T> targetEventClass) {
48         PojoCloudEventData<T> mappedCloudEvent = null;
49
50         try {
51             mappedCloudEvent =
52                     CloudEventUtils.mapData(cloudEvent, PojoCloudEventDataMapper.from(objectMapper, targetEventClass));
53
54         } catch (final CloudEventRWException cloudEventRwException) {
55             log.error("Unable to map cloud event to target event class type : {} with cause : {}", targetEventClass,
56                     cloudEventRwException.getMessage());
57         }
58
59         return mappedCloudEvent == null ? null : mappedCloudEvent.getValue();
60     }
61
62 }