aboutsummaryrefslogtreecommitdiffstats
path: root/prh-app-server/src/main/java/org/onap/dcaegen2/services/prh/tasks/ScheduledTasks.java
blob: de7837ec829c81d32c01ee6052e1982622c6e459 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/*
 * ============LICENSE_START=======================================================
 * PNF-REGISTRATION-HANDLER
 * ================================================================================
 * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.dcaegen2.services.prh.tasks;

import static org.onap.dcaegen2.services.prh.model.logging.MdcVariables.INSTANCE_UUID;
import static org.onap.dcaegen2.services.prh.model.logging.MdcVariables.RESPONSE_CODE;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import javax.net.ssl.SSLException;
import org.onap.dcaegen2.services.prh.exceptions.DmaapEmptyResponseException;
import org.onap.dcaegen2.services.prh.exceptions.PrhTaskException;
import org.onap.dcaegen2.services.prh.model.ConsumerDmaapModel;
import org.onap.dcaegen2.services.prh.model.logging.MdcVariables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 3/23/18
 */
@Component
public class ScheduledTasks {

    private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
    private static final Marker INVOKE = MarkerFactory.getMarker("INVOKE");
    private final DmaapConsumerTask dmaapConsumerTask;
    private final DmaapPublisherTask dmaapProducerTask;
    private final AaiProducerTask aaiProducerTask;
    private Map<String, String> mdcContextMap;

    /**
     * Constructor for tasks registration in PRHWorkflow.
     *
     * @param dmaapConsumerTask - fist task
     * @param dmaapPublisherTask - third task
     * @param aaiPublisherTask - second task
     */
    @Autowired
    public ScheduledTasks(DmaapConsumerTask dmaapConsumerTask, DmaapPublisherTask dmaapPublisherTask,
        AaiProducerTask aaiPublisherTask, Map<String, String> mdcContextMap) {
        this.dmaapConsumerTask = dmaapConsumerTask;
        this.dmaapProducerTask = dmaapPublisherTask;
        this.aaiProducerTask = aaiPublisherTask;
        this.mdcContextMap = mdcContextMap;
    }

    /**
     * Main function for scheduling prhWorkflow.
     */
    public void scheduleMainPrhEventTask() {
        MdcVariables.setMdcContextMap(mdcContextMap);
        try {
            logger.trace("Execution of tasks was registered");
            CountDownLatch mainCountDownLatch = new CountDownLatch(1);
            consumeFromDMaaPMessage()
                .doOnError(DmaapEmptyResponseException.class, error ->
                    logger.warn("Nothing to consume from DMaaP")
                )
                .flatMap(this::publishToAaiConfiguration)
                .flatMap(this::publishToDmaapConfiguration)
                .doOnTerminate(mainCountDownLatch::countDown)
                .subscribe(this::onSuccess, this::onError, this::onComplete);

            mainCountDownLatch.await();
        } catch (InterruptedException e) {
            logger.warn("Interruption problem on countDownLatch ", e);
            Thread.currentThread().interrupt();
        }
    }


    private void onComplete() {
        logger.info("PRH tasks have been completed");
    }

    private void onSuccess(ResponseEntity<String> responseCode) {
        MDC.put(RESPONSE_CODE, responseCode.getStatusCode().toString());
        logger.info("Prh consumed tasks successfully. HTTP Response code from DMaaPProducer {}",
            responseCode.getStatusCode().value());
        MDC.remove(RESPONSE_CODE);
    }

    private void onError(Throwable throwable) {
        if (!(throwable instanceof DmaapEmptyResponseException)) {
            logger.warn("Chain of tasks have been aborted due to errors in PRH workflow", throwable);
        }
    }


    private Mono<ConsumerDmaapModel> consumeFromDMaaPMessage() {
        return Mono.defer(() -> {
            MdcVariables.setMdcContextMap(mdcContextMap);
            MDC.put(INSTANCE_UUID, UUID.randomUUID().toString());
            logger.info(INVOKE, "Init configs");
            dmaapConsumerTask.initConfigs();
            return dmaapConsumerTask.execute("");
        });
    }

    private Mono<ConsumerDmaapModel> publishToAaiConfiguration(ConsumerDmaapModel monoDMaaPModel) {
        try {
            return aaiProducerTask.execute(monoDMaaPModel);
        } catch (PrhTaskException | SSLException e) {
            return Mono.error(e);
        }
    }

    private Mono<ResponseEntity<String>> publishToDmaapConfiguration(ConsumerDmaapModel monoAaiModel) {
        try {
            return dmaapProducerTask.execute(monoAaiModel);
        } catch (PrhTaskException e) {
            return Mono.error(e);
        }
    }
}