Fix eclipse/sonar warnings in models
[policy/models.git] / models-interactions / model-simulators / src / main / java / org / onap / policy / simulators / CdsSimulator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Nordix Foundation.
4  *  Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
5  *  Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.simulators;
24
25 import com.google.protobuf.InvalidProtocolBufferException;
26 import com.google.protobuf.util.JsonFormat;
27 import io.grpc.Server;
28 import io.grpc.netty.NettyServerBuilder;
29 import io.grpc.stub.StreamObserver;
30 import java.io.IOException;
31 import java.net.InetSocketAddress;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.atomic.AtomicInteger;
34 import lombok.Getter;
35 import org.apache.commons.lang3.StringUtils;
36 import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
37 import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase;
38 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput;
39 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput;
40 import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput.Builder;
41 import org.onap.policy.common.utils.resources.ResourceUtils;
42
43 public class CdsSimulator {
44     @Getter
45     private final int port;
46
47     private final Server server;
48
49     private final String resourceLocation;
50
51     private AtomicInteger countOfEvents = new AtomicInteger(1);
52
53     /**
54      * Constructs the object, but does not start it.
55      *
56      * @param host host name of the server
57      * @param port port of the server
58      */
59     public CdsSimulator(String host, int port) {
60         this(host, port, "org/onap/policy/simulators/cds/", 0, 0);
61     }
62
63     /**
64      * Constructs the object, but does not start it.
65      *
66      * @param host host name of the server
67      * @param port port of the server
68      * @param countOfSuccesfulEvents number of successive successful events
69      * @param requestedResponseDelayMs time for the request to be processed
70      */
71     public CdsSimulator(String host, int port, String resourceLocation, int countOfSuccesfulEvents,
72         long requestedResponseDelayMs) {
73         this.port = port;
74         this.resourceLocation = resourceLocation;
75
76         BluePrintProcessingServiceImplBase testCdsBlueprintServerImpl = new BluePrintProcessingServiceImplBase() {
77
78             @Override
79             public StreamObserver<ExecutionServiceInput> process(
80                             final StreamObserver<ExecutionServiceOutput> responseObserver) {
81
82                 return new StreamObserver<ExecutionServiceInput>() {
83
84                     @Override
85                     public void onNext(final ExecutionServiceInput executionServiceInput) {
86                         try {
87                             String responseString = getResponseString(executionServiceInput, countOfSuccesfulEvents);
88                             Builder builder = ExecutionServiceOutput.newBuilder();
89                             JsonFormat.parser().ignoringUnknownFields().merge(responseString, builder);
90                             TimeUnit.MILLISECONDS.sleep(requestedResponseDelayMs);
91                             responseObserver.onNext(builder.build());
92                         } catch (InvalidProtocolBufferException e) {
93                             throw new SimulatorRuntimeException("Cannot convert ExecutionServiceOutput output", e);
94                         } catch (InterruptedException e) {
95                             Thread.currentThread().interrupt();
96                             throw new SimulatorRuntimeException("Execution Interrupted", e);
97                         }
98                     }
99
100                     @Override
101                     public void onError(final Throwable throwable) {
102                         responseObserver.onError(throwable);
103                     }
104
105                     @Override
106                     public void onCompleted() {
107                         responseObserver.onCompleted();
108                     }
109                 };
110             }
111         };
112
113         server = NettyServerBuilder.forAddress(new InetSocketAddress(host, port)).addService(testCdsBlueprintServerImpl)
114                         .build();
115     }
116
117     public void start() throws IOException {
118         server.start();
119     }
120
121     public void stop() {
122         server.shutdown();
123     }
124
125     /**
126      * Constructs the ResponseString on the basis of request.
127      *
128      * @param executionServiceInput service input
129      * @param countOfSuccesfulEvents number of successive successful events
130      * @return  responseString
131      */
132     public String getResponseString(ExecutionServiceInput executionServiceInput, int countOfSuccesfulEvents) {
133         String resourceName = "DefaultResponseEvent";
134         if (!StringUtils.isBlank(executionServiceInput.getActionIdentifiers().getActionName())) {
135             ActionIdentifiers actionIdentifiers = executionServiceInput.getActionIdentifiers();
136             resourceName = actionIdentifiers.getBlueprintName() + "-" + actionIdentifiers.getActionName();
137         }
138         if (countOfSuccesfulEvents > 0 && countOfEvents.getAndIncrement() % countOfSuccesfulEvents == 0) {
139             // generating the failure response
140             resourceName = resourceName + "-error.json";
141         } else {
142             resourceName = resourceName + ".json";
143         }
144         String responseString = ResourceUtils.getResourceAsString(resourceLocation + resourceName);
145         if (responseString == null) {
146             responseString = ResourceUtils.getResourceAsString(resourceLocation
147                 + "DefaultResponseEvent.json");
148         }
149         return responseString;
150     }
151 }