diff options
Diffstat (limited to 'pnf-sim-lightweight/src/main/java')
26 files changed, 1911 insertions, 0 deletions
diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/ConfigurationProvider.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/ConfigurationProvider.java new file mode 100644 index 0000000..15c687e --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/ConfigurationProvider.java @@ -0,0 +1,28 @@ +package org.onap.pnfsimulator; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import java.io.File; + +public class ConfigurationProvider { + static PnfSimConfig conf = null; + + public static PnfSimConfig getConfigInstance() { + + ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); + try { + File file = new File("./config/config.yml"); + + conf = mapper.readValue(file, PnfSimConfig.class); + System.out.println("Ves URL: " + conf.getUrlves()); + System.out.println("SFTP URL: " + conf.getUrlsftp()); + System.out.println("FTPS URL: " + conf.getUrlftps()); + System.out.println("PNF sim IP: " + conf.getIppnfsim()); + + } catch (Exception e) { + e.printStackTrace(); + } + return conf; + } + +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/FileProvider.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/FileProvider.java new file mode 100644 index 0000000..beb564d --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/FileProvider.java @@ -0,0 +1,41 @@ +package org.onap.pnfsimulator; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.onap.pnfsimulator.simulator.validation.NoRopFilesException; + +public class FileProvider { + + public List<String> getFiles() throws NoRopFilesException { + + List<String> files = queryFiles(); + + files.sort(Collections.reverseOrder()); + + List<String> fileListSorted = new ArrayList<>(); + for (String f : files) { + fileListSorted.add(f); + } + return fileListSorted; + } + + private static List<String> queryFiles() throws NoRopFilesException { + + File folder = new File("./files/onap/"); + File[] listOfFiles = folder.listFiles(); + if (listOfFiles == null || listOfFiles.length == 0) { + throw new NoRopFilesException("No ROP files found in specified directory"); + } + + List<String> results = new ArrayList<>(); + for (int i = 0; i < listOfFiles.length; i++) { + if (listOfFiles[i].isFile()) { + results.add(listOfFiles[i].getName()); + } + } + + return results; + } +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/Main.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/Main.java new file mode 100644 index 0000000..a66bedb --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/Main.java @@ -0,0 +1,53 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ 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 java.util.concurrent.TimeUnit; +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) throws InterruptedException { + SpringApplication.run(Main.class, args); + + TimeUnit.SECONDS.sleep(5); + System.out.println("Start sending VES events"); + + + } + + @Bean + public MessageProvider messageProvider() { + return new MessageProvider(); + } + + @Bean + public JSONValidator jsonValidator() { + return new JSONValidator(); + } + +} + + diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/PnfSimConfig.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/PnfSimConfig.java new file mode 100644 index 0000000..3dd4aba --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/PnfSimConfig.java @@ -0,0 +1,57 @@ +package org.onap.pnfsimulator; + +public class PnfSimConfig { + private String urlves; + private String urlftps; + private String urlsftp; + private String ippnfsim; + private String typefileserver; + + public String getTypefileserver() { + return typefileserver; + } + + public void setTypefileserver(String typefileserver) { + this.typefileserver = typefileserver; + } + + + public String getUrlves() { + return urlves; + } + + public void setUrlves(String urlves) { + this.urlves = urlves; + } + + public String getUrlftps() { + return urlftps; + } + + public void setUrlftps(String urlftps) { + this.urlftps = urlftps; + } + + public String getUrlsftp() { + return urlsftp; + } + + public void setUrlsftp(String urlsftp) { + this.urlsftp = urlsftp; + } + + public void setIppnfsim(String ippnfsim) { + this.ippnfsim = ippnfsim; + } + + public String getIppnfsim() { + return ippnfsim; + } + + @Override + public String toString() { + return "PnfSimConfig [vesip=" + urlves + ", urlftps=" + urlftps + ", urlsftp=" + urlsftp + ", ippnfsim=" + + ippnfsim + ", typefileserver=" + typefileserver + "]"; + } + +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/logback.xml b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/logback.xml new file mode 100644 index 0000000..0f6d9de --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/logback.xml @@ -0,0 +1,50 @@ +<?xml version="1.0" encoding="UTF-8"?> +<Configuration complete="true" compact="true"> + + <Property name="outputFilename" value="pnfsimulator_output"/> + <Property name="log-path" value="/var/log/ONAP/pnfsimulator"/> + <Property name="archive" value="/var/log/ONAP/pnfsimulator/archive"/> + <property name="maxFileSize" value="50MB"/> + <property name="maxHistory" value="30"/> + <property name="totalSizeCap" value="10GB"/> + + <appender name="Console" target="SYSTEM_OUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <Pattern>%nopexception%logger + |%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX,UTC} + |%level + |%replace(%replace(%message){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%mdc){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%rootException){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%marker){'\t','\\\\t'}){'\n','\\\\n'} + |%thread + |%n</Pattern> + </encoder> + </appender> + + <appender name="ROLLING-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> + <encoder> + <pattern>%nopexception%logger + |%date{yyyy-MM-dd'T'HH:mm:ss.SSSXXX,UTC} + |%level + |%replace(%replace(%message){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%mdc){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%rootException){'\t','\\\\t'}){'\n','\\\\n'} + |%replace(%replace(%marker){'\t','\\\\t'}){'\n','\\\\n'} + |%thread + |%n</pattern> + </encoder> + <File>${log-path}/${outputFilename}.log</File> + <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> + <FileNamePattern>${archive}/${outputFilename}.%d{yyyy-MM-dd}.%i.log.zip</FileNamePattern> + <MaxFileSize>${maxFileSize}</MaxFileSize> + <MaxHistory>${maxHistory}</MaxHistory> + <TotalSizeCap>${totalSizeCap}</TotalSizeCap> + </rollingPolicy> + </appender> + + <root level="debug"> + <appender-ref ref="Console" /> + <appender-ref ref="ROLLING-FILE" /> + </root> +</Configuration> diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java new file mode 100644 index 0000000..e479b4a --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/logging/MDCVariables.java @@ -0,0 +1,36 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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.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"; + public static final String AUTHORIZATION = "Authorization"; + + private MDCVariables() { + } +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/message/JSONObjectFactory.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/message/JSONObjectFactory.java new file mode 100644 index 0000000..7c12983 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/message/JSONObjectFactory.java @@ -0,0 +1,142 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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.COMPRESSION; +import static org.onap.pnfsimulator.message.MessageConstants.COMPRESSION_VALUE; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT_ID; +import static org.onap.pnfsimulator.message.MessageConstants.FILE_FORMAT_TYPE; +import static org.onap.pnfsimulator.message.MessageConstants.FILE_FORMAT_TYPE_VALUE; +import static org.onap.pnfsimulator.message.MessageConstants.FILE_FORMAT_VERSION; +import static org.onap.pnfsimulator.message.MessageConstants.FILE_FORMAT_VERSION_VALUE; +import static org.onap.pnfsimulator.message.MessageConstants.HASH_MAP; +import static org.onap.pnfsimulator.message.MessageConstants.INTERNAL_HEADER_FIELDS; +import static org.onap.pnfsimulator.message.MessageConstants.LAST_EPOCH_MICROSEC; +import static org.onap.pnfsimulator.message.MessageConstants.LOCATION; +import static org.onap.pnfsimulator.message.MessageConstants.NAME; +import static org.onap.pnfsimulator.message.MessageConstants.NOTIFICATION_FIELDS_VERSION; +import static org.onap.pnfsimulator.message.MessageConstants.NOTIFICATION_FIELDS_VERSION_VALUE; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_LAST_SERVICE_DATE; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_MANUFACTURE_DATE; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_REGISTRATION_FIELDS_VERSION; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_REGISTRATION_FIELDS_VERSION_VALUE; +import static org.onap.pnfsimulator.message.MessageConstants.PRIORITY; +import static org.onap.pnfsimulator.message.MessageConstants.PRIORITY_NORMAL; +import static org.onap.pnfsimulator.message.MessageConstants.REPORTING_ENTITY_NAME; +import static org.onap.pnfsimulator.message.MessageConstants.SEQUENCE; +import static org.onap.pnfsimulator.message.MessageConstants.SEQUENCE_NUMBER; +import static org.onap.pnfsimulator.message.MessageConstants.SOURCE_NAME; +import static org.onap.pnfsimulator.message.MessageConstants.START_EPOCH_MICROSEC; +import static org.onap.pnfsimulator.message.MessageConstants.TIME_ZONE_OFFSET; +import static org.onap.pnfsimulator.message.MessageConstants.VERSION; +import static org.onap.pnfsimulator.message.MessageConstants.VERSION_NUMBER; +import static org.onap.pnfsimulator.message.MessageConstants.VES_EVENT_LISTENER_VERSION; +import static org.onap.pnfsimulator.message.MessageConstants.VES_EVENT_LISTENER_VERSION_NUMBER; +import java.util.Calendar; +import java.io.File; +import java.util.List; +import java.util.TimeZone; +import org.json.JSONArray; +import org.json.JSONObject; + +final class JSONObjectFactory { + + static JSONObject generateConstantCommonEventHeader() { + JSONObject commonEventHeader = new JSONObject(); + long timestamp = System.currentTimeMillis(); + String nodeName = generateDefaultName(); + commonEventHeader.put(EVENT_ID, generateEventId()); + commonEventHeader.put(TIME_ZONE_OFFSET, generateTimeZone(timestamp)); + commonEventHeader.put(LAST_EPOCH_MICROSEC, timestamp); + commonEventHeader.put(PRIORITY, PRIORITY_NORMAL); + commonEventHeader.put(SEQUENCE, SEQUENCE_NUMBER); + commonEventHeader.put(START_EPOCH_MICROSEC, timestamp); + commonEventHeader.put(INTERNAL_HEADER_FIELDS, new JSONObject()); + commonEventHeader.put(VERSION, VERSION_NUMBER); + commonEventHeader.put(VES_EVENT_LISTENER_VERSION, VES_EVENT_LISTENER_VERSION_NUMBER); + commonEventHeader.put(SOURCE_NAME, nodeName); + commonEventHeader.put(REPORTING_ENTITY_NAME, nodeName); + return commonEventHeader; + } + + static JSONObject generatePnfRegistrationFields() { + JSONObject pnfRegistrationFields = new JSONObject(); + pnfRegistrationFields.put(PNF_REGISTRATION_FIELDS_VERSION, PNF_REGISTRATION_FIELDS_VERSION_VALUE); + pnfRegistrationFields.put(PNF_LAST_SERVICE_DATE, String.valueOf(System.currentTimeMillis())); + pnfRegistrationFields.put(PNF_MANUFACTURE_DATE, String.valueOf(System.currentTimeMillis())); + return pnfRegistrationFields; + } + + static JSONObject generateNotificationFields() { + JSONObject notificationFields = new JSONObject(); + notificationFields.put(NOTIFICATION_FIELDS_VERSION, NOTIFICATION_FIELDS_VERSION_VALUE); + return notificationFields; + } + + static JSONArray generateArrayOfNamedHashMap(List<String> fileList, String xnfUrl) { + JSONArray arrayOfNamedHashMap = new JSONArray(); + + for (String fileName : fileList) { + JSONObject namedHashMap = new JSONObject(); + namedHashMap.put(NAME, fileName); + + JSONObject hashMap = new JSONObject(); + hashMap.put(FILE_FORMAT_TYPE, FILE_FORMAT_TYPE_VALUE); + hashMap.put(LOCATION, xnfUrl.concat(fileName)); + hashMap.put(FILE_FORMAT_VERSION, FILE_FORMAT_VERSION_VALUE); + hashMap.put(COMPRESSION, COMPRESSION_VALUE); + namedHashMap.put(HASH_MAP, hashMap); + + arrayOfNamedHashMap.put(namedHashMap); + } + + + return arrayOfNamedHashMap; + } + + + static String generateEventId() { + String timeAsString = String.valueOf(System.currentTimeMillis()); + return String.format("FileReady_%s", timeAsString); + } + + static String generateDefaultName() { + String defaultName = "default"; + int year = Calendar.getInstance().get(Calendar.YEAR); + int month = Calendar.getInstance().get(Calendar.MONTH); + int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); + + return defaultName + "-" + year + month + day; + } + + static String generateTimeZone(long timestamp) { + TimeZone timeZone = TimeZone.getDefault(); + int offsetInMillis = timeZone.getOffset(timestamp); + String offsetHHMM = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), + Math.abs((offsetInMillis / 60000) % 60)); + return ("UTC" + (offsetInMillis >= 0 ? "+" : "-") + offsetHHMM); + } + + private JSONObjectFactory() { + + } + +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java new file mode 100644 index 0000000..6ff6e5d --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/message/MessageConstants.java @@ -0,0 +1,95 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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 { + + public static final String SIMULATOR_PARAMS = "simulatorParams"; + public static final String COMMON_EVENT_HEADER_PARAMS = "commonEventHeaderParams"; + public static final String PNF_REGISTRATION_PARAMS = "pnfRegistrationParams"; + public static final String NOTIFICATION_PARAMS = "notificationParams"; + + static final String COMMON_EVENT_HEADER = "commonEventHeader"; + static final String PNF_REGISTRATION_FIELDS = "pnfRegistrationFields"; + static final String NOTIFICATION_FIELDS = "notificationFields"; + static final String EVENT = "event"; + + //============================================================================================= + //Simulation parameters + public static final String VES_SERVER_URL = "vesServerUrl"; + public static final String TEST_DURATION = "testDuration"; + public static final String MESSAGE_INTERVAL = "messageInterval"; + + //============================================================================================= + //commonEventHeader + //parameters + static final String DOMAIN = "domain"; + static final String EVENT_ID = "eventId"; + static final String TIME_ZONE_OFFSET = "timeZoneOffset"; + static final String EVENT_TYPE = "eventType"; + static final String LAST_EPOCH_MICROSEC = "lastEpochMicrosec"; + static final String PRIORITY = "priority"; + static final String SEQUENCE = "sequence"; + static final String START_EPOCH_MICROSEC = "startEpochMicrosec"; + static final String INTERNAL_HEADER_FIELDS = "internalHeaderFields"; + static final String VERSION = "version"; + static final String VES_EVENT_LISTENER_VERSION = "vesEventListenerVersion"; + static final String SOURCE_NAME = "sourceName"; + static final String REPORTING_ENTITY_NAME = "reportingEntityName"; + //constant values + static final int SEQUENCE_NUMBER = 0; + static final String VERSION_NUMBER = "4.0.1"; + static final String VES_EVENT_LISTENER_VERSION_NUMBER = "7.0.1"; + static final String PRIORITY_NORMAL = "Normal"; + + //============================================================================================= + //PNF registration + //parameters + static final String PNF_REGISTRATION_FIELDS_VERSION = "pnfRegistrationFieldsVersion"; + static final String PNF_LAST_SERVICE_DATE = "lastServiceDate"; + static final String PNF_MANUFACTURE_DATE = "manufactureDate"; + //constant values + static final String PNF_REGISTRATION_FIELDS_VERSION_VALUE = "2.0"; + static final String DOMAIN_PNF_REGISTRATION ="pnfRegistration"; + + //============================================================================================= + // Notifications + //parameters + static final String NOTIFICATION_FIELDS_VERSION = "notificationFieldsVersion"; + static final String ARRAY_OF_NAMED_HASH_MAP = "arrayOfNamedHashMap"; + static final String NAME = "name"; + static final String HASH_MAP = "hashMap"; + static final String FILE_FORMAT_TYPE = "fileFormatType"; + static final String LOCATION = "location"; + static final String FILE_FORMAT_VERSION = "fileFormatVersion"; + static final String COMPRESSION = "compression"; + + //constant values + static final String NOTIFICATION_FIELDS_VERSION_VALUE = "2.0"; + static final String DOMAIN_NOTIFICATION ="notification"; + static final String FILE_FORMAT_TYPE_VALUE = "org.3GPP.32.435#measCollec"; + static final String FILE_FORMAT_VERSION_VALUE = "V10"; + static final String COMPRESSION_VALUE = "gzip"; + + private MessageConstants() { + } + +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java new file mode 100644 index 0000000..c863625 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/message/MessageProvider.java @@ -0,0 +1,88 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ 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.ARRAY_OF_NAMED_HASH_MAP; +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.DOMAIN_NOTIFICATION; +import static org.onap.pnfsimulator.message.MessageConstants.DOMAIN_PNF_REGISTRATION; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT_TYPE; +import static org.onap.pnfsimulator.message.MessageConstants.NOTIFICATION_FIELDS; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_REGISTRATION_FIELDS; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.json.JSONArray; +import org.json.JSONObject; + +public class MessageProvider { + + public JSONObject createMessage(JSONObject commonEventHeaderParams, Optional<JSONObject> pnfRegistrationParams, + Optional<JSONObject> notificationParams) { + List<String> emptyList = new ArrayList<>(); + String emptyString = ""; + return createMessage(commonEventHeaderParams, pnfRegistrationParams, notificationParams, emptyList, emptyString); + } + + public JSONObject createMessage(JSONObject commonEventHeaderParams, Optional<JSONObject> pnfRegistrationParams, + Optional<JSONObject> notificationParams, List<String> fileList, String xnfUrl) { + + if (!pnfRegistrationParams.isPresent() && !notificationParams.isPresent()) { + throw new IllegalArgumentException( + "Both PNF registration and notification parameters objects are not present"); + } + JSONObject event = new JSONObject(); + + JSONObject commonEventHeader = JSONObjectFactory.generateConstantCommonEventHeader(); + Map<String, Object> commonEventHeaderFields = commonEventHeaderParams.toMap(); + commonEventHeaderFields.forEach((key, value) -> { + commonEventHeader.put(key, value); + }); + + JSONObject pnfRegistrationFields = JSONObjectFactory.generatePnfRegistrationFields(); + pnfRegistrationParams.ifPresent(jsonObject -> { + copyParametersToFields(jsonObject.toMap(), pnfRegistrationFields); + commonEventHeader.put(DOMAIN, DOMAIN_PNF_REGISTRATION); + commonEventHeader.put(EVENT_TYPE, DOMAIN_PNF_REGISTRATION); + event.put(PNF_REGISTRATION_FIELDS, pnfRegistrationFields); + }); + + JSONObject notificationFields = JSONObjectFactory.generateNotificationFields(); + notificationParams.ifPresent(jsonObject -> { + copyParametersToFields(jsonObject.toMap(), notificationFields); + JSONArray arrayOfNamedHashMap = JSONObjectFactory.generateArrayOfNamedHashMap(fileList, xnfUrl); + notificationFields.put(ARRAY_OF_NAMED_HASH_MAP, arrayOfNamedHashMap); + commonEventHeader.put(DOMAIN, DOMAIN_NOTIFICATION); + event.put(NOTIFICATION_FIELDS, notificationFields); + }); + + event.put(COMMON_EVENT_HEADER, commonEventHeader); + JSONObject root = new JSONObject(); + root.put(EVENT, event); + return root; + } + + private void copyParametersToFields(Map<String, Object> paramersMap, JSONObject fieldsJsonObject) { + paramersMap.forEach((key, value) -> { + fieldsJsonObject.put(key, value); + }); + } +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java new file mode 100644 index 0000000..bb173ae --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTask.java @@ -0,0 +1,62 @@ +/// * +// * ============LICENSE_START======================================================= +// * PNF-REGISTRATION-HANDLER +// * ================================================================================ +// * 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.TimerTask; +// 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; +// +// public class NetconfConfigurationCheckingTask extends TimerTask { +// +// private static final Logger LOGGER = +/// LoggerFactory.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() { +// try { +// 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/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java new file mode 100644 index 0000000..4e484b9 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorService.java @@ -0,0 +1,71 @@ +/// * +// * ============LICENSE_START======================================================= +// * PNF-REGISTRATION-HANDLER +// * ================================================================================ 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 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; +// +//// @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; +// +// 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() { +// setStartConfiguration(); +// NetconfConfigurationCheckingTask task = new NetconfConfigurationCheckingTask(reader, writer, +/// cache); +// timer.scheduleAtFixedRate(task, startDelay, timePeriod); +// } +// +// 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/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java new file mode 100644 index 0000000..d97315b --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfiguration.java @@ -0,0 +1,114 @@ +/// * +// * ============LICENSE_START======================================================= +// * PNF-REGISTRATION-HANDLER +// * ================================================================================ +// * 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 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 = +/// LoggerFactory.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 = "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"; +// +// 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 = resolveConnectionParams(); +// LOGGER.info("Configuration params are : {}", 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); +// } +// +// private String buildModelPath() { +// return String.format("/%s:%s", +// enviroment.getOrDefault(NETCONF_MODEL, DEFAULT_NETCONF_MODEL), +// enviroment.getOrDefault(NETCONF_MAIN_CONTAINER, DEFAULT_NETCONF_MAIN_CONTAINER)); +// } +// +// NetconfConnectionParams resolveConnectionParams() { +// 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) { +// LOGGER.warn("Invalid netconf port: {}. Default netconf port {} is set.", e.getMessage(), +// DEFAULT_NETCONF_PORT); +// return DEFAULT_NETCONF_PORT; +// } +// } +// } diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java new file mode 100644 index 0000000..3972184 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCache.java @@ -0,0 +1,34 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java new file mode 100644 index 0000000..e41e58f --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReader.java @@ -0,0 +1,42 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ 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; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class NetconfConfigurationReader { + + private static final Logger LOGGER = LoggerFactory.getLogger(NetconfConfigurationReader.class); + private final NetconfSession session; + private final String netconfModelPath; + + public NetconfConfigurationReader(NetconfSession session, String netconfModelPath) { + LOGGER.warn("netconfModelPath: {}", netconfModelPath); + this.session = session; + this.netconfModelPath = netconfModelPath; + } + + public String read() throws IOException, JNCException { + return session.getConfig(netconfModelPath).first().toXMLString(); + } +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java new file mode 100644 index 0000000..4003079 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriter.java @@ -0,0 +1,51 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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.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 = LoggerFactory.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.warn("Failed to write configuration to file: {}", e.getMessage()); + } + } +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java new file mode 100644 index 0000000..1d6eb89 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConnectionParams.java @@ -0,0 +1,45 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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; + 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("NetconfConnectionParams{address=%s, port=%d, user=%s, password=%s}", + address, + port, + user, + password); + } +}
\ No newline at end of file diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java new file mode 100644 index 0000000..7bb646c --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/rest/SimulatorController.java @@ -0,0 +1,235 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ 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.AUTHORIZATION; +import static org.onap.pnfsimulator.logging.MDCVariables.X_ONAP_REQUEST_ID; +import static org.onap.pnfsimulator.message.MessageConstants.COMMON_EVENT_HEADER_PARAMS; +import static org.onap.pnfsimulator.message.MessageConstants.SIMULATOR_PARAMS; +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 com.github.fge.jsonschema.core.exceptions.ProcessingException; +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Optional; +import java.util.UUID; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.pnfsimulator.message.MessageConstants; +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.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; + +@RestController +@RequestMapping("/simulator") +public class SimulatorController { + + 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; + + @Autowired + public SimulatorController(JSONValidator validator, SimulatorFactory factory) { + this.validator = validator; + this.factory = factory; + } + + @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(AUTHORIZATION, headers.getFirst(AUTHORIZATION)); + 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(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); + JSONObject commonEventHeaderParams = root.getJSONObject(COMMON_EVENT_HEADER_PARAMS); + Optional<JSONObject> pnfRegistrationFields = root.has(MessageConstants.PNF_REGISTRATION_PARAMS) + ? Optional.of(root.getJSONObject(MessageConstants.PNF_REGISTRATION_PARAMS)) + : Optional.empty(); + Optional<JSONObject> notificationFields = root.has(MessageConstants.NOTIFICATION_PARAMS) + ? Optional.of(root.getJSONObject(MessageConstants.NOTIFICATION_PARAMS)) + : Optional.empty(); + simulator = + factory.create(simulatorParams, commonEventHeaderParams, pnfRegistrationFields, notificationFields); + simulator.start(); + + MDC.put(RESPONSE_CODE, OK.toString()); + return ResponseBuilder.status(OK).put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Simulator started").build(); + + } 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(BAD_REQUEST).put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot start simulator, invalid json format").build(); + + } catch (ProcessingException | ValidationException | IOException e) { + MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); + LOGGER.warn("Json validation failed: {}", e.getMessage()); + return ResponseBuilder.status(BAD_REQUEST).put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot start simulator - Json format is not compatible with schema definitions") + .build(); + + } catch (Exception e) { + MDC.put(RESPONSE_CODE, INTERNAL_SERVER_ERROR.toString()); + LOGGER.error("Cannot start simulator - unexpected exception", e); + return ResponseBuilder.status(INTERNAL_SERVER_ERROR) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Unexpected exception: " + e.getMessage()).build(); + } finally { + MDC.clear(); + } + } + + @PostMapping("startmassmode") + public ResponseEntity startmassmode(@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(AUTHORIZATION, headers.getFirst(AUTHORIZATION)); + 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(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); + JSONObject commonEventHeaderParams = root.getJSONObject(COMMON_EVENT_HEADER_PARAMS); + Optional<JSONObject> pnfRegistrationFields = root.has(MessageConstants.PNF_REGISTRATION_PARAMS) + ? Optional.of(root.getJSONObject(MessageConstants.PNF_REGISTRATION_PARAMS)) + : Optional.empty(); + Optional<JSONObject> notificationFields = root.has(MessageConstants.NOTIFICATION_PARAMS) + ? Optional.of(root.getJSONObject(MessageConstants.NOTIFICATION_PARAMS)) + : Optional.empty(); + simulator = + factory.create(simulatorParams, commonEventHeaderParams, pnfRegistrationFields, notificationFields); + simulator.start(); + + MDC.put(RESPONSE_CODE, OK.toString()); + return ResponseBuilder.status(OK).put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Simulator started").build(); + + } 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(BAD_REQUEST).put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot start simulator, invalid json format").build(); + + } catch (ProcessingException | ValidationException | IOException e) { + MDC.put(RESPONSE_CODE, BAD_REQUEST.toString()); + LOGGER.warn("Json validation failed: {}", e.getMessage()); + return ResponseBuilder.status(BAD_REQUEST).put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Cannot start simulator - Json format is not compatible with schema definitions") + .build(); + + } catch (Exception e) { + MDC.put(RESPONSE_CODE, INTERNAL_SERVER_ERROR.toString()); + LOGGER.error("Cannot start simulator - unexpected exception", e); + return ResponseBuilder.status(INTERNAL_SERVER_ERROR) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Unexpected exception: " + e.getMessage()).build(); + } finally { + MDC.clear(); + } + } + + + + @GetMapping("status") + public ResponseEntity status() { + if (isSimulatorRunning()) { + ResponseBuilder responseBuilder = ResponseBuilder.status(OK) + .put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)).put(SIMULATOR_STATUS, "RUNNING"); + + return !simulator.isEndless() ? responseBuilder.put(REMAINING_TIME, simulator.getRemainingTime()).build() + : responseBuilder.build(); + } else { + return ResponseBuilder.status(OK).put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(SIMULATOR_STATUS, "NOT RUNNING").build(); + } + } + + @PostMapping("stop") + public ResponseEntity stop() { + if (isSimulatorRunning()) { + simulator.interrupt(); + + return ResponseBuilder.status(OK).put(TIMESTAMP, DateUtil.getTimestamp(RESPONSE_DATE_FORMAT)) + .put(MESSAGE, "Simulator successfully stopped").build(); + } else { + return ResponseBuilder.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/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java new file mode 100644 index 0000000..284d589 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/rest/util/DateUtil.java @@ -0,0 +1,35 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java new file mode 100644 index 0000000..98f4588 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/rest/util/ResponseBuilder.java @@ -0,0 +1,62 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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 { + + 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 HttpStatus httpStatus; + private Map<String, Object> body = new LinkedHashMap<>(); + + private ResponseBuilder(HttpStatus httpStatus) { + this.httpStatus = httpStatus; + } + + public static ResponseBuilder status(HttpStatus httpStatus) { + + return new ResponseBuilder(httpStatus); + } + + public ResponseBuilder put(String key, Object value) { + + body.put(key, value); + return this; + } + + public ResponseEntity build() { + + if (body.isEmpty()) { + return ResponseEntity.status(httpStatus).build(); + } + + return ResponseEntity.status(httpStatus).body(body); + } + +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java new file mode 100644 index 0000000..725fe43 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/Simulator.java @@ -0,0 +1,213 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ 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 com.github.fge.jsonschema.core.exceptions.ProcessingException; +import java.io.IOException; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.json.JSONObject; +import org.onap.pnfsimulator.FileProvider; +import org.onap.pnfsimulator.message.MessageProvider; +import org.onap.pnfsimulator.simulator.client.RestTemplateAdapter; +import org.onap.pnfsimulator.simulator.client.RestTemplateAdapterImpl; +import org.onap.pnfsimulator.simulator.validation.JSONValidator; +import org.onap.pnfsimulator.simulator.validation.NoRopFilesException; +import org.onap.pnfsimulator.simulator.validation.ValidationException; +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 = 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 RestTemplateAdapter httpClient; + private JSONObject messageBody; + private Duration duration; + private Duration interval; + private Instant endTime; + private JSONObject commonEventHeaderParams; + private Optional<JSONObject> pnfRegistrationParams; + private Optional<JSONObject> notificationParams; + private String xnfUrl; + private static final String DEFAULT_OUTPUT_SCHEMA_PATH = "json_schema/output_validator_ves_schema_30.0.1.json"; + private FileProvider fileProvider; + private Exception thrownException = null; + + private Simulator() {} + + public static Builder builder() { + return new Builder(); + } + + @Override + public void run() { + setMdcContextMap(contextMap); + LOGGER.info("Simulation started - duration: {}, interval: {}s", getDuration(), interval.getSeconds()); + endTime = Instant.now().plus(duration); + while (isEndless || runningTimeNotExceeded()) { + try { + + List<String> fileList = fileProvider.getFiles(); + MessageProvider messageProvider = new MessageProvider(); + JSONValidator validator = new JSONValidator(); + messageBody = messageProvider.createMessage(this.commonEventHeaderParams, this.pnfRegistrationParams, + this.notificationParams, fileList, this.xnfUrl); + validator.validate(messageBody.toString(), DEFAULT_OUTPUT_SCHEMA_PATH); + + LOGGER.info("Message to be sent:\n" + getMessage()); + httpClient.send(messageBody.toString(), vesUrl); + Thread.sleep(interval.toMillis()); + } catch (InterruptedException | ValidationException | ProcessingException | IOException | NoRopFilesException e) { + LOGGER.info("Simulation stopped due to an exception: " + e); + thrownException = e; + return; + } + } + LOGGER.info(EXIT, "Simulation finished"); + MDC.clear(); + } + + private void setMdcContextMap(Map<String, String> mdcContextMap) { + if (mdcContextMap != null) + MDC.setContextMap(mdcContextMap); + } + + private String getMessage() { + return messageBody.toString(4); + } + + private String getDuration() { + return isEndless() ? "infinity" : duration.getSeconds() + "s"; + } + + private boolean runningTimeNotExceeded() { + return Instant.now().isBefore(endTime); + } + + public boolean isEndless() { + return isEndless; + } + + public Exception getThrownException() { + return thrownException; + } + + public long getRemainingTime() { + return Duration.between(Instant.now(), endTime).getSeconds(); + } + + public static class Builder { + + private String vesUrl; + private RestTemplateAdapter httpClient; + //private JSONObject messageBody; + private Duration duration; + private Duration interval; + private Optional<JSONObject> notificationParams; + private Optional<JSONObject> pnfRegistrationParams; + private JSONObject commonEventHeaderParams; + private String xnfUrl; + private FileProvider fileProvider; + + private Builder() { + this.vesUrl = ""; + this.httpClient = new RestTemplateAdapterImpl(); + //this.messageBody = new JSONObject(); + this.duration = Duration.ZERO; + this.interval = Duration.ZERO; + this.commonEventHeaderParams = new JSONObject(); + } + + public Builder withVesUrl(String vesUrl) { + this.vesUrl = vesUrl; + return this; + } + + public Builder withCustomRestTemplateAdapter(RestTemplateAdapter 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 Builder withCommonEventHeaderParams(JSONObject commonEventHeaderParams) { + this.commonEventHeaderParams = commonEventHeaderParams; + return this; + } + + public Builder withNotificationParams(Optional<JSONObject> notificationParams) { + this.notificationParams = notificationParams; + return this; + } + + public Builder withPnfRegistrationParams(Optional<JSONObject> pnfRegistrationParams) { + this.pnfRegistrationParams = pnfRegistrationParams; + return this; + } + + public Builder withXnfUrl(String xnfUrl) { + this.xnfUrl = xnfUrl; + return this; + } + + public Builder withFileProvider(FileProvider fileProvider) { + this.fileProvider = fileProvider; + 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.xnfUrl = this.xnfUrl; + simulator.fileProvider = this.fileProvider; + simulator.commonEventHeaderParams = this.commonEventHeaderParams; + simulator.pnfRegistrationParams = this.pnfRegistrationParams; + simulator.notificationParams = this.notificationParams; + simulator.isEndless = duration.equals(Duration.ZERO); + return simulator; + } + } +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java new file mode 100644 index 0000000..851e6ad --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/SimulatorFactory.java @@ -0,0 +1,54 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ 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.parseInt; +import static org.onap.pnfsimulator.message.MessageConstants.MESSAGE_INTERVAL; +import static org.onap.pnfsimulator.message.MessageConstants.TEST_DURATION; +import java.time.Duration; +import java.util.Optional; +import org.json.JSONObject; +import org.onap.pnfsimulator.ConfigurationProvider; +import org.onap.pnfsimulator.FileProvider; +import org.onap.pnfsimulator.PnfSimConfig; +import org.springframework.stereotype.Service; + +@Service +public class SimulatorFactory { + + public Simulator create(JSONObject simulatorParams, JSONObject commonEventHeaderParams, + Optional<JSONObject> pnfRegistrationParams, Optional<JSONObject> notificationParams) { + PnfSimConfig configuration = ConfigurationProvider.getConfigInstance(); + + String xnfUrl = null; + if (configuration.getTypefileserver().equals("sftp")) { + xnfUrl = configuration.getUrlsftp() + "/"; + } else if (configuration.getTypefileserver().equals("ftps")) { + xnfUrl = configuration.getUrlftps() + "/"; + } + + String urlVes = configuration.getUrlves(); + Duration duration = Duration.ofSeconds(parseInt(simulatorParams.getString(TEST_DURATION))); + Duration interval = Duration.ofSeconds(parseInt(simulatorParams.getString(MESSAGE_INTERVAL))); + + return Simulator.builder().withVesUrl(urlVes).withXnfUrl(xnfUrl).withDuration(duration) + .withFileProvider(new FileProvider()).withCommonEventHeaderParams(commonEventHeaderParams) + .withNotificationParams(notificationParams).withPnfRegistrationParams(pnfRegistrationParams) + .withInterval(interval).build(); + } +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/client/RestTemplateAdapter.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/client/RestTemplateAdapter.java new file mode 100644 index 0000000..92e66b4 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/client/RestTemplateAdapter.java @@ -0,0 +1,26 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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; + +public interface RestTemplateAdapter { + + void send(String content, String url); +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/client/RestTemplateAdapterImpl.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/client/RestTemplateAdapterImpl.java new file mode 100644 index 0000000..e082637 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/client/RestTemplateAdapterImpl.java @@ -0,0 +1,155 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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 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 static org.onap.pnfsimulator.logging.MDCVariables.AUTHORIZATION; + +import org.springframework.web.client.ResourceAccessException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +import org.springframework.http.HttpEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.http.HttpHeaders; + +import java.util.UUID; +import org.springframework.web.client.HttpClientErrorException; +import org.apache.http.client.config.RequestConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +public class RestTemplateAdapterImpl implements RestTemplateAdapter { + + private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateAdapterImpl.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 RestTemplate restTemplate; + + public RestTemplateAdapterImpl() { + try { + this.restTemplate = createRestTemplate(); + } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException ex) { + LOGGER.warn("Error while creating a RestTemplate object: {}", ex.getMessage()); + } + } + + RestTemplateAdapterImpl(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + } + + @Override + public void send(String content, String url) { + try { + HttpEntity<String> entity = createPostEntity(content); + ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class); + LOGGER.info(INVOKE, "Message sent, ves response code: {}", response.getStatusCode()); + } catch (HttpClientErrorException codeEx) { + LOGGER.warn("Response body: ", codeEx.getResponseBodyAsString()); + LOGGER.warn("Error sending message to ves: {}", codeEx.getMessage()); + LOGGER.warn("URL: {}", url); + } catch (ResourceAccessException ioEx) { + LOGGER.warn("The URL cannot be reached: {}", ioEx.getMessage()); + LOGGER.warn("URL: {}", url); + } + } + + private CloseableHttpClient createClient() + throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { + + TrustManager[] trustAllCerts = new TrustManager[] { + new X509TrustManager() { + + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, + String authType) {} + + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, + String authType) {} + } + }; + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init( + null, + trustAllCerts, + new java.security.SecureRandom() + ); + + CloseableHttpClient httpClient = HttpClients + .custom() + .setSSLContext(sslContext) + .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) + .build(); + + return httpClient; + } + + private RestTemplate createRestTemplate() + throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { + + CloseableHttpClient client = createClient(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); + requestFactory.setHttpClient(client); + + return new RestTemplate(requestFactory); + + } + + private HttpEntity createPostEntity(String content) { + + HttpHeaders headers = new HttpHeaders(); + headers.set(CONTENT_TYPE, APPLICATION_JSON); + headers.set(AUTHORIZATION, MDC.get(AUTHORIZATION)); + headers.set(X_ONAP_REQUEST_ID, MDC.get(REQUEST_ID)); + headers.set(X_INVOCATION_ID, UUID.randomUUID().toString()); + + return new HttpEntity<>(content, headers); + + } +}
\ No newline at end of file diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/validation/JSONValidator.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/validation/JSONValidator.java new file mode 100644 index 0000000..89135f9 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/validation/JSONValidator.java @@ -0,0 +1,66 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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 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/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/validation/NoRopFilesException.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/validation/NoRopFilesException.java new file mode 100644 index 0000000..d3765a8 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/validation/NoRopFilesException.java @@ -0,0 +1,28 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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 NoRopFilesException extends Exception { + + public NoRopFilesException(String message) { + super(message); + } +} diff --git a/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java new file mode 100644 index 0000000..a934917 --- /dev/null +++ b/pnf-sim-lightweight/src/main/java/org/onap/pnfsimulator/simulator/validation/ValidationException.java @@ -0,0 +1,28 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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 { + + public ValidationException(String message) { + super(message); + } +} |