diff options
author | Pawel Kadlubanski <pawel.kadlubanski@nokia.com> | 2018-06-15 16:13:45 +0200 |
---|---|---|
committer | Pawel Kadlubanski <pawel.kadlubanski@nokia.com> | 2018-06-15 16:13:45 +0200 |
commit | 432696535f996211186269c78e36ab5a6c073997 (patch) | |
tree | 50c2209507e6e5335b4f1c11e6f309208900ba77 /test/mocks/pnfsimulator/src/main | |
parent | b1d31973db0cf699ef65d862c2fcf02177aafac5 (diff) |
Add netconf support to pnfsimulator.
Issue-ID: INT-458
Change-Id: Iebc9cf2a9f35c92dc354d1c6e857dc8345c1172f
Signed-off-by: Pawel Kadlubanski <pawel.kadlubanski@nokia.com>
Diffstat (limited to 'test/mocks/pnfsimulator/src/main')
22 files changed, 817 insertions, 199 deletions
diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java index 37f1b21c9..0e9fe4d3d 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/Main.java @@ -20,38 +20,14 @@ package org.onap.pnfsimulator; -import java.io.IOException; -import org.apache.commons.cli.ParseException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.onap.pnfsimulator.cli.SimulatorParamsProvider; -import org.onap.pnfsimulator.cli.SimulatorParams; -import org.onap.pnfsimulator.message.MessageProvider; -import org.onap.pnfsimulator.simulator.SimulatorFactory; -import org.onap.pnfsimulator.simulator.validation.ParamsValidator; -import org.onap.pnfsimulator.simulator.validation.ValidationException; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; +@SpringBootApplication +@EnableAsync public class Main { - - private static Logger logger = LogManager.getLogger(Main.class); - private static SimulatorFactory simulatorFactory = - new SimulatorFactory(MessageProvider.getInstance()); - public static void main(String[] args) { - - try { - - SimulatorParams params = new SimulatorParamsProvider().parse(args); - simulatorFactory - .create(params.getVesAddress(), params.getConfigFilePath()) - .start(); - - } catch (IOException e) { - logger.error("Invalid config file format", e); - } catch (ParseException e) { - logger.error("Invalid cli params", e); - } catch (ValidationException e){ - logger.error(e); - } + SpringApplication.run(Main.class, args); } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParamsProvider.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParamsProvider.java deleted file mode 100644 index ab705e907..000000000 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParamsProvider.java +++ /dev/null @@ -1,61 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.integration - * ================================================================================ - * 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.pnfsimulator.cli; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.DefaultParser; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; - -public class SimulatorParamsProvider { - - private static final String CLI_VAR_VES_ADDRESS = "address"; - private static final String CLI_VAR_CONFIG_FILE_PATH = "config"; - private static final String ENV_VAR_VES_ADDRESS = "VES_ADDRESS"; - private static final String ENV_VAR_CONFIG_FILE_PATH = "CONFIG_FILE_PATH"; - - private Options options; - private CommandLineParser parser; - - public SimulatorParamsProvider() { - createOptions(); - parser = new DefaultParser(); - } - - public SimulatorParams parse(String[] arg) throws ParseException { - CommandLine line = parser.parse(options, arg); - return new SimulatorParams( - line.getOptionValue(CLI_VAR_VES_ADDRESS, System.getenv().get(ENV_VAR_VES_ADDRESS)), - line.getOptionValue(CLI_VAR_CONFIG_FILE_PATH, System.getenv().get(ENV_VAR_CONFIG_FILE_PATH))); - } - - private void createOptions() { - options = new Options(); - - Option vesCollectorUlrOpt = new Option(CLI_VAR_VES_ADDRESS, true, "VES collector URL"); - options.addOption(vesCollectorUlrOpt); - - Option simulatorConfigFilePathOpt = new Option(CLI_VAR_CONFIG_FILE_PATH, true, "Simulator configuration file location."); - options.addOption(simulatorConfigFilePathOpt); - } -} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java index 5805a88c7..8e7c6fcfd 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java @@ -17,7 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - + package org.onap.pnfsimulator.message; public final class MessageConstants { @@ -36,12 +36,15 @@ public final class MessageConstants { public static final String PNF_LAST_SERVICE_DATE = "pnfLastServiceDate"; public static final String PNF_MANUFACTURE_DATE = "pnfManufactureDate"; + public static final String SIMULATOR_PARAMS_CONTAINER = "simulatorParams"; + public static final String MESSAGE_PARAMS_CONTAINER = "messageParams"; + // mandatory public static final String PNF_OAM_IPV4_ADDRESS = "pnfOamIpv4Address"; public static final String PNF_OAM_IPV6_ADDRESS = "pnfOamIpv6Address"; public static final String PNF_SERIAL_NUMBER = "pnfSerialNumber"; public static final String PNF_VENDOR_NAME = "pnfVendorName"; - + public static final String VES_SERVER_URL = "vesServerUrl"; public static final String PNF_PREFIX = "pnf"; public static final String COMMON_EVENT_HEADER = "commonEventHeader"; public static final String OTHER_FIELDS = "otherFields"; diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java index 94f5fc167..44ca9666c 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java @@ -39,24 +39,16 @@ import static org.onap.pnfsimulator.message.MessageConstants.EVENT; import java.util.Map; import java.util.UUID; - -import com.google.common.base.Preconditions; import org.json.JSONObject; public class MessageProvider { - private static MessageProvider instance; + public JSONObject createMessage(JSONObject params) { - public static MessageProvider getInstance() { - if (instance == null) { - instance = new MessageProvider(); + if(params == null){ + throw new IllegalArgumentException("Params object cannot be null"); } - return instance; - } - public JSONObject createMessage(JSONObject params) { - - Preconditions.checkArgument(params != null, "Params object cannot be null"); Map<String, Object> paramsMap = params.toMap(); JSONObject root = new JSONObject(); JSONObject commonEventHeader = generateConstantCommonEventHeader(); @@ -74,7 +66,6 @@ public class MessageProvider { JSONObject event = new JSONObject(); event.put(COMMON_EVENT_HEADER, commonEventHeader); event.put(OTHER_FIELDS, otherFields); - root.put(EVENT, event); return root; } @@ -93,7 +84,6 @@ public class MessageProvider { commonEventHeader.put(START_EPOCH_MICROSEC, timestamp); commonEventHeader.put(INTERNAL_HEADER_FIELDS, new JSONObject()); commonEventHeader.put(VERSION, 3); - commonEventHeader.put("functionalRole", "test_rola"); return commonEventHeader; } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java new file mode 100644 index 000000000..b4eda0a79 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.netconfmonitor; + +import com.tailf.jnc.JNCException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; + +import java.io.IOException; +import java.util.TimerTask; + +public class NetconfConfigurationCheckingTask extends TimerTask { + private static final Logger LOGGER = LogManager.getLogger(NetconfConfigurationCheckingTask.class); + + private final NetconfConfigurationReader reader; + private final NetconfConfigurationWriter writer; + private final NetconfConfigurationCache cache; + + public NetconfConfigurationCheckingTask(NetconfConfigurationReader reader, + NetconfConfigurationWriter writer, + NetconfConfigurationCache cache) { + this.reader = reader; + this.writer = writer; + this.cache = cache; + } + + @Override + public void run() { + String currentConfiguration = ""; + try { + currentConfiguration = reader.read(); + } catch (IOException|JNCException e) { + LOGGER.info("Error during configuration reading: {}", e.getMessage()); + } + if (!currentConfiguration.equals(cache.getConfiguration())) { + LOGGER.info("Configuration has changed, new configuration:\n\n{}", currentConfiguration); + writer.writeToFile(currentConfiguration); + cache.update(currentConfiguration); + } + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java new file mode 100644 index 000000000..c4d6198f7 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.netconfmonitor; + +import com.tailf.jnc.JNCException; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.io.IOException; +import java.util.Timer; + +@Service +public class NetconfMonitorService { + private static final long timePeriod = 1000L; + private static final long startDelay = 0; + + private Timer timer; + private NetconfConfigurationReader reader; + private NetconfConfigurationWriter writer; + private NetconfConfigurationCache cache; + + @Autowired + public NetconfMonitorService(Timer timer, + NetconfConfigurationReader reader, + NetconfConfigurationWriter writer, + NetconfConfigurationCache cache) { + this.timer = timer; + this.reader = reader; + this.writer = writer; + this.cache = cache; + } + + @PostConstruct + public void start() throws IOException, JNCException { + setStartConfiguration(); + NetconfConfigurationCheckingTask task = new NetconfConfigurationCheckingTask(reader, writer, cache); + timer.scheduleAtFixedRate(task, startDelay, timePeriod); + } + + private void setStartConfiguration() throws IOException, JNCException { + String configuration = reader.read(); + writer.writeToFile(configuration); + cache.update(configuration); + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java new file mode 100644 index 000000000..82ea85aee --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.netconfmonitor; + +import com.tailf.jnc.JNCException; +import com.tailf.jnc.NetconfSession; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.onap.pnfsimulator.netconfmonitor.netconf.*; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.io.IOException; +import java.util.Map; +import java.util.Timer; + +@Configuration +public class NetconfMonitorServiceConfiguration { + private static final Logger LOGGER = LogManager.getLogger(NetconfMonitorServiceConfiguration.class); + private static final Map<String, String> enviroment = System.getenv(); + + private static final String LOG_PATH = "/var/log"; + + private static final String NETCONF_ADDRESS = "NETCONF_ADDRESS"; + private static final String NETCONF_PORT = "NETCONF_PORT"; + private static final String NETCONF_MODEL = "NETCONF_MODEL"; + private static final String NETCONF_MAIN_CONTAINER = "NETCONF_MAIN_CONTAINER"; + + private static final String DEFAULT_NETCONF_ADDRESS = "netopeer"; + private static final int DEFAULT_NETCONF_PORT = 830; + private static final String DEFAULT_NETCONF_MODEL = "pnf-simulator"; + private static final String DEFAULT_NETCONF_MAIN_CONTAINER = "config"; + + private static final String DEFAULT_NETCONF_USER = "netconf"; + private static final String DEFAULT_NETCONF_PASSWORD = "netconf"; + + @Bean + public Timer timer() { + return new Timer("NetconfMonitorServiceTimer"); + } + + @Bean + public NetconfConfigurationCache configurationCache() { + return new NetconfConfigurationCache(); + } + + @Bean + public NetconfConfigurationReader configurationReader() throws IOException, JNCException { + NetconfConnectionParams params = createConnectionParams(); + LOGGER.info("Configuration params are : {}", params); + NetconfSession session = NetconfSessionFactory.create(params); + return new NetconfConfigurationReader(session, buildModelPath()); + } + + @Bean + public NetconfConfigurationWriter netconfConfigurationWriter() { + return new NetconfConfigurationWriter(LOG_PATH); + } + + private String buildModelPath() { + return String.format("/%s:%s", + enviroment.getOrDefault(NETCONF_MODEL, DEFAULT_NETCONF_MODEL), + enviroment.getOrDefault(NETCONF_MAIN_CONTAINER, DEFAULT_NETCONF_MAIN_CONTAINER)); + } + + private NetconfConnectionParams createConnectionParams() { + return new NetconfConnectionParams( + enviroment.getOrDefault(NETCONF_ADDRESS, DEFAULT_NETCONF_ADDRESS), + resolveNetconfPort(), + DEFAULT_NETCONF_USER, + DEFAULT_NETCONF_PASSWORD); + } + + private int resolveNetconfPort() { + try { + return Integer.parseInt(enviroment.get(NETCONF_PORT)); + } catch (NumberFormatException e) { + return DEFAULT_NETCONF_PORT; + } + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java new file mode 100644 index 000000000..820234620 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.netconfmonitor.netconf; + +public class NetconfConfigurationCache { + private String configuration = ""; + + public String getConfiguration() { + return configuration; + } + + public void update(String configuration) { + this.configuration = configuration; + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java new file mode 100644 index 000000000..e8979254d --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.netconfmonitor.netconf; + +import com.tailf.jnc.JNCException; +import com.tailf.jnc.NetconfSession; + +import java.io.IOException; + +public class NetconfConfigurationReader { + private final NetconfSession session; + private final String netconfModelPath; + + public NetconfConfigurationReader(NetconfSession session, String netconfModelPath) { + this.session = session; + this.netconfModelPath = netconfModelPath; + } + + public String read() throws IOException, JNCException { + return session.getConfig(netconfModelPath).first().toXMLString(); + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java new file mode 100644 index 000000000..4c3d53e39 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.netconfmonitor.netconf; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import org.onap.pnfsimulator.rest.util.DateUtil; + +public class NetconfConfigurationWriter { + private static final Logger LOGGER = LogManager.getLogger(NetconfConfigurationWriter.class); + private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); + private String pathToLog; + + public NetconfConfigurationWriter(String pathToLog) { + this.pathToLog = pathToLog; + } + + public void writeToFile(String configuration) { + String fileName = String.format("%s/config[%s].xml", pathToLog, DateUtil.getTimestamp(dateFormat)); + try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) { + writer.write(configuration); + LOGGER.info("Configuration wrote to file {}/{} ", pathToLog, fileName); + } catch (IOException e) { + LOGGER.info("Failed to write configuration to file: {}", e.getMessage()); + } + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParams.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java index 2ca0b5e7b..3130d2b06 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/cli/SimulatorParams.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java @@ -18,48 +18,27 @@ * ============LICENSE_END========================================================= */ -package org.onap.pnfsimulator.cli; - -import java.util.Objects; - -public class SimulatorParams { - - private String vesAddress; - private String configFilePath; - - public SimulatorParams(String vesAddress, String configFilePath) { - this.vesAddress = vesAddress; - this.configFilePath = configFilePath; - } - - public String getVesAddress() { - return vesAddress; - } - - public String getConfigFilePath() { - return configFilePath; +package org.onap.pnfsimulator.netconfmonitor.netconf; + +public class NetconfConnectionParams { + public final String address; + public final int port; + public final String user; + public final String password; + + public NetconfConnectionParams(String address, int port, String user, String password) { + this.address = address; + this.port = port; + this.user = user; + this.password = password; } @Override public String toString() { - return String.format("VES address=%s, Configuration file=%s", vesAddress, configFilePath); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof SimulatorParams)) { - return false; - } - SimulatorParams params = (SimulatorParams) o; - return Objects.equals(vesAddress, params.vesAddress) && - Objects.equals(configFilePath, params.configFilePath); - } - - @Override - public int hashCode() { - return Objects.hash(vesAddress, configFilePath); + return String.format("NetconfConnectionParams{address=%s, port=%d, user=%s, password=%s}", + address, + port, + user, + password); } -} +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfSessionFactory.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfSessionFactory.java new file mode 100644 index 000000000..4f31af5eb --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfSessionFactory.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.netconfmonitor.netconf; + +import com.tailf.jnc.JNCException; +import com.tailf.jnc.NetconfSession; +import com.tailf.jnc.SSHConnection; +import com.tailf.jnc.SSHSession; + +import java.io.IOException; + +public final class NetconfSessionFactory { + private NetconfSessionFactory() {} + + public static NetconfSession create(NetconfConnectionParams params) throws IOException, JNCException { + SSHConnection sshConnection = new SSHConnection(params.address, params.port); + sshConnection.authenticateWithPassword(params.user, params.password); + SSHSession sshSession = new SSHSession(sshConnection); + return new NetconfSession(sshSession); + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java new file mode 100644 index 000000000..46a63a21c --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.rest; + +import static org.onap.pnfsimulator.message.MessageConstants.SIMULATOR_PARAMS_CONTAINER; +import static org.onap.pnfsimulator.rest.util.ResponseBuilder.MESSAGE; +import static org.onap.pnfsimulator.rest.util.ResponseBuilder.REMAINING_TIME; +import static org.onap.pnfsimulator.rest.util.ResponseBuilder.SIMULATOR_STATUS; +import static org.onap.pnfsimulator.rest.util.ResponseBuilder.TIMESTAMP; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.pnfsimulator.message.MessageConstants; +import org.onap.pnfsimulator.message.MessageProvider; +import org.onap.pnfsimulator.rest.util.DateUtil; +import org.onap.pnfsimulator.rest.util.ResponseBuilder; +import org.onap.pnfsimulator.simulator.Simulator; +import org.onap.pnfsimulator.simulator.SimulatorFactory; +import org.onap.pnfsimulator.simulator.validation.ValidationException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + + +@RestController +@RequestMapping("/simulator") +public class SimulatorController { + + private static final Logger LOGGER = LogManager.getLogger(Simulator.class); + private static final DateFormat RESPONSE_DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss,SSS"); + + private Simulator simulator; + + + @PostMapping("start") + public ResponseEntity start(@RequestBody String message) { + + if (simulator != null && simulator.isAlive()) { + return ResponseBuilder + .status(HttpStatus.BAD_REQUEST.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot start simulator since it's already running") + .build(); + } + + try { + JSONObject root = new JSONObject(message); + JSONObject simulatorParams = root.getJSONObject(SIMULATOR_PARAMS_CONTAINER); + JSONObject messageParams = root.getJSONObject(MessageConstants.MESSAGE_PARAMS_CONTAINER); + + simulator = SimulatorFactory + .usingMessageProvider(new MessageProvider()) + .create(simulatorParams, messageParams); + + simulator.start(); + + } catch (JSONException e) { + + LOGGER.error("Cannot start simulator, invalid json format: " + e.getMessage()); + LOGGER.debug("Received json has invalid format:\n" + message); + return ResponseBuilder + .status(HttpStatus.BAD_REQUEST.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot start simulator, invalid json format") + .build(); + + } catch (ValidationException e) { + + LOGGER.error("Cannot start simulator - missing mandatory parameters"); + return ResponseBuilder + .status(HttpStatus.BAD_REQUEST.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, e.getMessage()) + .build(); + + } catch (RuntimeException e) { + + LOGGER.error("Cannot start simulator - unexpected exception", e); + return ResponseBuilder + .status(HttpStatus.INTERNAL_SERVER_ERROR.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Unexpected exception: " + e.getMessage()) + .build(); + } + + return ResponseBuilder + .status(HttpStatus.OK.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Simulator started") + .build(); + } + + @GetMapping("status") + public ResponseEntity status() { + + if (simulator != null && simulator.isAlive()) { + + ResponseBuilder responseBuilder = ResponseBuilder + .status(HttpStatus.OK.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(SIMULATOR_STATUS, "RUNNING"); + + if (!simulator.isEndless()) { + responseBuilder.put(REMAINING_TIME, simulator.getRemainingTime()); + } + return responseBuilder.build(); + } else { + return ResponseBuilder + .status(HttpStatus.OK.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(SIMULATOR_STATUS, "NOT RUNNING") + .build(); + } + } + + @PostMapping("stop") + public ResponseEntity stop() { + + if (simulator != null && simulator.isAlive()) { + simulator.interrupt(); + + return ResponseBuilder + .status(HttpStatus.OK.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Simulator successfully stopped") + .build(); + } else { + return ResponseBuilder + .status(HttpStatus.BAD_REQUEST.value()) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot stop simulator, because it's not running") + .build(); + } + } +} + diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java new file mode 100644 index 000000000..73443d06e --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.rest.util; + +import java.text.DateFormat; +import java.util.Date; + +public final class DateUtil { + + private DateUtil() { + } + + public static String getTimestamp(DateFormat dateFormat) { + + return dateFormat.format(new Date()); + } +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java new file mode 100644 index 000000000..31d22a713 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.rest.util; + +import java.util.LinkedHashMap; +import java.util.Map; +import org.springframework.http.ResponseEntity; + +public class ResponseBuilder { + + public static final String TIMESTAMP = "timestamp"; + public static final String MESSAGE = "message"; + public static final String SIMULATOR_STATUS = "simulatorStatus"; + public static final String REMAINING_TIME = "remainingTime"; + + private int statusCode; + private Map<String, Object> body = new LinkedHashMap<>(); + + private ResponseBuilder(int statusCode) { + this.statusCode = statusCode; + } + + public static ResponseBuilder status(int statusCode) { + + return new ResponseBuilder(statusCode); + } + + public ResponseBuilder put(String key, Object value) { + + body.put(key, value); + return this; + } + + public ResponseEntity build() { + + if (body.isEmpty()) { + return ResponseEntity.status(statusCode).build(); + } + + return ResponseEntity.status(statusCode).body(body); + } + +} diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java index ff2ca862a..0c713e127 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java @@ -25,41 +25,60 @@ import java.time.Instant; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; -import org.onap.pnfsimulator.simulator.client.HttpClientProvider; +import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; -public class Simulator { +public class Simulator extends Thread { - private static final Logger logger = LogManager.getLogger(HttpClientProvider.class); - private HttpClientProvider clientProvider; + private static final Logger LOGGER = LogManager.getLogger(Simulator.class); + private HttpClientAdapter clientProvider; private JSONObject messageBody; + private Instant endTime; private Duration duration; private Duration interval; + private final boolean isEndless; public Simulator(String vesServerUrl, JSONObject messageBody, Duration duration, Duration interval) { this.messageBody = messageBody; this.duration = duration; this.interval = interval; - this.clientProvider = new HttpClientProvider(vesServerUrl); + this.clientProvider = new HttpClientAdapter(vesServerUrl); + this.isEndless = duration.getSeconds() == 0; } - public void start() { - logger.info("SIMULATOR STARTED - DURATION: {}s, INTERVAL: {}s", duration.getSeconds(), interval.getSeconds()); + public void run() { + LOGGER.info("Simulation started - duration: " + getDuration() + ", interval: {}s", interval.getSeconds()); - Instant endTime = Instant.now().plus(duration); - while (runningTimeNotExceeded(endTime)) { + endTime = Instant.now().plus(duration); + boolean isEndless = isEndless(); + while (isEndless || runningTimeNotExceeded()) { try { - logger.info(()-> "MESSAGE TO BE SENT:\n" + messageBody.toString(4)); + LOGGER.debug("Message to be sent:\n" + messageBody.toString(4)); clientProvider.sendMsg(messageBody.toString()); Thread.sleep(interval.toMillis()); } catch (InterruptedException e) { - logger.error("SIMULATOR INTERRUPTED"); - break; + LOGGER.info("Simulation interrupted"); + return; } } - logger.info("SIMULATOR FINISHED"); + LOGGER.info("Simulation finished"); } - private boolean runningTimeNotExceeded(Instant endTime) { + public boolean isEndless() { + return isEndless; + } + + private String getDuration() { + return isEndless() ? "infinity" : duration.getSeconds() + "s"; + } + + private boolean runningTimeNotExceeded() { return Instant.now().isBefore(endTime); } + + public long getRemainingTime(){ + return Duration.between(Instant.now(), endTime).getSeconds(); + } + public String getMessage(){ + return messageBody.toString(4); + } }
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java index e3a003831..7f1b0a808 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java @@ -20,15 +20,12 @@ package org.onap.pnfsimulator.simulator; +import static java.lang.Integer.*; import static org.onap.pnfsimulator.message.MessageConstants.MESSAGE_INTERVAL; import static org.onap.pnfsimulator.message.MessageConstants.TEST_DURATION; +import static org.onap.pnfsimulator.message.MessageConstants.VES_SERVER_URL; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.util.List; -import org.apache.commons.io.FileUtils; import org.json.JSONObject; import org.onap.pnfsimulator.message.MessageProvider; import org.onap.pnfsimulator.simulator.validation.ParamsValidator; @@ -38,23 +35,23 @@ public class SimulatorFactory { private MessageProvider messageProvider; - public SimulatorFactory(MessageProvider messageProvider) { + public static SimulatorFactory usingMessageProvider(MessageProvider messageProvider) { + return new SimulatorFactory(messageProvider); + } + + private SimulatorFactory(MessageProvider messageProvider) { this.messageProvider = messageProvider; } - public Simulator create(String vesServerUrl, String configFilePath) throws IOException, ValidationException { + public Simulator create(JSONObject simulatorParams, JSONObject messageParams) throws ValidationException { - String configJson = FileUtils.readFileToString(new File(configFilePath), StandardCharsets.UTF_8); - JSONObject configObject = new JSONObject(configJson); - ParamsValidator.forObject(configObject).validate(); + ParamsValidator.forParams(simulatorParams, messageParams).validate(); - Duration duration = Duration.ofSeconds(parseJsonField(configObject, TEST_DURATION)); - Duration interval = Duration.ofSeconds(parseJsonField(configObject, MESSAGE_INTERVAL)); - JSONObject messageBody = messageProvider.createMessage(configObject); - return new Simulator(vesServerUrl, messageBody, duration, interval); - } + Duration duration = Duration.ofSeconds(parseInt(simulatorParams.getString(TEST_DURATION))); + Duration interval = Duration.ofSeconds(parseInt(simulatorParams.getString(MESSAGE_INTERVAL))); + String vesServerUrl = simulatorParams.getString(VES_SERVER_URL); - private int parseJsonField(JSONObject json, String fieldName) { - return Integer.parseInt((String) json.remove(fieldName)); + JSONObject messageBody = messageProvider.createMessage(messageParams); + return new Simulator(vesServerUrl, messageBody, duration, interval); } }
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientProvider.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java index 54d2c9fbb..35f0b6820 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientProvider.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java @@ -31,16 +31,16 @@ import org.apache.http.impl.client.HttpClientBuilder; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -public class HttpClientProvider { +public class HttpClientAdapter { - private static final Logger logger = LogManager.getLogger(HttpClientProvider.class); + private static final Logger LOGGER = LogManager.getLogger(HttpClientAdapter.class); private static final String CONTENT_TYPE = "Content-Type"; private static final String APPLICATION_JSON = "application/json"; private HttpClient client; private String url; - public HttpClientProvider(String url) { + public HttpClientAdapter(String url) { RequestConfig config = RequestConfig.custom() .setConnectTimeout(1000) @@ -60,9 +60,9 @@ public class HttpClientProvider { try { HttpPost request = createRequest(content); HttpResponse response = client.execute(request); - logger.info("MESSAGE SENT, VES RESPONSE CODE: {}", response.getStatusLine()); + LOGGER.info("MESSAGE SENT, VES RESPONSE CODE: {}", response.getStatusLine()); } catch (IOException e) { - logger.info("ERROR SENDING MESSAGE TO VES: {}", e.getMessage()); + LOGGER.info("ERROR SENDING MESSAGE TO VES: {}", e.getMessage()); } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ParamsValidator.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ParamsValidator.java index 6cdb781f1..3c8459473 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ParamsValidator.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ParamsValidator.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.simulator.validation; import static org.onap.pnfsimulator.message.MessageConstants.MESSAGE_INTERVAL; @@ -6,13 +26,15 @@ import static org.onap.pnfsimulator.message.MessageConstants.PNF_OAM_IPV6_ADDRES import static org.onap.pnfsimulator.message.MessageConstants.PNF_SERIAL_NUMBER; import static org.onap.pnfsimulator.message.MessageConstants.PNF_VENDOR_NAME; import static org.onap.pnfsimulator.message.MessageConstants.TEST_DURATION; +import static org.onap.pnfsimulator.message.MessageConstants.VES_SERVER_URL; import com.google.common.collect.ImmutableMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.function.Predicate; +import java.util.function.BiPredicate; import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; @@ -20,33 +42,50 @@ import org.json.JSONObject; public class ParamsValidator { private final static String MISSING_PARAMS_MESSAGE = "Following mandatory params are missing:\n"; - private final Map<String, Predicate<String>> validators = ImmutableMap - .<String, Predicate<String>>builder() + + private final Map<String, BiPredicate<String, JSONObject>> simulatorParamsValidators = ImmutableMap + .<String, BiPredicate<String, JSONObject>>builder() + .put(VES_SERVER_URL, this::isDefined) .put(TEST_DURATION, this::isNumeric) .put(MESSAGE_INTERVAL, this::isNumeric) + .build(); + + private final Map<String, BiPredicate<String, JSONObject>> messageParamsValidators = ImmutableMap + .<String, BiPredicate<String, JSONObject>>builder() .put(PNF_SERIAL_NUMBER, this::isDefined) .put(PNF_VENDOR_NAME, this::isDefined) .put(PNF_OAM_IPV4_ADDRESS, this::isDefined) .put(PNF_OAM_IPV6_ADDRESS, this::isDefined) .build(); - private JSONObject subject; + private JSONObject simulatorParams; + private JSONObject messageParams; - private ParamsValidator(JSONObject paramsObject) { - subject = paramsObject; + private ParamsValidator(JSONObject simulatorParams, JSONObject messageParams) { + this.simulatorParams = simulatorParams; + this.messageParams = messageParams; } - public static ParamsValidator forObject(JSONObject configObject) { - return new ParamsValidator(configObject); + public static ParamsValidator forParams(JSONObject simulatorParams, JSONObject messageParams) { + return new ParamsValidator(simulatorParams, messageParams); } public void validate() throws ValidationException { - List<String> missingParams = validators + Stream<String> missingSimulatorParams = simulatorParamsValidators .entrySet() .stream() - .filter(entry -> !entry.getValue().test(entry.getKey())) - .map(Entry::getKey) + .filter(entry -> !entry.getValue().test(entry.getKey(), simulatorParams)) + .map(Entry::getKey); + + Stream<String> missingMessageParams = messageParamsValidators + .entrySet() + .stream() + .filter(entry -> !entry.getValue().test(entry.getKey(), messageParams)) + .map(Entry::getKey); + + List<String> missingParams = Stream + .concat(missingMessageParams, missingSimulatorParams) .collect(Collectors.toList()); resolveMissingIP(missingParams); @@ -63,12 +102,13 @@ public class ParamsValidator { .collect(Collectors.joining("\n")); } - private boolean isNumeric(String param) { - return isDefined(param) && StringUtils.isNumeric(subject.getString(param)); + private boolean isNumeric(String param, JSONObject container) { + return isDefined(param, container) && StringUtils.isNumeric(container.getString(param)); } - private boolean isDefined(String param) { - return subject.has(param) && !subject.getString(param).isEmpty(); + private boolean isDefined(String param, JSONObject container) { + + return container.has(param) && !container.getString(param).isEmpty(); } private void resolveMissingIP(List<String> missingParams) { diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java index 9855a784e..086997f85 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java @@ -1,3 +1,23 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.integration + * ================================================================================ + * 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.pnfsimulator.simulator.validation; public class ValidationException extends Exception { diff --git a/test/mocks/pnfsimulator/src/main/resources/application.properties b/test/mocks/pnfsimulator/src/main/resources/application.properties new file mode 100644 index 000000000..888dcec44 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=5000
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/resources/log4j2.xml b/test/mocks/pnfsimulator/src/main/resources/log4j2.xml index 250f41709..d3941d32d 100644 --- a/test/mocks/pnfsimulator/src/main/resources/log4j2.xml +++ b/test/mocks/pnfsimulator/src/main/resources/log4j2.xml @@ -2,17 +2,22 @@ <Configuration status="WARN"> <Properties> <Property name="log4j.logLevel" value="info"/> - </Properties> + </Properties> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{ISO8601} +%r [%t] %-5p %c %x - %m%n"/> </Console> <Console name="ColorConsole" target="SYSTEM_OUT"> - <PatternLayout pattern="%style{%d{ISO8601} +%r}{yellow} %highlight{%-5level}{STYLE=Logback} %style{[%t]}{yellow} %style{%c{1.}}{BRIGHT} %message%n"/> + <PatternLayout + pattern="%style{%d{ISO8601} +%r}{yellow} %highlight{%-5level}{STYLE=Logback} %style{[%t]}{yellow} %style{%c{1.}}{BRIGHT} %message%n"/> </Console> + <File name="File" fileName="/var/log/pnfsimulator.log"> + <PatternLayout pattern="%d{ISO8601} +%r [%t] %-5p %c %x - %m%n"/> + </File> </Appenders> <Loggers> <Root level="${sys:log4j.logLevel}"> + <AppenderRef ref="File"/> <AppenderRef ref="ColorConsole"/> </Root> </Loggers> |