diff options
author | liamfallon <liam.fallon@ericsson.com> | 2018-08-30 09:37:29 +0100 |
---|---|---|
committer | liamfallon <liam.fallon@ericsson.com> | 2018-08-31 19:23:41 +0100 |
commit | f32508381ce0b555fc14978cbaa458aa4e2d91c5 (patch) | |
tree | 1cab66e5372b6467f288ae1351ce836e4eba2d03 /services/services-engine/src/main | |
parent | 052038c7a7e0b385462b3b653b7d06094d472df3 (diff) |
Use parameter service in apex
Switch parameter handling in apex to use
the ONAP PF common parameter service
Change-Id: Id318d19c726b18b1a69c630fa81ca7d695355e9c
Issue-ID: POLICY-954
Signed-off-by: liamfallon <liam.fallon@ericsson.com>
Diffstat (limited to 'services/services-engine/src/main')
19 files changed, 550 insertions, 541 deletions
diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/ApexEventProtocolParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/ApexEventProtocolParameters.java index 10cd58eb7..27970f982 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/ApexEventProtocolParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/ApexEventProtocolParameters.java @@ -32,16 +32,15 @@ public class ApexEventProtocolParameters extends EventProtocolParameters { public static final String APEX_EVENT_PROTOCOL_LABEL = "APEX"; /** - * Constructor to create a JSON event protocol parameter instance and register the instance with - * the parameter service. + * Constructor to create a JSON event protocol parameter instance and register the instance with the parameter + * service. */ public ApexEventProtocolParameters() { this(ApexEventProtocolParameters.class.getCanonicalName(), APEX_EVENT_PROTOCOL_LABEL); } /** - * Constructor to create an event protocol parameters instance with the name of a sub class of - * this class. + * Constructor to create an event protocol parameters instance with the name of a sub class of this class. * * @param parameterClassName the class name of a sub class of this class * @param eventProtocolLabel the name of the event protocol for this plugin diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorCarrierTechnologyParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorCarrierTechnologyParameters.java index fb722ea2f..839b4bffe 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorCarrierTechnologyParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorCarrierTechnologyParameters.java @@ -21,6 +21,7 @@ package org.onap.policy.apex.service.engine.event.impl.eventrequestor; import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; +import org.onap.policy.common.parameters.GroupValidationResult; /** * This class holds the parameters that allows an output event to to be sent back into APEX as one @@ -47,7 +48,7 @@ public class EventRequestorCarrierTechnologyParameters extends CarrierTechnology * the instance with the parameter service. */ public EventRequestorCarrierTechnologyParameters() { - super(EventRequestorCarrierTechnologyParameters.class.getCanonicalName()); + super(); // Set the carrier technology properties for the EVENT_REQUESTOR carrier technology this.setLabel(EVENT_REQUESTOR_CARRIER_TECHNOLOGY_LABEL); @@ -61,7 +62,15 @@ public class EventRequestorCarrierTechnologyParameters extends CarrierTechnology * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() */ @Override - public String validate() { - return ""; + public GroupValidationResult validate() { + return new GroupValidationResult(this); + } + + /* (non-Javadoc) + * @see org.onap.policy.common.parameters.ParameterGroup#getName() + */ + @Override + public String getName() { + return this.getLabel(); } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FILECarrierTechnologyParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FILECarrierTechnologyParameters.java index 76f9b4bb3..84d19fc62 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FILECarrierTechnologyParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FILECarrierTechnologyParameters.java @@ -23,23 +23,25 @@ package org.onap.policy.apex.service.engine.event.impl.filecarrierplugin; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.ApexFileEventConsumer; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.producer.ApexFileEventProducer; import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; import org.onap.policy.common.utils.resources.ResourceUtils; /** - * This class holds the parameters that allows transport of events into and out of Apex using files - * and standard input and output. + * This class holds the parameters that allows transport of events into and out of Apex using files and standard input + * and output. * - * <p>The following parameters are defined: + * <p> + * The following parameters are defined: * <ol> * <li>fileName: The full path to the file from which to read events or to which to write events. - * <li>standardIO: If this flag is set to true, then standard input is used to read events in or - * standard output is used to write events and the fileName parameter is ignored if present + * <li>standardIO: If this flag is set to true, then standard input is used to read events in or standard output is used + * to write events and the fileName parameter is ignored if present * <li>standardError: If this flag is set to true, then standard error is used to write events - * <li>streamingMode: If this flag is set to true, then streaming mode is set for reading events and - * event handling will wait on the input stream for events until the stream is closed. If streaming - * model is off, then event reading completes when the end of input is detected. - * <li>startDelay: The amount of milliseconds to wait at startup startup before processing the first - * event. + * <li>streamingMode: If this flag is set to true, then streaming mode is set for reading events and event handling will + * wait on the input stream for events until the stream is closed. If streaming model is off, then event reading + * completes when the end of input is detected. + * <li>startDelay: The amount of milliseconds to wait at startup startup before processing the first event. * </ol> * * @author Liam Fallon (liam.fallon@ericsson.com) @@ -63,11 +65,11 @@ public class FILECarrierTechnologyParameters extends CarrierTechnologyParameters // @formatter:on /** - * Constructor to create a file carrier technology parameters instance and register the instance - * with the parameter service. + * Constructor to create a file carrier technology parameters instance and register the instance with the parameter + * service. */ public FILECarrierTechnologyParameters() { - super(FILECarrierTechnologyParameters.class.getCanonicalName()); + super(); // Set the carrier technology properties for the FILE carrier technology this.setLabel(FILE_CARRIER_TECHNOLOGY_LABEL); @@ -168,14 +170,23 @@ public class FILECarrierTechnologyParameters extends CarrierTechnologyParameters /* * (non-Javadoc) * - * @see org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters# - * toString() + * @see org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters# toString() */ @Override public String toString() { return "FILECarrierTechnologyParameters [fileName=" + fileName + ", standardIO=" + standardIO - + ", standardError=" + standardError + ", streamingMode=" + streamingMode + ", startDelay=" + startDelay - + "]"; + + ", standardError=" + standardError + ", streamingMode=" + streamingMode + ", startDelay=" + + startDelay + "]"; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.common.parameters.ParameterGroup#getName() + */ + @Override + public String getName() { + return this.getLabel(); } /* @@ -184,14 +195,12 @@ public class FILECarrierTechnologyParameters extends CarrierTechnologyParameters * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() */ @Override - public String validate() { - final StringBuilder errorMessageBuilder = new StringBuilder(); - - errorMessageBuilder.append(super.validate()); + public GroupValidationResult validate() { + final GroupValidationResult result = super.validate(); if (!standardIO && !standardError && (fileName == null || fileName.trim().length() == 0)) { - errorMessageBuilder.append( - " fileName not specified or is blank or null, it must be specified as a valid file location\n"); + result.setResult("fileName", ValidationStatus.INVALID, + "fileName not specified or is blank or null, it must be specified as a valid file location"); } if (standardIO || standardError) { @@ -199,9 +208,10 @@ public class FILECarrierTechnologyParameters extends CarrierTechnologyParameters } if (startDelay < 0) { - errorMessageBuilder.append(" startDelay must be zero or a positive number of milliseconds\n"); + result.setResult("startDelay", ValidationStatus.INVALID, + "startDelay must be zero or a positive number of milliseconds"); } - return errorMessageBuilder.toString(); + return result; } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JSONEventProtocolParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JSONEventProtocolParameters.java index 56eaa4a1e..6efcceb43 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JSONEventProtocolParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JSONEventProtocolParameters.java @@ -87,6 +87,14 @@ public class JSONEventProtocolParameters extends EventProtocolTextCharDelimitedP this.setEventProtocolPluginClass(Apex2JSONEventConverter.class.getCanonicalName()); } + /* (non-Javadoc) + * @see org.onap.policy.common.parameters.ParameterGroup#getName() + */ + @Override + public String getName() { + return this.getLabel(); + } + /** * Gets the name alias. * diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java index 2124b3118..ee5f9ae72 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java @@ -45,6 +45,7 @@ import org.onap.policy.apex.service.engine.runtime.ApexEventListener; import org.onap.policy.apex.service.engine.runtime.EngineService; import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface; import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; +import org.onap.policy.common.parameters.GroupValidationResult; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -156,9 +157,9 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven LOGGER.warn("Engine service configuration parameters is null"); throw new ApexException("engine service configuration parameters is null"); } - final String validation = config.validate(); - if (validation != null && validation.length() > 0) { - LOGGER.warn("Invalid engine service configuration parameters: " + validation); + final GroupValidationResult validation = config.validate(); + if (!validation.isValid()) { + LOGGER.warn("Invalid engine service configuration parameters: {}" + validation.getResult()); throw new ApexException("Invalid engine service configuration parameters: " + validation); } final AxArtifactKey engineServiceKey = config.getEngineKey(); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterValidator.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterConstants.java index a8cbe3b46..1937fd2bf 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterValidator.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterConstants.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * Copyright (C) 2018 Ericsson. 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. @@ -21,16 +21,18 @@ package org.onap.policy.apex.service.parameters; /** - * This interface is implemented by Apex parameter classes so that they can be validated. - * - * @author Liam Fallon (liam.fallon@ericsson.com) + * This class holds constants used when managing parameter groups in apex. */ -public interface ApexParameterValidator { +public abstract class ApexParameterConstants { + public static final String MAIN_GROUP_NAME = "APEX_PARAMETERS"; + public static final String ENGINE_SERVICE_GROUP_NAME = "ENGINE_SERVICE_PARAMETERS"; + public static final String EVENT_HANDLER_GROUP_NAME = "EVENT_HANDLER_PARAMETERS"; + /** - * Validate a parameter java bean, if the parameter bean is valid, an empty string is returned, - * otherwise the string gives details of the invalid parameters. - * - * @return the string with validation errors + * Private default constructor to prevent subclassing */ - String validate(); + private ApexParameterConstants() { + // Prevents subclassing + } + } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterException.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterException.java deleted file mode 100644 index 2bc064593..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterException.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.parameters; - -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; - -/** - * This exception will be called if an error occurs in Apex parameter handling. - * - * @author Liam Fallon - */ -public class ApexParameterException extends ApexException { - private static final long serialVersionUID = -8507246953751956974L; - - /** - * Instantiates a new apex parameter handling exception with a message. - * - * @param message the message - */ - public ApexParameterException(final String message) { - super(message); - } - - /** - * Instantiates a new apex parameter handling exception with a message and a caused by - * exception. - * - * @param message the message - * @param ex the exception that caused this exception to be thrown - */ - public ApexParameterException(final String message, final Exception ex) { - super(message, ex); - } -} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java index 31209bf08..c93e52118 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterHandler.java @@ -29,6 +29,9 @@ import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnolo import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParametersJSONAdapter; import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParametersJSONAdapter; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ParameterException; +import org.onap.policy.common.parameters.ParameterService; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -48,9 +51,12 @@ public class ApexParameterHandler { * * @param arguments the arguments passed to Apex * @return the parameters read from the configuration file - * @throws ApexParameterException on parameter exceptions + * @throws ParameterException on parameter exceptions */ - public ApexParameters getParameters(final ApexCommandLineArguments arguments) throws ApexParameterException { + public ApexParameters getParameters(final ApexCommandLineArguments arguments) throws ParameterException { + // Clear all existing parameters + ParameterService.clear(); + ApexParameters parameters = null; // Read the parameters @@ -58,27 +64,27 @@ public class ApexParameterHandler { // Register the adapters for our carrier technologies and event protocols with GSON // @formatter:off final Gson gson = new GsonBuilder() - .registerTypeAdapter(EngineParameters .class, - new EngineServiceParametersJSONAdapter()) - .registerTypeAdapter(CarrierTechnologyParameters.class, - new CarrierTechnologyParametersJSONAdapter()) - .registerTypeAdapter(EventProtocolParameters .class, - new EventProtocolParametersJSONAdapter()) - .create(); + .registerTypeAdapter(EngineParameters .class, + new EngineServiceParametersJSONAdapter()) + .registerTypeAdapter(CarrierTechnologyParameters.class, + new CarrierTechnologyParametersJSONAdapter()) + .registerTypeAdapter(EventProtocolParameters .class, + new EventProtocolParametersJSONAdapter()) + .create(); // @formatter:on parameters = gson.fromJson(new FileReader(arguments.getFullConfigurationFilePath()), ApexParameters.class); } catch (final Exception e) { final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath() - + "\"\n" + "(" + e.getClass().getSimpleName() + "):" + e.getMessage(); + + "\"\n" + "(" + e.getClass().getSimpleName() + "):" + e.getMessage(); LOGGER.error(errorMessage, e); - throw new ApexParameterException(errorMessage, e); + throw new ParameterException(errorMessage, e); } // The JSON processing returns null if there is an empty file if (parameters == null) { final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; LOGGER.error(errorMessage); - throw new ApexParameterException(errorMessage); + throw new ParameterException(errorMessage); } // Check if we should override the model file parameter @@ -87,17 +93,43 @@ public class ApexParameterHandler { parameters.getEngineServiceParameters().setPolicyModelFileName(modelFilePath); } - // validate the parameters - final String validationResult = parameters.validate(); - if (!validationResult.isEmpty()) { - String returnMessage = - "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; - returnMessage += validationResult; + // Validate the parameters + final GroupValidationResult validationResult = parameters.validate(); + if (!validationResult.isValid()) { + String returnMessage = "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + + "\"\n"; + returnMessage += validationResult.getResult(); LOGGER.error(returnMessage); - throw new ApexParameterException(returnMessage); + throw new ParameterException(returnMessage); } + if (!validationResult.isClean()) { + String returnMessage = "validation messages(s) on parameters from \"" + arguments.getConfigurationFilePath() + + "\"\n"; + returnMessage += validationResult.getResult(); + + LOGGER.info(returnMessage); + } + + // Register the parameters with the parameter service + registerParameters(parameters); + return parameters; } + + /** + * Register all the incoming parameters with the parameter service + * @param parameters The parameters to register + */ + private void registerParameters(ApexParameters parameters) { + ParameterService.register(parameters); + ParameterService.register(parameters.getEngineServiceParameters()); + ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters()); + ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters()); + ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters().getSchemaParameters()); + ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters().getDistributorParameters()); + ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters().getLockManagerParameters()); + ParameterService.register(parameters.getEngineServiceParameters().getEngineParameters().getContextParameters().getPersistorParameters()); + } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterRuntimeException.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterRuntimeException.java deleted file mode 100644 index a4917f1b6..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameterRuntimeException.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.service.parameters; - -import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; - -/** - * This exception will be called if an error occurs in Apex parameter handling. - * - * @author Liam Fallon - */ -public class ApexParameterRuntimeException extends ApexRuntimeException { - private static final long serialVersionUID = -8507246953751956974L; - - /** - * Instantiates a new apex parameter handling exception with a message. - * - * @param message the message - */ - public ApexParameterRuntimeException(final String message) { - super(message); - } - - /** - * Instantiates a new apex parameter handling exception with a message and a caused by - * exception. - * - * @param message the message - * @param ex the exception that caused this exception to be thrown - */ - public ApexParameterRuntimeException(final String message, final Exception ex) { - super(message, ex); - } -} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java index 9c65c0b32..069bcc9a8 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java @@ -27,38 +27,47 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.model.basicmodel.service.AbstractParameters; -import org.onap.policy.apex.model.basicmodel.service.ParameterService; import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ValidationStatus; /** * The main container parameter class for an Apex service. * - * <p>The following parameters are defined: + * <p> + * The following parameters are defined: * <ol> - * <li>engineServiceParameters: The parameters for the Apex engine service itself, such as the - * number of engine threads to run and the deployment port number to use. - * <li>eventOutputParameters: A map of parameters for event outputs that Apex will use to emit - * events. Apex emits events on all outputs - * <li>eventInputParameters: A map or parameters for event inputs from which Apex will consume - * events. Apex reads events from all its event inputs. - * <li>synchronousEventHandlerParameters: A map of parameters for synchronous event handlers That - * Apex receives events from and replies immediately to those events. + * <li>engineServiceParameters: The parameters for the Apex engine service itself, such as the number of engine threads + * to run and the deployment port number to use. + * <li>eventOutputParameters: A map of parameters for event outputs that Apex will use to emit events. Apex emits events + * on all outputs + * <li>eventInputParameters: A map or parameters for event inputs from which Apex will consume events. Apex reads events + * from all its event inputs. * </ol> * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class ApexParameters extends AbstractParameters implements ApexParameterValidator { +public class ApexParameters implements ParameterGroup { + // Parameter group name + private String name; + + // Constants for recurring strings + private static final String PEER_STRING = "peer "; + private static final String EVENT_INPUT_PARAMETERS_STRING = "eventInputParameters"; + private static final String EVENT_OUTPUT_PARAMETERS_STRING = "eventOutputParameters"; + private static final String FOR_PEERED_MODE_STRING = " for peered mode "; + /** - * Constructor to create an apex parameters instance and register the instance with the - * parameter service. + * Constructor to create an apex parameters instance and register the instance with the parameter service. */ public ApexParameters() { - super(ContextParameters.class.getCanonicalName()); - ParameterService.registerParameters(ApexParameters.class, this); + super(); + + // Set the name for the parameters + this.name = ApexParameterConstants.MAIN_GROUP_NAME; } // Parameters for the engine service and the engine threads in the engine service @@ -124,92 +133,78 @@ public class ApexParameters extends AbstractParameters implements ApexParameterV this.eventInputParameters = eventInputParameters; } - /** - * This method formats a validation result with a header if the result is not empty. - * - * @param validationResultMessage The incoming message - * @param heading The heading to prepend on the message - * @return the formatted message - */ - private String validationResultFormatter(final String validationResultMessage, final String heading) { - final StringBuilder errorMessageBuilder = new StringBuilder(); - - if (validationResultMessage.length() > 0) { - errorMessageBuilder.append(heading); - errorMessageBuilder.append(validationResultMessage); - } + @Override + public String getName() { + return name; + } - return errorMessageBuilder.toString(); + @Override + public void setName(final String name) { + this.name = name; } - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() - */ @Override - public String validate() { - final StringBuilder errorMessageBuilder = new StringBuilder(); + public GroupValidationResult validate() { + GroupValidationResult result = new GroupValidationResult(this); if (engineServiceParameters == null) { - errorMessageBuilder.append(" engine service parameters are not specified\n"); + result.setResult("engineServiceParameters", ValidationStatus.INVALID, + "engine service parameters are not specified"); } else { - errorMessageBuilder.append(validationResultFormatter(engineServiceParameters.validate(), - " engine service parameters invalid\n")); + result.setResult("engineServiceParameters", engineServiceParameters.validate()); } // Sanity check, we must have an entry in both output and input maps - if (eventOutputParameters.isEmpty() || eventInputParameters.isEmpty()) { - errorMessageBuilder.append(" at least one event output and one event input must be specified\n"); + if (eventInputParameters.isEmpty()) { + result.setResult(EVENT_INPUT_PARAMETERS_STRING, ValidationStatus.INVALID, + "at least one event input must be specified"); + } + + if (eventOutputParameters.isEmpty()) { + result.setResult(EVENT_OUTPUT_PARAMETERS_STRING, ValidationStatus.INVALID, + "at least one event output must be specified"); } // Validate that the values of all parameters are ok - validateEventHandlerMap("event input", errorMessageBuilder, eventInputParameters); - validateEventHandlerMap("event output", errorMessageBuilder, eventOutputParameters); + validateEventHandlerMap(EVENT_INPUT_PARAMETERS_STRING, result, eventInputParameters); + validateEventHandlerMap(EVENT_OUTPUT_PARAMETERS_STRING, result, eventOutputParameters); // Only do peer mode validate if there are no other errors - if (errorMessageBuilder.length() == 0) { + if (result.isValid()) { for (final EventHandlerPeeredMode peeredMode : EventHandlerPeeredMode.values()) { - validatePeeredMode(errorMessageBuilder, peeredMode); + validatePeeredMode(result, peeredMode); } } - // Check if we have any errors - if (errorMessageBuilder.length() > 0) { - errorMessageBuilder.insert(0, "Apex parameters invalid\n"); - } - - return errorMessageBuilder.toString().trim(); + return result; } /** * This method validates the parameters in an event handler map. * * @param eventHandlerType the type of the event handler to use on error messages - * @param errorMessageBuilder the builder to use to return validation messages + * @param result the result object to use to return validation messages * @param parsForValidation The event handler parameters to validate (input or output) */ - // CHECKSTYLE:OFF: checkstyle:finalParameter - private void validateEventHandlerMap(final String eventHandlerType, final StringBuilder errorMessageBuilder, - final Map<String, EventHandlerParameters> parsForValidation) { - // CHECKSTYLE:ON: checkstyle:finalParameter + private void validateEventHandlerMap(final String eventHandlerType, final GroupValidationResult result, + final Map<String, EventHandlerParameters> parsForValidation) { for (final Entry<String, EventHandlerParameters> parameterEntry : parsForValidation.entrySet()) { if (parameterEntry.getKey() == null || parameterEntry.getKey().trim().isEmpty()) { - errorMessageBuilder - .append(" invalid " + eventHandlerType + " name \"" + parameterEntry.getKey() + "\" \n"); + result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, + "invalid " + eventHandlerType + " name \"" + parameterEntry.getKey() + "\""); } else if (parameterEntry.getValue() == null) { - errorMessageBuilder.append(" invalid/Null event input prameters specified for " + eventHandlerType - + " name \"" + parameterEntry.getKey() + "\" \n"); + result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, + "invalid/Null event input prameters specified for " + eventHandlerType + " name \"" + + parameterEntry.getKey() + "\" "); } else { - errorMessageBuilder.append(validationResultFormatter(parameterEntry.getValue().validate(), - " " + eventHandlerType + " (" + parameterEntry.getKey() + ") parameters invalid\n")); + result.setResult(eventHandlerType, parameterEntry.getKey(), parameterEntry.getValue().validate()); } parameterEntry.getValue().setName(parameterEntry.getKey()); // Validate parameters for peered mode settings for (final EventHandlerPeeredMode peeredMode : EventHandlerPeeredMode.values()) { - validatePeeredModeParameters(eventHandlerType, errorMessageBuilder, parameterEntry, peeredMode); + validatePeeredModeParameters(eventHandlerType, result, parameterEntry, peeredMode); } } } @@ -218,34 +213,36 @@ public class ApexParameters extends AbstractParameters implements ApexParameterV * Validate parameter values for event handlers in a peered mode. * * @param eventHandlerType The event handler type we are checking - * @param errorMessageBuilder The builder to which to append any error messages + * @param result The result object to which to append any error messages * @param parameterEntry The entry to check the peered mode on * @param peeredMode The mode to check */ - private void validatePeeredModeParameters(final String eventHandlerType, final StringBuilder errorMessageBuilder, - final Entry<String, EventHandlerParameters> parameterEntry, final EventHandlerPeeredMode peeredMode) { - final String messagePreamble = " specified peered mode \"" + peeredMode + "\""; + private void validatePeeredModeParameters(final String eventHandlerType, final GroupValidationResult result, + final Entry<String, EventHandlerParameters> parameterEntry, + final EventHandlerPeeredMode peeredMode) { + final String messagePreamble = "specified peered mode \"" + peeredMode + "\""; final String peer = parameterEntry.getValue().getPeer(peeredMode); if (parameterEntry.getValue().isPeeredMode(peeredMode)) { if (peer == null || peer.trim().isEmpty()) { - errorMessageBuilder.append(messagePreamble + " mandatory parameter not specified or is null on " - + eventHandlerType + " \"" + parameterEntry.getKey() + "\" \n"); + result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, + messagePreamble + " mandatory parameter not specified or is null"); } if (parameterEntry.getValue().getPeerTimeout(peeredMode) < 0) { - errorMessageBuilder.append( - messagePreamble + " timeout value \"" + parameterEntry.getValue().getPeerTimeout(peeredMode) - + "\" is illegal on " + eventHandlerType + " \"" + parameterEntry.getKey() - + "\", specify a non-negative timeout value in milliseconds\n"); + result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, messagePreamble + + " timeout value \"" + parameterEntry.getValue().getPeerTimeout(peeredMode) + + "\" is illegal, specify a non-negative timeout value in milliseconds"); } } else { if (peer != null) { - errorMessageBuilder.append(messagePreamble + " peer is illegal on non synchronous " + eventHandlerType - + " \"" + parameterEntry.getKey() + "\" \n"); + result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, + messagePreamble + " peer is illegal on " + eventHandlerType + " \"" + + parameterEntry.getKey() + "\" "); } if (parameterEntry.getValue().getPeerTimeout(peeredMode) != 0) { - errorMessageBuilder.append(messagePreamble + " timeout is illegal on non synchronous " - + eventHandlerType + " \"" + parameterEntry.getKey() + "\" \n"); + result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, + messagePreamble + " timeout is illegal on " + eventHandlerType + " \"" + + parameterEntry.getKey() + "\""); } } } @@ -253,10 +250,10 @@ public class ApexParameters extends AbstractParameters implements ApexParameterV /** * This method validates that the settings are valid for the given peered mode. * - * @param errorMessageBuilder The builder to which to append any error messages + * @param result The result object to which to append any error messages * @param peeredMode The peered mode to check */ - private void validatePeeredMode(final StringBuilder errorMessageBuilder, final EventHandlerPeeredMode peeredMode) { + private void validatePeeredMode(final GroupValidationResult result, final EventHandlerPeeredMode peeredMode) { // Find the input and output event handlers that use this peered mode final Map<String, EventHandlerParameters> inputParametersUsingMode = new HashMap<>(); final Map<String, EventHandlerParameters> outputParametersUsingMode = new HashMap<>(); @@ -274,23 +271,24 @@ public class ApexParameters extends AbstractParameters implements ApexParameterV } // Validate the parameters for each side of the peered mode parameters - validatePeeredModePeers(" event input for peered mode \"" + peeredMode + "\": ", errorMessageBuilder, - peeredMode, inputParametersUsingMode, outputParametersUsingMode); - validatePeeredModePeers(" event output for peered mode \"" + peeredMode + "\": ", errorMessageBuilder, - peeredMode, outputParametersUsingMode, inputParametersUsingMode); + validatePeeredModePeers(EVENT_INPUT_PARAMETERS_STRING, result, peeredMode, inputParametersUsingMode, + outputParametersUsingMode); + validatePeeredModePeers(EVENT_OUTPUT_PARAMETERS_STRING, result, peeredMode, outputParametersUsingMode, + inputParametersUsingMode); } /** * This method validates that the settings are valid for the event handlers on one. * - * @param messagePreamble the preamble for messages indicating the peered mode side - * @param errorMessageBuilder The builder to which to append any error messages + * @param handlerMapVariableName the variable name of the map on which the paired parameters are being checked + * @param result The result object to which to append any error messages * @param leftModeParameters The mode parameters being checked * @param rightModeParameters The mode parameters being referenced by the checked parameters */ - private void validatePeeredModePeers(final String messagePreamble, final StringBuilder errorMessageBuilder, - final EventHandlerPeeredMode peeredMode, final Map<String, EventHandlerParameters> leftModeParameterMap, - final Map<String, EventHandlerParameters> rightModeParameterMap) { + private void validatePeeredModePeers(final String handlerMapVariableName, final GroupValidationResult result, + final EventHandlerPeeredMode peeredMode, + final Map<String, EventHandlerParameters> leftModeParameterMap, + final Map<String, EventHandlerParameters> rightModeParameterMap) { // These sets are used to check for duplicate references on the both sides final Set<String> leftCheckDuplicateSet = new HashSet<>(); @@ -306,52 +304,74 @@ public class ApexParameters extends AbstractParameters implements ApexParameterV // Check that the peer reference is OK if (rightModeParameters == null) { - errorMessageBuilder.append(messagePreamble + "peer \"" + leftModeParameters.getPeer(peeredMode) - + "\" for event handler \"" + leftModeParameterEntry.getKey() - + "\" does not exist or is not defined as being synchronous\n"); + result.setResult(handlerMapVariableName, leftModeParameterEntry.getKey(), ValidationStatus.INVALID, + PEER_STRING + '"' + leftModeParameters.getPeer(peeredMode) + FOR_PEERED_MODE_STRING + peeredMode + + " does not exist or is not defined with the same peered mode"); continue; } // Now check that the right side peer is the left side event handler final String rightSidePeer = rightModeParameters.getPeer(peeredMode); if (!rightSidePeer.equals(leftModeParameterEntry.getKey())) { - errorMessageBuilder - .append(messagePreamble + "peer value \"" + rightSidePeer + "\" on peer \"" + leftSidePeer - + "\" does not equal event handler \"" + leftModeParameterEntry.getKey() + "\"\n"); + result.setResult(handlerMapVariableName, leftModeParameterEntry.getKey(), ValidationStatus.INVALID, + PEER_STRING + '"' + leftModeParameters.getPeer(peeredMode) + FOR_PEERED_MODE_STRING + peeredMode + + ", value \"" + rightSidePeer + "\" on peer \"" + leftSidePeer + + "\" does not equal event handler \"" + leftModeParameterEntry.getKey() + + "\""); } else { // Check for duplicates if (!leftCheckDuplicateSet.add(leftSidePeer)) { - errorMessageBuilder - .append(messagePreamble + "peer value \"" + leftSidePeer + "\" on event handler \"" - + leftModeParameterEntry.getKey() + "\" is used more than once\n"); + result.setResult(handlerMapVariableName, leftModeParameterEntry.getKey(), ValidationStatus.INVALID, + PEER_STRING + '"' + leftModeParameters.getPeer(peeredMode) + FOR_PEERED_MODE_STRING + + peeredMode + ", peer value \"" + leftSidePeer + + "\" on event handler \"" + leftModeParameterEntry.getKey() + + "\" is used more than once"); } if (!rightCheckDuplicateSet.add(rightSidePeer)) { - errorMessageBuilder.append(messagePreamble + "peer value \"" + rightSidePeer + "\" on peer \"" - + leftSidePeer + "\" on event handler \"" + leftModeParameterEntry.getKey() - + "\" is used more than once\n"); + result.setResult(handlerMapVariableName, leftModeParameterEntry.getKey(), ValidationStatus.INVALID, + PEER_STRING + '"' + leftModeParameters.getPeer(peeredMode) + FOR_PEERED_MODE_STRING + + peeredMode + ", peer value \"" + rightSidePeer + "\" on peer \"" + + leftSidePeer + "\" on event handler \"" + + leftModeParameterEntry.getKey() + "\" is used more than once"); } } - // Cross-set the timeouts if they are not specified - if (leftModeParameters.getPeerTimeout(peeredMode) != 0) { - if (rightModeParameters.getPeerTimeout(peeredMode) != 0) { - if (leftModeParameters.getPeerTimeout(peeredMode) != rightModeParameters - .getPeerTimeout(peeredMode)) { - errorMessageBuilder.append(messagePreamble + "timeout " - + leftModeParameters.getPeerTimeout(peeredMode) + "on event handler \"" - + leftModeParameters.getName() + "\" does not equal timeout value " - + rightModeParameters.getPeerTimeout(peeredMode) + "on event handler \"" - + rightModeParameters.getName() + "\"\n"); - } - } else { - rightModeParameters.setPeerTimeout(peeredMode, leftModeParameters.getPeerTimeout(peeredMode)); + if (!crossCheckPeeredTimeoutValues(leftModeParameters, rightModeParameters, peeredMode)) { + result.setResult(handlerMapVariableName, leftModeParameterEntry.getKey(), ValidationStatus.INVALID, + PEER_STRING + '"' + leftModeParameters.getPeer(peeredMode) + FOR_PEERED_MODE_STRING + peeredMode + + " timeout " + leftModeParameters.getPeerTimeout(peeredMode) + + " on event handler \"" + leftModeParameters.getName() + + "\" does not equal timeout " + + rightModeParameters.getPeerTimeout(peeredMode) + " on event handler \"" + + rightModeParameters.getName() + "\""); + + } + } + } + + /** + * Validate the timeout values on two peers. + * + * @param leftModeParameters The parameters of the left hand peer + * @param peeredMode The peered mode being checked + * @return true if the timeout values are cross checked as being OK + */ + private boolean crossCheckPeeredTimeoutValues(final EventHandlerParameters leftModeParameters, + final EventHandlerParameters rightModeParameters, final EventHandlerPeeredMode peeredMode) { + // Cross-set the timeouts if they are not specified + if (leftModeParameters.getPeerTimeout(peeredMode) != 0) { + if (rightModeParameters.getPeerTimeout(peeredMode) != 0) { + if (leftModeParameters.getPeerTimeout(peeredMode) != rightModeParameters.getPeerTimeout(peeredMode)) { + return false; } } else { - if (rightModeParameters.getPeerTimeout(peeredMode) != 0) { - leftModeParameters.setPeerTimeout(peeredMode, rightModeParameters.getPeerTimeout(peeredMode)); - } + rightModeParameters.setPeerTimeout(peeredMode, leftModeParameters.getPeerTimeout(peeredMode)); + } + } else { + if (rightModeParameters.getPeerTimeout(peeredMode) != 0) { + leftModeParameters.setPeerTimeout(peeredMode, rightModeParameters.getPeerTimeout(peeredMode)); } } - + return true; } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java index 025183328..0c10df706 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParameters.java @@ -20,25 +20,28 @@ package org.onap.policy.apex.service.parameters.carriertechnology; -import org.onap.policy.apex.model.basicmodel.service.AbstractParameters; -import org.onap.policy.apex.service.parameters.ApexParameterValidator; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ParameterRuntimeException; +import org.onap.policy.common.parameters.ValidationStatus; /** - * The default carrier technology parameter class that may be specialized by carrier technology - * plugins that require plugin specific parameters. + * The default carrier technology parameter class that may be specialized by carrier technology plugins that require + * plugin specific parameters. * - * <p>The following parameters are defined: + * <p> + * The following parameters are defined: * <ol> * <li>label: The label of the carrier technology. - * <li>eventProducerPluginClass: The name of the plugin class that will be used by Apex to produce - * and emit output events for this carrier technology - * <li>eventConsumerPluginClass: The name of the plugin class that will be used by Apex to receive - * and process input events from this carrier technology carrier technology + * <li>eventProducerPluginClass: The name of the plugin class that will be used by Apex to produce and emit output + * events for this carrier technology + * <li>eventConsumerPluginClass: The name of the plugin class that will be used by Apex to receive and process input + * events from this carrier technology carrier technology * </ol> * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public abstract class CarrierTechnologyParameters extends AbstractParameters implements ApexParameterValidator { +public abstract class CarrierTechnologyParameters implements ParameterGroup { // The carrier technology label private String label = null; @@ -49,13 +52,13 @@ public abstract class CarrierTechnologyParameters extends AbstractParameters imp private String eventConsumerPluginClass = null; /** - * Constructor to create a carrier technology parameters instance with the name of a sub class - * of this class and register the instance with the parameter service. + * Constructor to create a carrier technology parameters instance with the name of a sub class of this class and + * register the instance with the parameter service. * * @param parameterClassName the class name of a sub class of this class */ - public CarrierTechnologyParameters(final String parameterClassName) { - super(parameterClassName); + public CarrierTechnologyParameters() { + super(); } /** @@ -132,7 +135,7 @@ public abstract class CarrierTechnologyParameters extends AbstractParameters imp @Override public String toString() { return "CarrierTechnologyParameters [label=" + label + ", eventProducerPluginClass=" + eventProducerPluginClass - + ", eventConsumerPluginClass=" + eventConsumerPluginClass + "]"; + + ", eventConsumerPluginClass=" + eventConsumerPluginClass + "]"; } /* @@ -141,21 +144,34 @@ public abstract class CarrierTechnologyParameters extends AbstractParameters imp * @see org.onap.policy.apex.service.parameters.ApexParameterValidator#validate() */ @Override - public String validate() { - final StringBuilder errorMessageBuilder = new StringBuilder(); + public GroupValidationResult validate() { + final GroupValidationResult result = new GroupValidationResult(this); if (label == null || label.length() == 0) { - errorMessageBuilder.append(" carrier technology label not specified or is blank\n"); + result.setResult("label", ValidationStatus.INVALID, "carrier technology label not specified or is blank"); } if (eventProducerPluginClass == null || eventProducerPluginClass.length() == 0) { - errorMessageBuilder.append(" carrier technology eventProducerPluginClass not specified or is blank\n"); + result.setResult("eventProducerPluginClass", ValidationStatus.INVALID, + "carrier technology eventProducerPluginClass not specified or is blank"); } if (eventConsumerPluginClass == null || eventConsumerPluginClass.length() == 0) { - errorMessageBuilder.append(" carrier technology eventConsumerPluginClass not specified or is blank\n"); + result.setResult("eventConsumerPluginClass", ValidationStatus.INVALID, + "carrier technology eventConsumerPluginClass not specified or is blank"); } - return errorMessageBuilder.toString(); + return result; } + + @Override + public String getName() { + return this.getLabel(); + } + + @Override + public void setName(final String name) { + throw new ParameterRuntimeException("the name/label of this carrier technology is always \"" + getLabel() + "\""); + } + } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJSONAdapter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJSONAdapter.java index 38abd3c6c..e443c1eb0 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJSONAdapter.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJSONAdapter.java @@ -26,7 +26,7 @@ import java.util.Map; import org.onap.policy.apex.service.engine.event.impl.eventrequestor.EventRequestorCarrierTechnologyParameters; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FILECarrierTechnologyParameters; -import org.onap.policy.apex.service.parameters.ApexParameterRuntimeException; +import org.onap.policy.common.parameters.ParameterRuntimeException; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -34,7 +34,6 @@ import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; @@ -74,7 +73,7 @@ public class CarrierTechnologyParametersJSONAdapter final JsonSerializationContext context) { final String returnMessage = "serialization of Apex carrier technology parameters to Json is not supported"; LOGGER.error(returnMessage); - throw new ApexParameterRuntimeException(returnMessage); + throw new ParameterRuntimeException(returnMessage); } /* @@ -85,7 +84,7 @@ public class CarrierTechnologyParametersJSONAdapter */ @Override public CarrierTechnologyParameters deserialize(final JsonElement json, final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { + final JsonDeserializationContext context) { final JsonObject jsonObject = json.getAsJsonObject(); // Get the carrier technology label primitive @@ -103,7 +102,7 @@ public class CarrierTechnologyParametersJSONAdapter final String errorMessage = "carrier technology parameter \"" + CARRIER_TECHNOLOGY_TOKEN + "\" value \"" + labelJsonPrimitive.getAsString() + "\" invalid in JSON file"; LOGGER.warn(errorMessage); - throw new ApexParameterRuntimeException(errorMessage); + throw new ParameterRuntimeException(errorMessage); } // We now get the technology carrier parameter class @@ -130,7 +129,7 @@ public class CarrierTechnologyParametersJSONAdapter + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null") + "\" invalid in JSON file"; LOGGER.warn(errorMessage); - throw new ApexParameterRuntimeException(errorMessage); + throw new ParameterRuntimeException(errorMessage); } // Get the class for the carrier technology @@ -142,7 +141,7 @@ public class CarrierTechnologyParametersJSONAdapter "carrier technology \"" + carrierTechnologyLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + "\" value \"" + carrierTechnologyParameterClassName + "\", could not find class"; LOGGER.warn(errorMessage, e); - throw new ApexParameterRuntimeException(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); } // Deserialise the class @@ -158,7 +157,7 @@ public class CarrierTechnologyParametersJSONAdapter final String errorMessage = "could not create default parameters for carrier technology \"" + carrierTechnologyLabel + "\"\n" + e.getMessage(); LOGGER.warn(errorMessage, e); - throw new ApexParameterRuntimeException(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); } } @@ -170,7 +169,7 @@ public class CarrierTechnologyParametersJSONAdapter + "\", specify correct carrier technology parameter plugin in parameter \"" + PARAMETER_CLASS_NAME + "\""; LOGGER.warn(errorMessage); - throw new ApexParameterRuntimeException(errorMessage); + throw new ParameterRuntimeException(errorMessage); } return carrierTechnologyParameters; diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParameters.java index 3a53b59cb..70badae93 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParameters.java @@ -24,42 +24,42 @@ import java.io.File; import java.net.URL; import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.basicmodel.service.AbstractParameters; -import org.onap.policy.apex.model.basicmodel.service.ParameterService; -import org.onap.policy.apex.service.parameters.ApexParameterValidator; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.service.parameters.ApexParameterConstants; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ValidationStatus; import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.apex.core.engine.EngineParameters; /** - * This class holds the parameters for an Apex Engine Service with multiple engine threads running - * multiple engines. + * This class holds the parameters for an Apex Engine Service with multiple engine threads running multiple engines. * - * <p>The following parameters are defined: + * <p> + * The following parameters are defined: * <ol> - * <li>name: The name of the Apex engine service, which can be set to any value that matches the - * regular expression {@link org.onap.policy.apex.model.basicmodel.concepts.AxKey#NAME_REGEXP}. - * <li>version: The name of the Apex engine service, which can be set to any value that matches the - * regular expression {@link org.onap.policy.apex.model.basicmodel.concepts.AxKey#VERSION_REGEXP}. + * <li>name: The name of the Apex engine service, which can be set to any value that matches the regular expression + * {@link org.onap.policy.apex.model.basicmodel.concepts.AxKey#NAME_REGEXP}. + * <li>version: The name of the Apex engine service, which can be set to any value that matches the regular expression + * {@link org.onap.policy.apex.model.basicmodel.concepts.AxKey#VERSION_REGEXP}. * <li>id: The ID of the Apex engine service, which can be set to any integer value by a user. - * <li>instanceCount: The number of Apex engines to spawn in this engine service. Each engine - * executes in its own thread. - * <li>deploymentPort: The port that the Apex Engine Service will open so that it can be managed - * using the EngDep protocol. The EngDep protocol allows the engine service to be monitored, to - * start and stop engines in the engine service, and to update the policy model of the engine - * service. - * <li>engineParameters: Parameters (a {@link EngineParameters} instance) that all of the engines in - * the engine service will use. All engine threads use the same parameters and act as a pool of - * engines. Engine parameters specify the executors and context management for the engines. - * <li>policyModelFileName: The full path to the policy model file name to deploy on the engine - * service. - * <li>periodicEventPeriod: The period in milliseconds at which the periodic event PERIOIC_EVENT - * will be generated by APEX, 0 means no periodic event generation, negative values are illegal. + * <li>instanceCount: The number of Apex engines to spawn in this engine service. Each engine executes in its own + * thread. + * <li>deploymentPort: The port that the Apex Engine Service will open so that it can be managed using the EngDep + * protocol. The EngDep protocol allows the engine service to be monitored, to start and stop engines in the engine + * service, and to update the policy model of the engine service. + * <li>engineParameters: Parameters (a {@link EngineParameters} instance) that all of the engines in the engine service + * will use. All engine threads use the same parameters and act as a pool of engines. Engine parameters specify the + * executors and context management for the engines. + * <li>policyModelFileName: The full path to the policy model file name to deploy on the engine service. + * <li>periodicEventPeriod: The period in milliseconds at which the periodic event PERIOIC_EVENT will be generated by + * APEX, 0 means no periodic event generation, negative values are illegal. * </ol> * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class EngineServiceParameters extends AbstractParameters implements ApexParameterValidator { +public class EngineServiceParameters implements ParameterGroup { private static final int MAX_PORT = 65535; // @formatter:off @@ -78,6 +78,9 @@ public class EngineServiceParameters extends AbstractParameters implements ApexP /** The default EngDep deployment port of the Apex engine service. */ public static final int DEFAULT_DEPLOYMENT_PORT = 34421; + // Constants for repeated strings + private static final String POLICY_MODEL_FILE_NAME = "policyModelFileName"; + // Apex engine service parameters private String name = DEFAULT_NAME; private String version = DEFAULT_VERSION; @@ -92,12 +95,14 @@ public class EngineServiceParameters extends AbstractParameters implements ApexP private EngineParameters engineParameters = new EngineParameters(); /** - * Constructor to create an apex engine service parameters instance and register the instance - * with the parameter service. + * Constructor to create an apex engine service parameters instance and register the instance with the parameter + * service. */ public EngineServiceParameters() { - super(EngineServiceParameters.class.getCanonicalName()); - ParameterService.registerParameters(EngineServiceParameters.class, this); + super(); + + // Set the name for the parameters + this.name = ApexParameterConstants.ENGINE_SERVICE_GROUP_NAME; } /** @@ -221,16 +226,14 @@ public class EngineServiceParameters extends AbstractParameters implements ApexP /** * Sets the file name of the policy engine for deployment on the engine service. * - * @param policyModelFileName the file name of the policy engine for deployment on the engine - * service + * @param policyModelFileName the file name of the policy engine for deployment on the engine service */ public void setPolicyModelFileName(final String policyModelFileName) { this.policyModelFileName = policyModelFileName; } /** - * Get the period in milliseconds at which periodic events are sent, zero means no periodic - * events are being sent. + * Get the period in milliseconds at which periodic events are sent, zero means no periodic events are being sent. * * @return the periodic period */ @@ -239,8 +242,8 @@ public class EngineServiceParameters extends AbstractParameters implements ApexP } /** - * Set the period in milliseconds at which periodic events are sent, zero means no periodic - * events are to be sent, negative values are illegal. + * Set the period in milliseconds at which periodic events are sent, zero means no periodic events are to be sent, + * negative values are illegal. * * @param periodicEventPeriod the periodic period */ @@ -272,57 +275,67 @@ public class EngineServiceParameters extends AbstractParameters implements ApexP * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() */ @Override - public String validate() { - final StringBuilder errorMessageBuilder = new StringBuilder(); - - try { - new AxArtifactKey(name, version); - } catch (final Exception e) { - errorMessageBuilder.append(" name [" + name + "] and/or version [" + version + "] invalid\n"); - errorMessageBuilder.append(" " + e.getMessage() + "\n"); + public GroupValidationResult validate() { + final GroupValidationResult result = new GroupValidationResult(this); + + if (name == null || !name.matches(AxKey.NAME_REGEXP)) { + result.setResult("name", ValidationStatus.INVALID, + "name is invalid, it must match regular expression" + AxKey.NAME_REGEXP); + } + + if (version == null || !version.matches(AxKey.VERSION_REGEXP)) { + result.setResult("version", ValidationStatus.INVALID, + "version is invalid, it must match regular expression" + AxKey.VERSION_REGEXP); } if (id < 0) { - errorMessageBuilder.append( - " id not specified or specified value [" + id + "] invalid, must be specified as id >= 0\n"); + result.setResult("id", ValidationStatus.INVALID, + "id not specified or specified value [" + id + "] invalid, must be specified as id >= 0"); } if (instanceCount < 1) { - errorMessageBuilder.append( - " instanceCount [" + instanceCount + "] invalid, must be specified as instanceCount >= 1\n"); + result.setResult("instanceCount", ValidationStatus.INVALID, + "instanceCount [" + instanceCount + "] invalid, must be specified as instanceCount >= 1"); } if (deploymentPort < 1 || deploymentPort > MAX_PORT) { - errorMessageBuilder.append( - " deploymentPort [" + deploymentPort + "] invalid, must be specified as 1024 <= port <= 65535\n"); + result.setResult("deploymentPort", ValidationStatus.INVALID, "deploymentPort [" + deploymentPort + + "] invalid, must be specified as 1024 <= port <= 65535"); } if (policyModelFileName != null) { - if (policyModelFileName.trim().length() == 0) { - errorMessageBuilder.append(" policyModelFileName [" + policyModelFileName - + "] invalid, must be specified as a non-empty string\n"); - } else { - // The file name can refer to a resource on the local file system or on the class - // path - final URL fileURL = ResourceUtils.getUrl4Resource(policyModelFileName); - if (fileURL == null) { - errorMessageBuilder.append( - " policyModelFileName [" + policyModelFileName + "] not found or is not a plain file\n"); - } else { - final File policyModelFile = new File(fileURL.getPath()); - if (!policyModelFile.isFile()) { - errorMessageBuilder.append(" policyModelFileName [" + policyModelFileName - + "] not found or is not a plain file\n"); - } - } - } + validatePolicyModelFileName(result); } if (periodicEventPeriod < 0) { - errorMessageBuilder.append(" periodicEventPeriod [" + periodicEventPeriod - + "] invalid, must be specified in milliseconds as >=0\n"); + result.setResult("periodicEventPeriod", ValidationStatus.INVALID, "periodicEventPeriod [" + + periodicEventPeriod + "] invalid, must be specified in milliseconds as >=0"); } - return errorMessageBuilder.toString(); + return result; + } + + /** + * Validate the policy model file name parameter + * @param result the variable in which to store the result of the validation + */ + private void validatePolicyModelFileName(final GroupValidationResult result) { + if (policyModelFileName.trim().length() == 0) { + result.setResult(POLICY_MODEL_FILE_NAME, ValidationStatus.INVALID, "\"" + + policyModelFileName + "\" invalid, must be specified as a non-empty string"); + return; + } + + // The file name can refer to a resource on the local file system or on the class + // path + final URL fileURL = ResourceUtils.getUrl4Resource(policyModelFileName); + if (fileURL == null) { + result.setResult(POLICY_MODEL_FILE_NAME, ValidationStatus.INVALID, "not found or is not a plain file"); + } else { + final File policyModelFile = new File(fileURL.getPath()); + if (!policyModelFile.isFile()) { + result.setResult(POLICY_MODEL_FILE_NAME, ValidationStatus.INVALID, "not found or is not a plain file"); + } + } } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJSONAdapter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJSONAdapter.java index 9fca2fd19..98e41f6af 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJSONAdapter.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJSONAdapter.java @@ -32,8 +32,8 @@ import org.onap.policy.apex.context.parameters.SchemaHelperParameters; import org.onap.policy.apex.context.parameters.SchemaParameters; import org.onap.policy.apex.core.engine.EngineParameters; import org.onap.policy.apex.core.engine.ExecutorParameters; -import org.onap.policy.apex.model.basicmodel.service.AbstractParameters; -import org.onap.policy.apex.service.parameters.ApexParameterRuntimeException; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ParameterRuntimeException; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -47,13 +47,12 @@ import com.google.gson.JsonSerializer; /** * This class deserializes engine service parameters from JSON format. The class produces an - * {@link EngineServiceParameters} instance from incoming JSON read from a configuration file in - * JSON format. + * {@link EngineServiceParameters} instance from incoming JSON read from a configuration file in JSON format. * * @author Liam Fallon (liam.fallon@ericsson.com) */ public class EngineServiceParametersJSONAdapter - implements JsonSerializer<EngineParameters>, JsonDeserializer<EngineParameters> { + implements JsonSerializer<EngineParameters>, JsonDeserializer<EngineParameters> { private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineServiceParametersJSONAdapter.class); private static final String PARAMETER_CLASS_NAME = "parameterClassName"; @@ -75,28 +74,28 @@ public class EngineServiceParametersJSONAdapter */ @Override public JsonElement serialize(final EngineParameters src, final Type typeOfSrc, - final JsonSerializationContext context) { + final JsonSerializationContext context) { final String returnMessage = "serialization of Apex parameters to Json is not supported"; LOGGER.error(returnMessage); - throw new ApexParameterRuntimeException(returnMessage); + throw new ParameterRuntimeException(returnMessage); } /* * (non-Javadoc) * - * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, - * java.lang.reflect.Type, com.google.gson.JsonDeserializationContext) + * @see com.google.gson.JsonDeserializer#deserialize(com.google.gson.JsonElement, java.lang.reflect.Type, + * com.google.gson.JsonDeserializationContext) */ @Override public EngineParameters deserialize(final JsonElement json, final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { + final JsonDeserializationContext context) { final JsonObject engineParametersJsonObject = json.getAsJsonObject(); final EngineParameters engineParameters = new EngineParameters(); // Deserialise context parameters, they may be a subclass of the ContextParameters class engineParameters.setContextParameters( - (ContextParameters) context.deserialize(engineParametersJsonObject, ContextParameters.class)); + (ContextParameters) context.deserialize(engineParametersJsonObject, ContextParameters.class)); // Context parameter wrangling getContextParameters(engineParametersJsonObject, engineParameters, context); @@ -115,7 +114,7 @@ public class EngineServiceParametersJSONAdapter * @param context the JSON context */ private void getContextParameters(final JsonObject engineParametersJsonObject, - final EngineParameters engineParameters, final JsonDeserializationContext context) { + final EngineParameters engineParameters, final JsonDeserializationContext context) { final JsonElement contextParametersElement = engineParametersJsonObject.get(CONTEXT_PARAMETERS); // Context parameters are optional so if the element does not exist, just return @@ -124,8 +123,8 @@ public class EngineServiceParametersJSONAdapter } // We do this because the JSON parameters may be for a subclass of ContextParameters - final ContextParameters contextParameters = - (ContextParameters) deserializeParameters(CONTEXT_PARAMETERS, contextParametersElement, context); + final ContextParameters contextParameters = (ContextParameters) deserializeParameters(CONTEXT_PARAMETERS, + contextParametersElement, context); // We know this will work because if the context parameters was not a Json object, the // previous deserializeParameters() call would not have worked @@ -134,22 +133,20 @@ public class EngineServiceParametersJSONAdapter // Now get the distributor, lock manager, and persistence parameters final JsonElement distributorParametersElement = contextParametersObject.get(DISTRIBUTOR_PARAMETERS); if (distributorParametersElement != null) { - contextParameters - .setDistributorParameters((DistributorParameters) deserializeParameters(DISTRIBUTOR_PARAMETERS, - distributorParametersElement, context)); + contextParameters.setDistributorParameters((DistributorParameters) deserializeParameters( + DISTRIBUTOR_PARAMETERS, distributorParametersElement, context)); } final JsonElement lockManagerParametersElement = contextParametersObject.get(LOCK_MANAGER_PARAMETERS); if (lockManagerParametersElement != null) { - contextParameters - .setLockManagerParameters((LockManagerParameters) deserializeParameters(LOCK_MANAGER_PARAMETERS, - lockManagerParametersElement, context)); + contextParameters.setLockManagerParameters((LockManagerParameters) deserializeParameters( + LOCK_MANAGER_PARAMETERS, lockManagerParametersElement, context)); } final JsonElement persistorParametersElement = contextParametersObject.get(PERSISTOR_PARAMETERS); if (persistorParametersElement != null) { contextParameters.setPersistorParameters((PersistorParameters) deserializeParameters(PERSISTOR_PARAMETERS, - persistorParametersElement, context)); + persistorParametersElement, context)); } // Schema Handler parameter wrangling @@ -167,25 +164,24 @@ public class EngineServiceParametersJSONAdapter * @param context the JSON context */ private void getExecutorParameters(final JsonObject engineParametersJsonObject, - final EngineParameters engineParameters, final JsonDeserializationContext context) { + final EngineParameters engineParameters, final JsonDeserializationContext context) { final JsonElement executorParametersElement = engineParametersJsonObject.get(EXECUTOR_PARAMETERS); // Executor parameters are mandatory so if the element does not exist throw an exception if (executorParametersElement == null) { final String returnMessage = "no \"" + EXECUTOR_PARAMETERS - + "\" entry found in parameters, at least one executor parameter entry must be specified"; + + "\" entry found in parameters, at least one executor parameter entry must be specified"; LOGGER.error(returnMessage); - throw new ApexParameterRuntimeException(returnMessage); + throw new ParameterRuntimeException(returnMessage); } // Deserialize the executor parameters - final JsonObject executorParametersJsonObject = - engineParametersJsonObject.get(EXECUTOR_PARAMETERS).getAsJsonObject(); + final JsonObject executorParametersJsonObject = engineParametersJsonObject.get(EXECUTOR_PARAMETERS) + .getAsJsonObject(); for (final Entry<String, JsonElement> executorEntries : executorParametersJsonObject.entrySet()) { - final ExecutorParameters executorParameters = - (ExecutorParameters) deserializeParameters(EXECUTOR_PARAMETERS + ':' + executorEntries.getKey(), - executorEntries.getValue(), context); + final ExecutorParameters executorParameters = (ExecutorParameters) deserializeParameters( + EXECUTOR_PARAMETERS + ':' + executorEntries.getKey(), executorEntries.getValue(), context); engineParameters.getExecutorParameterMap().put(executorEntries.getKey(), executorParameters); } } @@ -198,12 +194,12 @@ public class EngineServiceParametersJSONAdapter * @param context the JSON context */ private void getSchemaHandlerParameters(final JsonObject contextParametersJsonObject, - final ContextParameters contextParameters, final JsonDeserializationContext context) { + final ContextParameters contextParameters, final JsonDeserializationContext context) { final JsonElement schemaParametersElement = contextParametersJsonObject.get(SCHEMA_PARAMETERS); // Insert the default Java schema helper contextParameters.getSchemaParameters().getSchemaHelperParameterMap() - .put(SchemaParameters.DEFAULT_SCHEMA_FLAVOUR, new JavaSchemaHelperParameters()); + .put(SchemaParameters.DEFAULT_SCHEMA_FLAVOUR, new JavaSchemaHelperParameters()); // Context parameters are optional so if the element does not exist, just return if (schemaParametersElement == null) { @@ -211,14 +207,14 @@ public class EngineServiceParametersJSONAdapter } // Deserialize the executor parameters - final JsonObject schemaHelperParametersJsonObject = - contextParametersJsonObject.get(SCHEMA_PARAMETERS).getAsJsonObject(); + final JsonObject schemaHelperParametersJsonObject = contextParametersJsonObject.get(SCHEMA_PARAMETERS) + .getAsJsonObject(); for (final Entry<String, JsonElement> schemaHelperEntries : schemaHelperParametersJsonObject.entrySet()) { contextParameters.getSchemaParameters().getSchemaHelperParameterMap().put(schemaHelperEntries.getKey(), - (SchemaHelperParameters) deserializeParameters( - SCHEMA_PARAMETERS + ':' + schemaHelperEntries.getKey(), schemaHelperEntries.getValue(), - context)); + (SchemaHelperParameters) deserializeParameters( + SCHEMA_PARAMETERS + ':' + schemaHelperEntries.getKey(), + schemaHelperEntries.getValue(), context)); } } @@ -229,10 +225,10 @@ public class EngineServiceParametersJSONAdapter * @param parametersElement The JSON object holding the parameters * @param context The GSON context * @return the parameters - * @throws ApexParameterRuntimeException on errors reading the parameters + * @throws ParameterRuntimeException on errors reading the parameters */ - private AbstractParameters deserializeParameters(final String parametersLabel, final JsonElement parametersElement, - final JsonDeserializationContext context) throws ApexParameterRuntimeException { + private ParameterGroup deserializeParameters(final String parametersLabel, final JsonElement parametersElement, + final JsonDeserializationContext context) { JsonObject parametersObject = null; // Check that the JSON element is a JSON object @@ -241,45 +237,45 @@ public class EngineServiceParametersJSONAdapter } else { final String returnMessage = "value of \"" + parametersLabel + "\" entry is not a parameter JSON object"; LOGGER.error(returnMessage); - throw new ApexParameterRuntimeException(returnMessage); + throw new ParameterRuntimeException(returnMessage); } // Get the parameter class name for instantiation in deserialization final JsonElement parameterClassNameElement = parametersObject.get(PARAMETER_CLASS_NAME); if (parameterClassNameElement == null) { - final String returnMessage = - "could not find field \"" + PARAMETER_CLASS_NAME + "\" in \"" + parametersLabel + "\" entry"; + final String returnMessage = "could not find field \"" + PARAMETER_CLASS_NAME + "\" in \"" + parametersLabel + + "\" entry"; LOGGER.error(returnMessage); - throw new ApexParameterRuntimeException(returnMessage); + throw new ParameterRuntimeException(returnMessage); } // Check the parameter is a JSON primitive if (!parameterClassNameElement.isJsonPrimitive()) { - final String returnMessage = "value for field \"" + PARAMETER_CLASS_NAME + "\" in \"" + parametersLabel - + "\" entry is not a plain string"; + final String returnMessage = "value for field \"" + PARAMETER_CLASS_NAME + "\" of \"" + parametersLabel + + "\" entry is not a plain string"; LOGGER.error(returnMessage); - throw new ApexParameterRuntimeException(returnMessage); + throw new ParameterRuntimeException(returnMessage); } // Check the parameter has a value final String parameterClassName = parameterClassNameElement.getAsString(); if (parameterClassName == null || parameterClassName.trim().length() == 0) { final String returnMessage = "value for field \"" + PARAMETER_CLASS_NAME + "\" in \"" + parametersLabel - + "\" entry is not specified or is blank"; + + "\" entry is not specified or is blank"; LOGGER.error(returnMessage); - throw new ApexParameterRuntimeException(returnMessage); + throw new ParameterRuntimeException(returnMessage); } // Deserialize the parameters using GSON - AbstractParameters parameters = null; + ParameterGroup parameters = null; try { parameters = context.deserialize(parametersObject, Class.forName(parameterClassName)); } catch (JsonParseException | ClassNotFoundException e) { - final String returnMessage = - "failed to deserialize the parameters for \"" + parametersLabel + "\" " + "to parameter class \"" - + parameterClassName + "\"\n" + e.getClass().getCanonicalName() + ": " + e.getMessage(); + final String returnMessage = "failed to deserialize the parameters for \"" + parametersLabel + "\" " + + "to parameter class \"" + parameterClassName + "\"\n" + e.getClass().getCanonicalName() + + ": " + e.getMessage(); LOGGER.error(returnMessage, e); - throw new ApexParameterRuntimeException(returnMessage, e); + throw new ParameterRuntimeException(returnMessage, e); } return parameters; diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventhandler/EventHandlerParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventhandler/EventHandlerParameters.java index 164544b4e..76ccd683c 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventhandler/EventHandlerParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventhandler/EventHandlerParameters.java @@ -23,42 +23,42 @@ package org.onap.policy.apex.service.parameters.eventhandler; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; -import org.onap.policy.apex.model.basicmodel.service.AbstractParameters; -import org.onap.policy.apex.service.parameters.ApexParameterValidator; +import org.onap.policy.apex.service.parameters.ApexParameterConstants; import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ValidationStatus; /** * The parameters for a single event producer, event consumer or synchronous event handler. * - * <p>Event producers, consumers, and synchronous event handlers all use a carrier technology and an - * event protocol so the actual parameters for each one are the same. Therefore, we use the same - * class for the parameters of each one. + * <p> + * Event producers, consumers, and synchronous event handlers all use a carrier technology and an event protocol so the + * actual parameters for each one are the same. Therefore, we use the same class for the parameters of each one. * - * <p>The following parameters are defined: + * <p> + * The following parameters are defined: * <ol> - * <li>carrierTechnologyParameters: The carrier technology is the type of messaging infrastructure - * used to carry events. Examples are File, Kafka or REST. - * <li>eventProtocolParameters: The format that the events are in when being carried. Examples are - * JSON, XML, or Java Beans. carrier technology + * <li>carrierTechnologyParameters: The carrier technology is the type of messaging infrastructure used to carry events. + * Examples are File, Kafka or REST. + * <li>eventProtocolParameters: The format that the events are in when being carried. Examples are JSON, XML, or Java + * Beans. carrier technology * <li>synchronousMode: true if the event handler is working in synchronous mode, defaults to false - * <li>synchronousPeer: the peer event handler (consumer for producer or producer for consumer) of - * this event handler in synchronous mode - * <li>synchronousTimeout: the amount of time to wait for the reply to synchronous events before - * they are timed out + * <li>synchronousPeer: the peer event handler (consumer for producer or producer for consumer) of this event handler in + * synchronous mode + * <li>synchronousTimeout: the amount of time to wait for the reply to synchronous events before they are timed out * <li>requestorMode: true if the event handler is working in requestor mode, defaults to false - * <li>requestorPeer: the peer event handler (consumer for producer or producer for consumer) of - * this event handler in requestor mode - * <li>requestorTimeout: the amount of time to wait for the reply to synchronous events before they - * are timed out - * <li>eventNameFilter: a regular expression to apply to events on this event handler. If specified, - * events not matching the given regular expression are ignored. If it is null, all events are - * handledDefaults to null. + * <li>requestorPeer: the peer event handler (consumer for producer or producer for consumer) of this event handler in + * requestor mode + * <li>requestorTimeout: the amount of time to wait for the reply to synchronous events before they are timed out + * <li>eventNameFilter: a regular expression to apply to events on this event handler. If specified, events not matching + * the given regular expression are ignored. If it is null, all events are handledDefaults to null. * </ol> * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class EventHandlerParameters extends AbstractParameters implements ApexParameterValidator { +public class EventHandlerParameters implements ParameterGroup { private String name = null; private CarrierTechnologyParameters carrierTechnologyParameters = null; private EventProtocolParameters eventProtocolParameters = null; @@ -75,17 +75,10 @@ public class EventHandlerParameters extends AbstractParameters implements ApexPa * Constructor to create an event handler parameters instance. */ public EventHandlerParameters() { - super(EventHandlerParameters.class.getCanonicalName()); - } + super(); - /** - * Constructor to create an event handler parameters instance with the name of a sub class of - * this class. - * - * @param parameterClassName the class name of a sub class of this class - */ - public EventHandlerParameters(final String parameterClassName) { - super(parameterClassName); + // Set the name for the parameters + this.name = ApexParameterConstants.EVENT_HANDLER_GROUP_NAME; } /** @@ -151,7 +144,6 @@ public class EventHandlerParameters extends AbstractParameters implements ApexPa this.eventProtocolParameters = eventProtocolParameters; } - /** * Checks if the event handler is in the given peered mode. * @@ -320,30 +312,33 @@ public class EventHandlerParameters extends AbstractParameters implements ApexPa * @see org.onap.policy.apex.service.parameters.ApexParameterValidator#validate() */ @Override - public String validate() { - final StringBuilder errorMessageBuilder = new StringBuilder(); + public GroupValidationResult validate() { + final GroupValidationResult result = new GroupValidationResult(this); if (eventProtocolParameters == null) { - errorMessageBuilder.append(" event handler eventProtocolParameters not specified or blank\n"); + result.setResult("eventProtocolParameters", ValidationStatus.INVALID, + "event handler eventProtocolParameters not specified or blank"); } else { - errorMessageBuilder.append(eventProtocolParameters.validate()); + result.setResult("eventProtocolParameters", eventProtocolParameters.validate()); } if (carrierTechnologyParameters == null) { - errorMessageBuilder.append(" event handler carrierTechnologyParameters not specified or blank\n"); + result.setResult("carrierTechnologyParameters", ValidationStatus.INVALID, + "event handler carrierTechnologyParameters not specified or blank"); } else { - errorMessageBuilder.append(carrierTechnologyParameters.validate()); + result.setResult("carrierTechnologyParameters", carrierTechnologyParameters.validate()); } if (eventNameFilter != null) { try { Pattern.compile(eventNameFilter); } catch (final PatternSyntaxException pse) { - errorMessageBuilder.append(" event handler eventNameFilter is not a valid regular expression: " - + pse.getMessage() + "\n"); + result.setResult("eventNameFilter", ValidationStatus.INVALID, + "event handler eventNameFilter is not a valid regular expression: " + pse.getMessage()); } } - return errorMessageBuilder.toString(); + + return result; } /* @@ -354,9 +349,10 @@ public class EventHandlerParameters extends AbstractParameters implements ApexPa @Override public String toString() { return "EventHandlerParameters [name=" + name + ", carrierTechnologyParameters=" + carrierTechnologyParameters - + ", eventProtocolParameters=" + eventProtocolParameters + ", synchronousMode=" + synchronousMode - + ", synchronousPeer=" + synchronousPeer + ", synchronousTimeout=" + synchronousTimeout - + ", requestorMode=" + requestorMode + ", requestorPeer=" + requestorPeer + ", requestorTimeout=" - + requestorTimeout + ", eventName=" + eventName + ", eventNameFilter=" + eventNameFilter + "]"; + + ", eventProtocolParameters=" + eventProtocolParameters + ", synchronousMode=" + + synchronousMode + ", synchronousPeer=" + synchronousPeer + ", synchronousTimeout=" + + synchronousTimeout + ", requestorMode=" + requestorMode + ", requestorPeer=" + requestorPeer + + ", requestorTimeout=" + requestorTimeout + ", eventName=" + eventName + ", eventNameFilter=" + + eventNameFilter + "]"; } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParameters.java index 66b5c0aae..06b5e41f5 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParameters.java @@ -20,23 +20,26 @@ package org.onap.policy.apex.service.parameters.eventprotocol; -import org.onap.policy.apex.model.basicmodel.service.AbstractParameters; -import org.onap.policy.apex.service.parameters.ApexParameterValidator; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ParameterRuntimeException; +import org.onap.policy.common.parameters.ValidationStatus; /** - * A default event protocol parameter class that may be specialized by event protocol plugins that - * require plugin specific parameters. + * A default event protocol parameter class that may be specialized by event protocol plugins that require plugin + * specific parameters. * - * <p>The following parameters are defined: + * <p> + * The following parameters are defined: * <ol> * <li>label: The label of the event protocol technology. - * <li>eventProducerPluginClass: The name of the plugin class that will be used by Apex to produce - * and emit output events for this carrier technology + * <li>eventProducerPluginClass: The name of the plugin class that will be used by Apex to produce and emit output + * events for this carrier technology * </ol> * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public abstract class EventProtocolParameters extends AbstractParameters implements ApexParameterValidator { +public abstract class EventProtocolParameters implements ParameterGroup { // The event protocol label private String label = null; @@ -44,13 +47,13 @@ public abstract class EventProtocolParameters extends AbstractParameters impleme private String eventProtocolPluginClass; /** - * Constructor to create an event protocol parameters instance with the name of a sub class of - * this class and register the instance with the parameter service. + * Constructor to create an event protocol parameters instance with the name of a sub class of this class and + * register the instance with the parameter service. * * @param parameterClassName the class name of a sub class of this class */ public EventProtocolParameters(final String parameterClassName) { - super(parameterClassName); + super(); } /** @@ -97,7 +100,7 @@ public abstract class EventProtocolParameters extends AbstractParameters impleme @Override public String toString() { return "CarrierTechnologyParameters [label=" + label + ", EventProtocolPluginClass=" + eventProtocolPluginClass - + "]"; + + "]"; } /* @@ -106,17 +109,28 @@ public abstract class EventProtocolParameters extends AbstractParameters impleme * @see org.onap.policy.apex.service.parameters.ApexParameterValidator#validate() */ @Override - public String validate() { - final StringBuilder errorMessageBuilder = new StringBuilder(); + public GroupValidationResult validate() { + final GroupValidationResult result = new GroupValidationResult(this); if (label == null || label.length() == 0) { - errorMessageBuilder.append(" event protocol label not specified or is blank\n"); + result.setResult("label", ValidationStatus.INVALID, "event protocol label not specified or is blank"); } if (eventProtocolPluginClass == null || eventProtocolPluginClass.length() == 0) { - errorMessageBuilder.append(" event protocol eventProtocolPluginClass not specified or is blank\n"); + result.setResult("eventProtocolPluginClass", ValidationStatus.INVALID, + "event protocol eventProtocolPluginClass not specified or is blank"); } - return errorMessageBuilder.toString(); + return result; + } + + @Override + public String getName() { + return this.getLabel(); + } + + @Override + public void setName(final String name) { + throw new ParameterRuntimeException("the name/label of this event protocol is always \"" + getLabel() + "\""); } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java index 9d087bf31..2f09e0a65 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java @@ -26,7 +26,7 @@ import java.util.Map; import org.onap.policy.apex.service.engine.event.impl.apexprotocolplugin.ApexEventProtocolParameters; import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JSONEventProtocolParameters; -import org.onap.policy.apex.service.parameters.ApexParameterRuntimeException; +import org.onap.policy.common.parameters.ParameterRuntimeException; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; @@ -34,7 +34,6 @@ import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; @@ -55,11 +54,11 @@ public class EventProtocolParametersJSONAdapter private static final String EVENT_PROTOCOL_PARAMETERS = "parameters"; // Built in event protocol parameters - private static final Map<String, String> BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP = new HashMap<>(); + private static final Map<String, String> BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP = new HashMap<>(); static { - BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP.put("JSON", JSONEventProtocolParameters.class.getCanonicalName()); - BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP.put("APEX", ApexEventProtocolParameters.class.getCanonicalName()); + BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.put("JSON", JSONEventProtocolParameters.class.getCanonicalName()); + BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.put("APEX", ApexEventProtocolParameters.class.getCanonicalName()); } /* @@ -73,7 +72,7 @@ public class EventProtocolParametersJSONAdapter final JsonSerializationContext context) { final String returnMessage = "serialization of Apex event protocol parameters to Json is not supported"; LOGGER.error(returnMessage); - throw new ApexParameterRuntimeException(returnMessage); + throw new ParameterRuntimeException(returnMessage); } /* @@ -84,7 +83,7 @@ public class EventProtocolParametersJSONAdapter */ @Override public EventProtocolParameters deserialize(final JsonElement json, final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { + final JsonDeserializationContext context) { final JsonObject jsonObject = json.getAsJsonObject(); // Get the event protocol label primitive @@ -102,7 +101,7 @@ public class EventProtocolParametersJSONAdapter final String errorMessage = "event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" value \"" + labelJsonPrimitive.getAsString() + "\" invalid in JSON file"; LOGGER.warn(errorMessage); - throw new ApexParameterRuntimeException(errorMessage); + throw new ParameterRuntimeException(errorMessage); } // We now get the event protocol parameter class @@ -114,7 +113,7 @@ public class EventProtocolParametersJSONAdapter // If no event protocol parameter class was specified, we use the default if (classNameJsonPrimitive == null) { - eventProtocolParameterClassName = BUILT_IN_EVENT_RPOTOCOL_PARMETER_CLASS_MAP.get(eventProtocolLabel); + eventProtocolParameterClassName = BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.get(eventProtocolLabel); } else { // We use the specified one eventProtocolParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", ""); @@ -127,7 +126,7 @@ public class EventProtocolParametersJSONAdapter + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null") + "\" invalid in JSON file"; LOGGER.warn(errorMessage); - throw new ApexParameterRuntimeException(errorMessage); + throw new ParameterRuntimeException(errorMessage); } // Get the class for the event protocol @@ -139,7 +138,7 @@ public class EventProtocolParametersJSONAdapter "event protocol \"" + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + "\" value \"" + eventProtocolParameterClassName + "\", could not find class"; LOGGER.warn(errorMessage, e); - throw new ApexParameterRuntimeException(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); } // Deserialise the class @@ -154,7 +153,7 @@ public class EventProtocolParametersJSONAdapter final String errorMessage = "could not create default parameters for event protocol \"" + eventProtocolLabel + "\"\n" + e.getMessage(); LOGGER.warn(errorMessage, e); - throw new ApexParameterRuntimeException(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); } } @@ -166,7 +165,7 @@ public class EventProtocolParametersJSONAdapter + "\", specify correct event protocol parameter plugin in parameter \"" + PARAMETER_CLASS_NAME + "\""; LOGGER.warn(errorMessage); - throw new ApexParameterRuntimeException(errorMessage); + throw new ParameterRuntimeException(errorMessage); } return eventProtocolParameters; diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextCharDelimitedParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextCharDelimitedParameters.java index 7094a3d3f..d10d81ce2 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextCharDelimitedParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextCharDelimitedParameters.java @@ -20,13 +20,15 @@ package org.onap.policy.apex.service.parameters.eventprotocol; -import org.onap.policy.apex.service.parameters.ApexParameterValidator; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; /** - * An event protocol parameter class for character delimited textual event protocols that may be - * specialized by event protocol plugins that require plugin specific parameters. + * An event protocol parameter class for character delimited textual event protocols that may be specialized by event + * protocol plugins that require plugin specific parameters. * - * <p>The following parameters are defined: + * <p> + * The following parameters are defined: * <ol> * <li>startChar: starting character delimiter for text blocks containing an event. * <li>endChar: ending character delimiter for text blocks containing an event. @@ -34,15 +36,13 @@ import org.onap.policy.apex.service.parameters.ApexParameterValidator; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public abstract class EventProtocolTextCharDelimitedParameters extends EventProtocolParameters - implements ApexParameterValidator { +public abstract class EventProtocolTextCharDelimitedParameters extends EventProtocolParameters { // The starting and ending character delimiter private char startChar = '\0'; private char endChar = '\0'; /** - * Constructor to create an event protocol parameters instance with the name of a sub class of - * this class. + * Constructor to create an event protocol parameters instance with the name of a sub class of this class. * * @param parameterClassName the class name of a sub class of this class */ @@ -94,7 +94,7 @@ public abstract class EventProtocolTextCharDelimitedParameters extends EventProt @Override public String toString() { return "EventProtocolTextCharDelimitedParameters {" + super.toString() + "} [startChar=" + startChar - + ", endChar=" + endChar + "]"; + + ", endChar=" + endChar + "]"; } /* @@ -103,19 +103,19 @@ public abstract class EventProtocolTextCharDelimitedParameters extends EventProt * @see org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters#validate() */ @Override - public String validate() { - final StringBuilder errorMessageBuilder = new StringBuilder(); - - errorMessageBuilder.append(super.validate()); + public GroupValidationResult validate() { + final GroupValidationResult result = super.validate(); if (startChar == '\0') { - errorMessageBuilder.append(" text character delimited start character has not been specified\n"); + result.setResult("startChar", ValidationStatus.INVALID, + "text character delimited start character has not been specified"); } if (endChar == '\0') { - errorMessageBuilder.append(" text character delimited end character has not been specified\n"); + result.setResult("endChar", ValidationStatus.INVALID, + "text character delimited end character has not been specified\n"); } - return errorMessageBuilder.toString(); + return result; } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextTokenDelimitedParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextTokenDelimitedParameters.java index f71ebc6d8..dce2ee2c3 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextTokenDelimitedParameters.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolTextTokenDelimitedParameters.java @@ -20,7 +20,8 @@ package org.onap.policy.apex.service.parameters.eventprotocol; -import org.onap.policy.apex.service.parameters.ApexParameterValidator; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; /** * An event protocol parameter class for token delimited textual event protocols that may be specialized by event @@ -38,8 +39,7 @@ import org.onap.policy.apex.service.parameters.ApexParameterValidator; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public abstract class EventProtocolTextTokenDelimitedParameters extends EventProtocolParameters - implements ApexParameterValidator { +public abstract class EventProtocolTextTokenDelimitedParameters extends EventProtocolParameters { // The delimiter token for text blocks private String startDelimiterToken = null; private String endDelimiterToken = null; @@ -124,15 +124,14 @@ public abstract class EventProtocolTextTokenDelimitedParameters extends EventPro * @see org.onap.policy.apex.service.parameters.ApexParameterValidator#validate() */ @Override - public String validate() { - final StringBuilder errorMessageBuilder = new StringBuilder(); - - errorMessageBuilder.append(super.validate()); + public GroupValidationResult validate() { + final GroupValidationResult result = super.validate(); if (startDelimiterToken == null || startDelimiterToken.length() == 0) { - errorMessageBuilder.append(" text start delimiter token not specified or is blank\n"); + result.setResult("startDelimiterToken", ValidationStatus.INVALID, + "text start delimiter token not specified or is blank\n"); } - return errorMessageBuilder.toString(); + return result; } } |