1 package org.onap.pnfsimulator.simulator.validation;
3 import static org.onap.pnfsimulator.message.MessageConstants.MESSAGE_INTERVAL;
4 import static org.onap.pnfsimulator.message.MessageConstants.PNF_OAM_IPV4_ADDRESS;
5 import static org.onap.pnfsimulator.message.MessageConstants.PNF_OAM_IPV6_ADDRESS;
6 import static org.onap.pnfsimulator.message.MessageConstants.PNF_SERIAL_NUMBER;
7 import static org.onap.pnfsimulator.message.MessageConstants.PNF_VENDOR_NAME;
8 import static org.onap.pnfsimulator.message.MessageConstants.TEST_DURATION;
10 import com.google.common.collect.ImmutableMap;
11 import java.util.ArrayList;
12 import java.util.List;
13 import java.util.function.BiPredicate;
14 import org.apache.commons.lang3.StringUtils;
15 import org.json.JSONObject;
18 public class ParamsValidator {
20 private final static String MISSING_PARAMS_ERROR = "Some mandatory params are missing";
21 private static ParamsValidator instance;
24 public static ParamsValidator getInstance() {
25 if (instance == null) {
26 instance = new ParamsValidator();
31 public void validate(JSONObject params) throws ValidationException {
32 ImmutableMap<String, BiPredicate<JSONObject, String>> paramValidators = ImmutableMap
33 .<String, BiPredicate<JSONObject, String>>builder()
34 .put(TEST_DURATION, this::isNotNumeric)
35 .put(MESSAGE_INTERVAL, this::isNotNumeric)
36 .put(PNF_SERIAL_NUMBER, this::nullOrEmpty)
37 .put(PNF_VENDOR_NAME, this::nullOrEmpty)
38 .put(PNF_OAM_IPV4_ADDRESS, this::nullOrEmpty)
39 .put(PNF_OAM_IPV6_ADDRESS, this::nullOrEmpty)
42 List<String> missingParams = new ArrayList<>();
44 paramValidators.forEach((param, validator) -> {
45 if (validator.test(params, param)) {
46 missingParams.add(param);
50 clearIPError(missingParams);
51 if (!missingParams.isEmpty()) {
52 throw new ValidationException(constructMessage(missingParams));
56 private String constructMessage(List<String> missingParams) {
57 StringBuilder msg = new StringBuilder(MISSING_PARAMS_ERROR);
59 missingParams.forEach(param -> {
64 return msg.toString();
67 private boolean isNotNumeric(JSONObject params, String param) {
68 return nullOrEmpty(params, param) || !StringUtils.isNumeric(params.getString(param));
71 private boolean nullOrEmpty(JSONObject params, String param) {
72 return !params.has(param) || params.getString(param).isEmpty();
75 private void clearIPError(List<String> missingParams) {
76 // if only one IP is missing clear the error
77 if (!(missingParams.contains(PNF_OAM_IPV4_ADDRESS) && missingParams.contains(PNF_OAM_IPV6_ADDRESS))) {
78 missingParams.remove(PNF_OAM_IPV4_ADDRESS);
79 missingParams.remove(PNF_OAM_IPV6_ADDRESS);