Async request response NCMP -> Client
[cps.git] / cps-ncmp-rest / src / main / java / org / onap / cps / ncmp / rest / executor / CpsNcmpTaskExecutor.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 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.rest.executor;
22
23 import static java.util.concurrent.TimeUnit.MILLISECONDS;
24
25 import java.util.concurrent.CompletableFuture;
26 import java.util.function.Supplier;
27 import lombok.extern.slf4j.Slf4j;
28 import org.springframework.stereotype.Service;
29
30 @Slf4j
31 @Service
32 public class CpsNcmpTaskExecutor {
33
34     /**
35      * Execute task asynchronously and publish response to supplied topic.
36      *
37      * @param taskSupplier functional method is get() task need to executed asynchronously
38      * @param timeOutInMillis the time out value in milliseconds
39      */
40     public void executeTask(final Supplier<Object> taskSupplier, final int timeOutInMillis) {
41         CompletableFuture.supplyAsync(taskSupplier::get)
42             .orTimeout(timeOutInMillis, MILLISECONDS)
43             .whenCompleteAsync(
44                 (responseAsJson, throwable) -> {
45                     handleTaskCompletion(throwable);
46                 }
47             );
48     }
49
50     private void handleTaskCompletion(final Throwable throwable) {
51         if (throwable == null) {
52             log.info("Async task completed successfully.");
53         } else {
54             log.error("Async task failed. caused by : {}", throwable.getMessage());
55         }
56     }
57 }
58
59
60