diff options
Diffstat (limited to 'test/mocks/pnfsimulator/src/main/java/org/onap')
21 files changed, 429 insertions, 577 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 0e9fe4d3d..9a4f55ad4 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 @@ -1,33 +1,29 @@ -/*- - * ============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; +import org.onap.pnfsimulator.message.MessageProvider; +import org.onap.pnfsimulator.simulator.validation.JSONValidator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync public class Main { + public static void main(String[] args) { SpringApplication.run(Main.class, args); } + + @Bean + public MessageProvider messageProvider() { + return new MessageProvider(); + } + + @Bean + public JSONValidator jsonValidator() { + return new JSONValidator(); + } } + + diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java new file mode 100644 index 000000000..ca65b55c9 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java @@ -0,0 +1,15 @@ +package org.onap.pnfsimulator.logging; + +public final class MDCVariables { + + public static final String X_ONAP_REQUEST_ID = "X-ONAP-RequestID"; + public static final String X_INVOCATION_ID = "X-InvocationID"; + public static final String REQUEST_ID = "RequestID"; + public static final String INVOCATION_ID = "InvocationID"; + public static final String INSTANCE_UUID = "InstanceUUID"; + public static final String RESPONSE_CODE = "ResponseCode"; + public static final String SERVICE_NAME = "ServiceName"; + + private MDCVariables() { + } +} 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 8e7c6fcfd..a0930a651 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 @@ -1,23 +1,3 @@ -/*- - * ============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.message; public final class MessageConstants { 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 44ca9666c..b21eed4fc 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 @@ -1,27 +1,8 @@ -/*- - * ============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.message; import static org.onap.pnfsimulator.message.MessageConstants.COMMON_EVENT_HEADER; import static org.onap.pnfsimulator.message.MessageConstants.DOMAIN; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT; import static org.onap.pnfsimulator.message.MessageConstants.EVENT_ID; import static org.onap.pnfsimulator.message.MessageConstants.EVENT_TYPE; import static org.onap.pnfsimulator.message.MessageConstants.INTERNAL_HEADER_FIELDS; @@ -35,7 +16,6 @@ import static org.onap.pnfsimulator.message.MessageConstants.PRIORITY; import static org.onap.pnfsimulator.message.MessageConstants.SEQUENCE; import static org.onap.pnfsimulator.message.MessageConstants.START_EPOCH_MICROSEC; import static org.onap.pnfsimulator.message.MessageConstants.VERSION; -import static org.onap.pnfsimulator.message.MessageConstants.EVENT; import java.util.Map; import java.util.UUID; @@ -45,11 +25,11 @@ public class MessageProvider { public JSONObject createMessage(JSONObject params) { - if(params == null){ + if (params == null) { throw new IllegalArgumentException("Params object cannot be null"); } - Map<String, Object> paramsMap = params.toMap(); + Map<String, Object> paramsMap = params.toMap(); JSONObject root = new JSONObject(); JSONObject commonEventHeader = generateConstantCommonEventHeader(); JSONObject otherFields = generateConstantOtherFields(); 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 index b4eda0a79..edbb195c8 100644 --- 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 @@ -1,37 +1,17 @@ -/*- - * ============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 java.io.IOException; +import java.util.TimerTask; 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; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class NetconfConfigurationCheckingTask extends TimerTask { - private static final Logger LOGGER = LogManager.getLogger(NetconfConfigurationCheckingTask.class); + + private static final Logger LOGGER = LoggerFactory.getLogger(NetconfConfigurationCheckingTask.class); private final NetconfConfigurationReader reader; private final NetconfConfigurationWriter writer; @@ -47,16 +27,15 @@ public class NetconfConfigurationCheckingTask extends TimerTask { @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); + String currentConfiguration = reader.read(); + if (!currentConfiguration.equals(cache.getConfiguration())) { + LOGGER.info("Configuration has changed, new configuration:\n\n{}", currentConfiguration); + writer.writeToFile(currentConfiguration); + cache.update(currentConfiguration); + } + } catch (IOException | JNCException e) { + LOGGER.warn("Error during configuration reading: {}", e.getMessage()); } } } 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 index c4d6198f7..ab6925b00 100644 --- 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 @@ -1,38 +1,20 @@ -/*- - * ============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 java.io.IOException; +import java.util.Timer; +import javax.annotation.PostConstruct; import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; 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 Logger LOGGER = LoggerFactory.getLogger(NetconfMonitorService.class); private static final long timePeriod = 1000L; private static final long startDelay = 0; @@ -53,15 +35,19 @@ public class NetconfMonitorService { } @PostConstruct - public void start() throws IOException, JNCException { + public void start() { setStartConfiguration(); - NetconfConfigurationCheckingTask task = new NetconfConfigurationCheckingTask(reader, writer, cache); + 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); + private void setStartConfiguration() { + try { + String configuration = reader.read(); + writer.writeToFile(configuration); + cache.update(configuration); + } catch (IOException | JNCException e) { + LOGGER.warn("Error during configuration reading: {}", e.getMessage()); + } } } 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 index 82ea85aee..be804a5dc 100644 --- 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 @@ -1,40 +1,25 @@ -/*- - * ============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 com.tailf.jnc.SSHConnection; +import com.tailf.jnc.SSHSession; import java.io.IOException; import java.util.Map; import java.util.Timer; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; +import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConnectionParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; @Configuration public class NetconfMonitorServiceConfiguration { - private static final Logger LOGGER = LogManager.getLogger(NetconfMonitorServiceConfiguration.class); + + private static final Logger LOGGER = LoggerFactory.getLogger(NetconfMonitorServiceConfiguration.class); private static final Map<String, String> enviroment = System.getenv(); private static final String LOG_PATH = "/var/log"; @@ -44,7 +29,7 @@ public class NetconfMonitorServiceConfiguration { 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 String DEFAULT_NETCONF_ADDRESS = "localhost"; 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"; @@ -64,12 +49,18 @@ public class NetconfMonitorServiceConfiguration { @Bean public NetconfConfigurationReader configurationReader() throws IOException, JNCException { - NetconfConnectionParams params = createConnectionParams(); + NetconfConnectionParams params = resolveConnectionParams(); LOGGER.info("Configuration params are : {}", params); - NetconfSession session = NetconfSessionFactory.create(params); + NetconfSession session = createNetconfSession(params); return new NetconfConfigurationReader(session, buildModelPath()); } + NetconfSession createNetconfSession(NetconfConnectionParams params) throws IOException, JNCException { + SSHConnection sshConnection = new SSHConnection(params.address, params.port); + sshConnection.authenticateWithPassword(params.user, params.password); + return new NetconfSession( new SSHSession(sshConnection)); + } + @Bean public NetconfConfigurationWriter netconfConfigurationWriter() { return new NetconfConfigurationWriter(LOG_PATH); @@ -77,22 +68,24 @@ public class NetconfMonitorServiceConfiguration { private String buildModelPath() { return String.format("/%s:%s", - enviroment.getOrDefault(NETCONF_MODEL, DEFAULT_NETCONF_MODEL), - enviroment.getOrDefault(NETCONF_MAIN_CONTAINER, DEFAULT_NETCONF_MAIN_CONTAINER)); + enviroment.getOrDefault(NETCONF_MODEL, DEFAULT_NETCONF_MODEL), + enviroment.getOrDefault(NETCONF_MAIN_CONTAINER, DEFAULT_NETCONF_MAIN_CONTAINER)); } - private NetconfConnectionParams createConnectionParams() { + NetconfConnectionParams resolveConnectionParams() { return new NetconfConnectionParams( - enviroment.getOrDefault(NETCONF_ADDRESS, DEFAULT_NETCONF_ADDRESS), - resolveNetconfPort(), - DEFAULT_NETCONF_USER, - DEFAULT_NETCONF_PASSWORD); + 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) { + LOGGER.warn("Invalid netconf port: {}. Default netconf port {} is set.", e.getMessage(), + DEFAULT_NETCONF_PORT); 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 index 820234620..852346db2 100644 --- 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 @@ -1,26 +1,7 @@ -/*- - * ============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() { 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 index e8979254d..8bd1a57a0 100644 --- 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 @@ -1,31 +1,11 @@ -/*- - * ============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; 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 index 4c3d53e39..93934f080 100644 --- 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 @@ -1,37 +1,17 @@ -/*- - * ============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 java.text.DateFormat; +import java.text.SimpleDateFormat; import org.onap.pnfsimulator.rest.util.DateUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class NetconfConfigurationWriter { - private static final Logger LOGGER = LogManager.getLogger(NetconfConfigurationWriter.class); + + private static final Logger LOGGER = LoggerFactory.getLogger(NetconfConfigurationWriter.class); private static final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); private String pathToLog; @@ -45,7 +25,7 @@ public class NetconfConfigurationWriter { writer.write(configuration); LOGGER.info("Configuration wrote to file {}/{} ", pathToLog, fileName); } catch (IOException e) { - LOGGER.info("Failed to write configuration to file: {}", e.getMessage()); + LOGGER.warn("Failed to write configuration to file: {}", e.getMessage()); } } } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java index 3130d2b06..df95269c3 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java @@ -1,26 +1,7 @@ -/*- - * ============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 NetconfConnectionParams { + public final String address; public final int port; public final String user; @@ -36,9 +17,9 @@ public class NetconfConnectionParams { @Override public String toString() { return String.format("NetconfConnectionParams{address=%s, port=%d, user=%s, password=%s}", - address, - port, - user, - password); + 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 deleted file mode 100644 index 4f31af5eb..000000000 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfSessionFactory.java +++ /dev/null @@ -1,39 +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.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 index 46a63a21c..fd4f7a987 100644 --- 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 @@ -1,49 +1,47 @@ -/*- - * ============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.logging.MDCVariables.INSTANCE_UUID; +import static org.onap.pnfsimulator.logging.MDCVariables.INVOCATION_ID; +import static org.onap.pnfsimulator.logging.MDCVariables.REQUEST_ID; +import static org.onap.pnfsimulator.logging.MDCVariables.RESPONSE_CODE; +import static org.onap.pnfsimulator.logging.MDCVariables.SERVICE_NAME; +import static org.onap.pnfsimulator.logging.MDCVariables.X_INVOCATION_ID; +import static org.onap.pnfsimulator.logging.MDCVariables.X_ONAP_REQUEST_ID; 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 static org.springframework.http.HttpStatus.BAD_REQUEST; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; +import static org.springframework.http.HttpStatus.OK; +import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import com.github.fge.jsonschema.core.exceptions.ProcessingException; +import java.util.UUID; 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.JSONValidator; import org.onap.pnfsimulator.simulator.validation.ValidationException; -import org.springframework.http.HttpStatus; +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.HttpHeaders; 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.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -52,87 +50,104 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/simulator") public class SimulatorController { - private static final Logger LOGGER = LogManager.getLogger(Simulator.class); + private static final Logger LOGGER = LoggerFactory.getLogger(Simulator.class); private static final DateFormat RESPONSE_DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss,SSS"); - + private final Marker ENTRY = MarkerFactory.getMarker("ENTRY"); private Simulator simulator; + private JSONValidator validator; + private SimulatorFactory factory; - @PostMapping("start") - public ResponseEntity start(@RequestBody String message) { + @Autowired + public SimulatorController(JSONValidator validator, SimulatorFactory factory) { + this.validator = validator; + this.factory = factory; + } - if (simulator != null && simulator.isAlive()) { + @PostMapping("start") + public ResponseEntity start(@RequestHeader HttpHeaders headers, @RequestBody String message) { + MDC.put(REQUEST_ID, headers.getFirst(X_ONAP_REQUEST_ID)); + MDC.put(INVOCATION_ID, headers.getFirst(X_INVOCATION_ID)); + MDC.put(INSTANCE_UUID, UUID.randomUUID().toString()); + MDC.put(SERVICE_NAME, "/simulator/start"); + LOGGER.info(ENTRY,"Simulator starting"); + + if (isSimulatorRunning()) { + MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); return ResponseBuilder - .status(HttpStatus.BAD_REQUEST.value()) + .status(BAD_REQUEST) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(MESSAGE, "Cannot start simulator since it's already running") .build(); } try { + validator.validate(message, "json_schema/input_validator.json"); + 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 = factory.create(simulatorParams, messageParams); simulator.start(); - } catch (JSONException e) { + MDC.put(RESPONSE_CODE, OK.toString()); + return ResponseBuilder + .status(OK) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Simulator started") + .build(); - LOGGER.error("Cannot start simulator, invalid json format: " + e.getMessage()); - LOGGER.debug("Received json has invalid format:\n" + message); + } catch (JSONException e) { + MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); + LOGGER.warn("Cannot start simulator, invalid json format: {}", e.getMessage()); + LOGGER.debug("Received json has invalid format", e); return ResponseBuilder - .status(HttpStatus.BAD_REQUEST.value()) + .status(BAD_REQUEST) .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"); + } catch (ProcessingException | ValidationException | IOException e) { + MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); + LOGGER.warn("Json validation failed: {}", e.getMessage()); return ResponseBuilder - .status(HttpStatus.BAD_REQUEST.value()) + .status(BAD_REQUEST) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) - .put(MESSAGE, e.getMessage()) + .put(MESSAGE, "Cannot start simulator - Json format is not compatible with schema definitions") .build(); - } catch (RuntimeException e) { - + } catch (Exception e) { + MDC.put(RESPONSE_CODE, INTERNAL_SERVER_ERROR.toString()); LOGGER.error("Cannot start simulator - unexpected exception", e); return ResponseBuilder - .status(HttpStatus.INTERNAL_SERVER_ERROR.value()) + .status(INTERNAL_SERVER_ERROR) .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(); + finally { + MDC.clear(); + } } @GetMapping("status") public ResponseEntity status() { - - if (simulator != null && simulator.isAlive()) { - + if (isSimulatorRunning()) { ResponseBuilder responseBuilder = ResponseBuilder - .status(HttpStatus.OK.value()) + .status(OK) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(SIMULATOR_STATUS, "RUNNING"); - if (!simulator.isEndless()) { - responseBuilder.put(REMAINING_TIME, simulator.getRemainingTime()); - } - return responseBuilder.build(); + return !simulator.isEndless() ? + responseBuilder + .put(REMAINING_TIME, simulator.getRemainingTime()) + .build() : + responseBuilder + .build(); } else { return ResponseBuilder - .status(HttpStatus.OK.value()) + .status(OK) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(SIMULATOR_STATUS, "NOT RUNNING") .build(); @@ -141,22 +156,25 @@ public class SimulatorController { @PostMapping("stop") public ResponseEntity stop() { - - if (simulator != null && simulator.isAlive()) { + if (isSimulatorRunning()) { simulator.interrupt(); return ResponseBuilder - .status(HttpStatus.OK.value()) + .status(OK) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(MESSAGE, "Simulator successfully stopped") .build(); } else { return ResponseBuilder - .status(HttpStatus.BAD_REQUEST.value()) + .status(BAD_REQUEST) .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) .put(MESSAGE, "Cannot stop simulator, because it's not running") .build(); } } + + private boolean isSimulatorRunning() { + return simulator != null && simulator.isAlive(); + } } 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 index 73443d06e..f48611c6b 100644 --- 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 @@ -1,23 +1,3 @@ -/*- - * ============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; 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 index 31d22a713..25c040e06 100644 --- 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 @@ -1,27 +1,8 @@ -/*- - * ============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.HttpStatus; import org.springframework.http.ResponseEntity; public class ResponseBuilder { @@ -31,16 +12,16 @@ public class ResponseBuilder { public static final String SIMULATOR_STATUS = "simulatorStatus"; public static final String REMAINING_TIME = "remainingTime"; - private int statusCode; + private HttpStatus httpStatus; private Map<String, Object> body = new LinkedHashMap<>(); - private ResponseBuilder(int statusCode) { - this.statusCode = statusCode; + private ResponseBuilder(HttpStatus httpStatus) { + this.httpStatus = httpStatus; } - public static ResponseBuilder status(int statusCode) { + public static ResponseBuilder status(HttpStatus httpStatus) { - return new ResponseBuilder(statusCode); + return new ResponseBuilder(httpStatus); } public ResponseBuilder put(String key, Object value) { @@ -52,10 +33,10 @@ public class ResponseBuilder { public ResponseEntity build() { if (body.isEmpty()) { - return ResponseEntity.status(statusCode).build(); + return ResponseEntity.status(httpStatus).build(); } - return ResponseEntity.status(statusCode).body(body); + return ResponseEntity.status(httpStatus).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 0c713e127..4051dcfb0 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 @@ -1,70 +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.simulator; import java.time.Duration; import java.time.Instant; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; +import java.util.Map; import org.json.JSONObject; import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; +import org.onap.pnfsimulator.simulator.client.HttpClientAdapterImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; public class Simulator extends Thread { - private static final Logger LOGGER = LogManager.getLogger(Simulator.class); - private HttpClientAdapter clientProvider; + private static final Logger LOGGER = LoggerFactory.getLogger(Simulator.class); + private final Marker EXIT = MarkerFactory.getMarker("EXIT"); + private Map<String,String> contextMap = MDC.getCopyOfContextMap(); + private boolean isEndless; + private String vesUrl; + private HttpClientAdapter httpClient; 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 HttpClientAdapter(vesServerUrl); - this.isEndless = duration.getSeconds() == 0; + private Instant endTime; + + private Simulator() { } - public void run() { - LOGGER.info("Simulation started - duration: " + getDuration() + ", interval: {}s", interval.getSeconds()); + public static Builder builder() { + return new Builder(); + } + public void run() { + setMdcContextMap(contextMap); + LOGGER.info("Simulation started - duration: {}, interval: {}s", getDuration(), interval.getSeconds()); endTime = Instant.now().plus(duration); - boolean isEndless = isEndless(); while (isEndless || runningTimeNotExceeded()) { try { - LOGGER.debug("Message to be sent:\n" + messageBody.toString(4)); - clientProvider.sendMsg(messageBody.toString()); + LOGGER.debug("Message to be sent:\n" + getMessage()); + httpClient.send(messageBody.toString(), vesUrl); Thread.sleep(interval.toMillis()); } catch (InterruptedException e) { LOGGER.info("Simulation interrupted"); return; } } - LOGGER.info("Simulation finished"); + LOGGER.info(EXIT, "Simulation finished"); + MDC.clear(); } - public boolean isEndless() { - return isEndless; + private void setMdcContextMap(Map<String,String> mdcContextMap) { + if(mdcContextMap != null) + MDC.setContextMap(mdcContextMap); + } + + private String getMessage() { + return messageBody.toString(4); } private String getDuration() { @@ -75,10 +67,65 @@ public class Simulator extends Thread { return Instant.now().isBefore(endTime); } - public long getRemainingTime(){ + public boolean isEndless() { + return isEndless; + } + + public long getRemainingTime() { return Duration.between(Instant.now(), endTime).getSeconds(); } - public String getMessage(){ - return messageBody.toString(4); + + public static class Builder { + + private String vesUrl; + private HttpClientAdapter httpClient; + private JSONObject messageBody; + private Duration duration; + private Duration interval; + + private Builder() { + this.vesUrl = ""; + this.httpClient = new HttpClientAdapterImpl(); + this.messageBody = new JSONObject(); + this.duration = Duration.ZERO; + this.interval = Duration.ZERO; + } + + public Builder withVesUrl(String vesUrl) { + this.vesUrl = vesUrl; + return this; + } + + public Builder withCustomHttpClientAdapter(HttpClientAdapter httpClient) { + this.httpClient = httpClient; + return this; + } + + public Builder withMessageBody(JSONObject messageBody) { + this.messageBody = messageBody; + return this; + } + + public Builder withDuration(Duration duration) { + this.duration = duration; + return this; + } + + + public Builder withInterval(Duration interval) { + this.interval = interval; + return this; + } + + public Simulator build() { + Simulator simulator = new Simulator(); + simulator.vesUrl = this.vesUrl; + simulator.httpClient = this.httpClient; + simulator.messageBody = this.messageBody; + simulator.duration = this.duration; + simulator.interval = this.interval; + simulator.isEndless = duration.equals(Duration.ZERO); + return simulator; + } } }
\ 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 7f1b0a808..443f1547c 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 @@ -1,57 +1,48 @@ -/*- - * ============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; -import static java.lang.Integer.*; +import static java.lang.Integer.parseInt; 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 com.github.fge.jsonschema.core.exceptions.ProcessingException; +import java.io.IOException; import java.time.Duration; import org.json.JSONObject; import org.onap.pnfsimulator.message.MessageProvider; -import org.onap.pnfsimulator.simulator.validation.ParamsValidator; +import org.onap.pnfsimulator.simulator.validation.JSONValidator; import org.onap.pnfsimulator.simulator.validation.ValidationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +@Service public class SimulatorFactory { - private MessageProvider messageProvider; + private static final String DEFAULT_OUTPUT_SCHEMA_PATH = "json_schema/output_validator.json"; - public static SimulatorFactory usingMessageProvider(MessageProvider messageProvider) { - return new SimulatorFactory(messageProvider); - } + private MessageProvider messageProvider; + private JSONValidator validator; - private SimulatorFactory(MessageProvider messageProvider) { + @Autowired + public SimulatorFactory(MessageProvider messageProvider, JSONValidator validator) { this.messageProvider = messageProvider; + this.validator = validator; } - public Simulator create(JSONObject simulatorParams, JSONObject messageParams) throws ValidationException { - - ParamsValidator.forParams(simulatorParams, messageParams).validate(); - + public Simulator create(JSONObject simulatorParams, JSONObject messageParams) + throws ProcessingException, IOException, ValidationException { 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); + String vesUrl = simulatorParams.getString(VES_SERVER_URL); JSONObject messageBody = messageProvider.createMessage(messageParams); - return new Simulator(vesServerUrl, messageBody, duration, interval); + validator.validate(messageBody.toString(), DEFAULT_OUTPUT_SCHEMA_PATH); + + return Simulator.builder() + .withVesUrl(vesUrl) + .withDuration(duration) + .withInterval(interval) + .withMessageBody(messageBody) + .build(); } }
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java index 35f0b6820..020cb8416 100644 --- a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapter.java @@ -1,76 +1,6 @@ -/*- - * ============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.client; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -public class HttpClientAdapter { - - 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 HttpClientAdapter(String url) { - - RequestConfig config = RequestConfig.custom() - .setConnectTimeout(1000) - .setConnectionRequestTimeout(1000) - .setSocketTimeout(1000) - .build(); - - this.client = HttpClientBuilder - .create() - .setDefaultRequestConfig(config) - .build(); - - this.url = url; - } - - public void sendMsg(String content) { - try { - HttpPost request = createRequest(content); - HttpResponse response = client.execute(request); - LOGGER.info("MESSAGE SENT, VES RESPONSE CODE: {}", response.getStatusLine()); - } catch (IOException e) { - LOGGER.info("ERROR SENDING MESSAGE TO VES: {}", e.getMessage()); - } - } +public interface HttpClientAdapter { - private HttpPost createRequest(String content) throws UnsupportedEncodingException { - StringEntity stringEntity = new StringEntity(content); - HttpPost request = new HttpPost(url); - request.addHeader(CONTENT_TYPE, APPLICATION_JSON); - request.setEntity(stringEntity); - return request; - } + void send(String content, String url); } diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java new file mode 100644 index 000000000..c38ac3efa --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImpl.java @@ -0,0 +1,67 @@ +package org.onap.pnfsimulator.simulator.client; + +import static org.onap.pnfsimulator.logging.MDCVariables.REQUEST_ID; +import static org.onap.pnfsimulator.logging.MDCVariables.X_INVOCATION_ID; +import static org.onap.pnfsimulator.logging.MDCVariables.X_ONAP_REQUEST_ID; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.UUID; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +public class HttpClientAdapterImpl implements HttpClientAdapter { + + private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientAdapterImpl.class); + private static final String CONTENT_TYPE = "Content-Type"; + private static final String APPLICATION_JSON = "application/json"; + private final Marker INVOKE = MarkerFactory.getMarker("INVOKE"); + private static final RequestConfig CONFIG = RequestConfig.custom() + .setConnectTimeout(1000) + .setConnectionRequestTimeout(1000) + .setSocketTimeout(1000) + .build(); + + private HttpClient client; + + public HttpClientAdapterImpl(HttpClient client) { + this.client = client; + } + + public HttpClientAdapterImpl() { + this.client = HttpClientBuilder + .create() + .setDefaultRequestConfig(CONFIG) + .build(); + } + + @Override + public void send(String content, String url) { + try { + HttpPost request = createRequest(content, url); + HttpResponse response = client.execute(request); + LOGGER.info(INVOKE, "Message sent, ves response code: {}", response.getStatusLine()); + } catch (IOException e) { + LOGGER.warn("Error sending message to ves: {}", e.getMessage()); + } + } + + private HttpPost createRequest(String content, String url) throws UnsupportedEncodingException { + HttpPost request = new HttpPost(url); + StringEntity stringEntity = new StringEntity(content); + request.addHeader(CONTENT_TYPE, APPLICATION_JSON); + request.addHeader(X_ONAP_REQUEST_ID, MDC.get(REQUEST_ID)); + request.addHeader(X_INVOCATION_ID, UUID.randomUUID().toString()); + request.setEntity(stringEntity); + return request; + } +}
\ No newline at end of file diff --git a/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/JSONValidator.java b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/JSONValidator.java new file mode 100644 index 000000000..37fd71a81 --- /dev/null +++ b/test/mocks/pnfsimulator/src/main/java/org/onap/pnfsimulator/simulator/validation/JSONValidator.java @@ -0,0 +1,46 @@ +package org.onap.pnfsimulator.simulator.validation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.github.fge.jackson.JsonLoader; +import com.github.fge.jsonschema.core.exceptions.ProcessingException; +import com.github.fge.jsonschema.core.report.LogLevel; +import com.github.fge.jsonschema.core.report.ProcessingMessage; +import com.github.fge.jsonschema.core.report.ProcessingReport; +import com.github.fge.jsonschema.main.JsonSchema; +import com.github.fge.jsonschema.main.JsonSchemaFactory; +import com.google.gson.JsonParser; +import java.io.FileReader; +import java.io.IOException; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +public class JSONValidator { + + public void validate(String data, String jsonSchemaPath) + throws ValidationException, ProcessingException, IOException { + String jsonSchema = readJsonSchemaAsString(jsonSchemaPath); + JsonNode jsonData = JsonLoader.fromString(data); + ProcessingReport report = createJsonSchema(jsonSchema).validate(jsonData); + + if (!report.isSuccess()) { + throw new ValidationException(constructValidationErrors(report)); + } + } + + private String readJsonSchemaAsString(String schemaPath) throws IOException { + try (FileReader reader = new FileReader(schemaPath)) { + return new JsonParser().parse(reader).toString(); + } + } + + private JsonSchema createJsonSchema(String schema) throws ProcessingException, IOException { + return JsonSchemaFactory.byDefault().getJsonSchema(JsonLoader.fromString(schema)); + } + + private String constructValidationErrors(ProcessingReport report) { + return StreamSupport.stream(report.spliterator(), false) + .filter(entry -> entry.getLogLevel() == LogLevel.ERROR) + .map(ProcessingMessage::getMessage) + .collect(Collectors.joining("\n")); + } +} 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 086997f85..9855a784e 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,23 +1,3 @@ -/*- - * ============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 { |