2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 NOKIA Intellectual Property. 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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 * ============LICENSE_END=========================================================
21 package org.onap.pnfsimulator.simulator;
23 import java.time.Duration;
24 import java.time.Instant;
25 import org.apache.logging.log4j.LogManager;
26 import org.apache.logging.log4j.Logger;
27 import org.json.JSONObject;
28 import org.onap.pnfsimulator.simulator.client.HttpClientAdapter;
30 public class Simulator extends Thread {
32 private static final Logger LOGGER = LogManager.getLogger(Simulator.class);
33 private HttpClientAdapter clientProvider;
34 private JSONObject messageBody;
35 private Instant endTime;
36 private Duration duration;
37 private Duration interval;
38 private final boolean isEndless;
40 public Simulator(String vesServerUrl, JSONObject messageBody, Duration duration, Duration interval) {
41 this.messageBody = messageBody;
42 this.duration = duration;
43 this.interval = interval;
44 this.clientProvider = new HttpClientAdapter(vesServerUrl);
45 this.isEndless = duration.getSeconds() == 0;
49 LOGGER.info("Simulation started - duration: " + getDuration() + ", interval: {}s", interval.getSeconds());
51 endTime = Instant.now().plus(duration);
52 boolean isEndless = isEndless();
53 while (isEndless || runningTimeNotExceeded()) {
55 LOGGER.debug("Message to be sent:\n" + messageBody.toString(4));
56 clientProvider.sendMsg(messageBody.toString());
57 Thread.sleep(interval.toMillis());
58 } catch (InterruptedException e) {
59 LOGGER.info("Simulation interrupted");
63 LOGGER.info("Simulation finished");
66 public boolean isEndless() {
70 private String getDuration() {
71 return isEndless() ? "infinity" : duration.getSeconds() + "s";
74 private boolean runningTimeNotExceeded() {
75 return Instant.now().isBefore(endTime);
78 public long getRemainingTime(){
79 return Duration.between(Instant.now(), endTime).getSeconds();
81 public String getMessage(){
82 return messageBody.toString(4);