aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/cds/AbstractCDSProcessingBBUtils.java
blob: 424a4f3eccc11c1bbd7543cc8840b40d305eab38 (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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 * Copyright (C) 2019 TechMahindra
 * ================================================================================
 * Modifications Copyright (c) 2019 Samsung
 * ================================================================================
 * 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.so.client.cds;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
import org.onap.ccsdk.cds.controllerblueprints.common.api.EventType;
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput;
import org.onap.so.client.PreconditionFailedException;
import org.onap.so.client.RestPropertiesLoader;
import org.onap.so.client.cds.beans.AbstractCDSPropertiesBean;
import org.onap.so.client.exception.BadResponseException;
import org.onap.so.client.exception.ExceptionBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Struct;
import com.google.protobuf.Struct.Builder;
import com.google.protobuf.util.JsonFormat;
import io.grpc.Status;

/**
 * Util class to support Call to CDS client
 *
 */
@Component
public class AbstractCDSProcessingBBUtils {

    private static final Logger logger = LoggerFactory.getLogger(AbstractCDSProcessingBBUtils.class);

    private static final String SUCCESS = "Success";
    private static final String FAILED = "Failed";
    private static final String PROCESSING = "Processing";
    private static final String RESPONSE_PAYLOAD = "CDSResponsePayload";
    private static final String CDS_STATUS = "CDSStatus";
    private static final String EXEC_INPUT = "executionServiceInput";


    /**
     * indicate exception thrown.
     */
    private static final String EXCEPTION = "Exception";

    @Autowired
    protected ExceptionBuilder exceptionUtil;

    /**
     * Extracting data from execution object and building the ExecutionServiceInput Object
     *
     * @param execution DelegateExecution object
     */
    public void constructExecutionServiceInputObject(DelegateExecution execution) {
        logger.trace("Start AbstractCDSProcessingBBUtils.preProcessRequest ");

        try {
            AbstractCDSPropertiesBean executionObject =
                    (AbstractCDSPropertiesBean) execution.getVariable("executionObject");

            String payload = executionObject.getRequestObject();

            CommonHeader commonHeader = CommonHeader.newBuilder().setOriginatorId(executionObject.getOriginatorId())
                    .setRequestId(executionObject.getRequestId()).setSubRequestId(executionObject.getSubRequestId())
                    .build();
            ActionIdentifiers actionIdentifiers =
                    ActionIdentifiers.newBuilder().setBlueprintName(executionObject.getBlueprintName())
                            .setBlueprintVersion(executionObject.getBlueprintVersion())
                            .setActionName(executionObject.getActionName()).setMode(executionObject.getMode()).build();

            Builder struct = Struct.newBuilder();
            try {
                JsonFormat.parser().merge(payload, struct);
            } catch (InvalidProtocolBufferException e) {
                logger.error("Failed to parse received message. blueprint({}:{}) for action({}). {}",
                        executionObject.getBlueprintVersion(), executionObject.getBlueprintName(),
                        executionObject.getActionName(), e);
            }

            ExecutionServiceInput executionServiceInput =
                    ExecutionServiceInput.newBuilder().setCommonHeader(commonHeader)
                            .setActionIdentifiers(actionIdentifiers).setPayload(struct.build()).build();

            execution.setVariable(EXEC_INPUT, executionServiceInput);

        } catch (Exception ex) {
            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
        }
    }

    /**
     * get the executionServiceInput object from execution and send a request to CDS Client and wait for TIMEOUT period
     *
     * @param execution DelegateExecution object
     */
    public void sendRequestToCDSClient(DelegateExecution execution) {

        logger.trace("Start AbstractCDSProcessingBBUtils.sendRequestToCDSClient ");
        try {
            CDSProperties props = RestPropertiesLoader.getInstance().getNewImpl(CDSProperties.class);
            if (props == null) {
                throw new PreconditionFailedException(
                        "No RestProperty.CDSProperties implementation found on classpath, can't create client.");
            }

            ExecutionServiceInput executionServiceInput = (ExecutionServiceInput) execution.getVariable(EXEC_INPUT);

            CDSResponse cdsResponse = new CDSResponse();

            try (CDSProcessingClient cdsClient = new CDSProcessingClient(new ResponseHandler(cdsResponse))) {
                CountDownLatch countDownLatch = cdsClient.sendRequest(executionServiceInput);
                countDownLatch.await(props.getTimeout(), TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                logger.error("Caught exception in sendRequestToCDSClient in AbstractCDSProcessingBBUtils : ", ex);
                Thread.currentThread().interrupt();
            }

            String cdsResponseStatus = cdsResponse.status;

            /**
             * throw CDS failed exception.
             */
            if (!cdsResponseStatus.equals(SUCCESS)) {
                throw new BadResponseException("CDS call failed with status: " + cdsResponse.status
                        + " and errorMessage: " + cdsResponse.errorMessage);
            }

            execution.setVariable(CDS_STATUS, cdsResponseStatus);

            if (cdsResponse.payload != null) {
                String payload = JsonFormat.printer().print(cdsResponse.payload);
                execution.setVariable(RESPONSE_PAYLOAD, payload);
            }



        } catch (Exception ex) {
            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, ex);
        }
    }

    private class ResponseHandler implements CDSProcessingListener {

        private CDSResponse cdsResponse;

        ResponseHandler(CDSResponse cdsResponse) {
            this.cdsResponse = cdsResponse;
        }

        /**
         * Get Response from CDS Client
         */
        @Override
        public void onMessage(ExecutionServiceOutput message) {
            logger.info("Received notification from CDS: {}", message);
            EventType eventType = message.getStatus().getEventType();

            switch (eventType) {
                case EVENT_COMPONENT_PROCESSING:
                    cdsResponse.status = PROCESSING;
                    break;
                case EVENT_COMPONENT_EXECUTED:
                    cdsResponse.status = SUCCESS;
                    break;
                default:
                    cdsResponse.status = FAILED;
                    cdsResponse.errorMessage = message.getStatus().getErrorMessage();
                    break;
            }
            cdsResponse.payload = message.getPayload();
        }

        /**
         * On error at CDS, log the error
         */
        @Override
        public void onError(Throwable t) {
            Status status = Status.fromThrowable(t);
            logger.error("Failed processing blueprint {}", status, t);
            cdsResponse.status = EXCEPTION;
        }
    }

    private class CDSResponse {

        String status;
        String errorMessage;
        Struct payload;

        @Override
        public String toString() {
            return "CDSResponse{" + "status='" + status + '\'' + ", errorMessage='" + errorMessage + '\'' + ", payload="
                    + payload + '}';
        }
    }
}