From 4cfa2e2d98f6877d54da304ef17f096284430908 Mon Sep 17 00:00:00 2001 From: liamfallon Date: Thu, 13 Sep 2018 15:25:32 +0100 Subject: Sonar/Checkstyle in service/plugins Sonar and Checkstyle changes in plugins and services, and knock on changes Issue-ID: POLICY-1034 Change-Id: Iff7df74e54fce2c661dcc2fae75ae93d4cacfe5b Signed-off-by: liamfallon --- .../engine/engdep/EngDepMessageListener.java | 96 +++-- .../engine/engdep/EngDepMessagingService.java | 7 +- .../apex/service/engine/event/ApexEvent.java | 42 +- .../engine/event/ApexPeriodicEventGenerator.java | 8 +- .../engine/event/SynchronousEventCache.java | 41 +- .../engine/event/impl/EventConsumerFactory.java | 5 - .../engine/event/impl/EventProducerFactory.java | 5 - .../impl/enevent/ApexEvent2EnEventConverter.java | 19 +- .../FILECarrierTechnologyParameters.java | 217 ---------- .../FileCarrierTechnologyParameters.java | 212 ++++++++++ .../consumer/ApexFileEventConsumer.java | 61 +-- .../CharacterDelimitedTextBlockReader.java | 35 +- .../consumer/HeaderDelimitedTextBlockReader.java | 2 +- .../producer/ApexFileEventProducer.java | 10 +- .../Apex2JSONEventConverter.java | 438 -------------------- .../Apex2JsonEventConverter.java | 440 +++++++++++++++++++++ .../JSONEventProtocolParameters.java | 187 --------- .../JsonEventProtocolParameters.java | 187 +++++++++ .../engine/main/ApexCommandLineArguments.java | 23 +- .../service/engine/main/ApexEventMarshaller.java | 8 +- .../service/engine/main/ApexEventUnmarshaller.java | 60 ++- .../policy/apex/service/engine/main/ApexMain.java | 8 - .../apex/service/engine/runtime/EngineService.java | 2 +- .../engine/runtime/impl/EngineServiceImpl.java | 166 ++++---- .../service/engine/runtime/impl/EngineWorker.java | 74 ++-- .../service/parameters/ApexParameterHandler.java | 35 +- .../apex/service/parameters/ApexParameters.java | 42 +- .../CarrierTechnologyParameters.java | 15 +- .../CarrierTechnologyParametersJSONAdapter.java | 177 --------- .../CarrierTechnologyParametersJsonAdapter.java | 184 +++++++++ .../engineservice/EngineServiceParameters.java | 11 +- .../EngineServiceParametersJSONAdapter.java | 283 ------------- .../EngineServiceParametersJsonAdapter.java | 283 +++++++++++++ .../eventhandler/EventHandlerParameters.java | 43 +- .../EventProtocolParametersJSONAdapter.java | 173 -------- .../EventProtocolParametersJsonAdapter.java | 177 +++++++++ 36 files changed, 1893 insertions(+), 1883 deletions(-) delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FILECarrierTechnologyParameters.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FileCarrierTechnologyParameters.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JSONEventConverter.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JsonEventConverter.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JSONEventProtocolParameters.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JsonEventProtocolParameters.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJSONAdapter.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJsonAdapter.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJSONAdapter.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJsonAdapter.java delete mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java create mode 100644 services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJsonAdapter.java (limited to 'services/services-engine/src/main') diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessageListener.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessageListener.java index 3840e915d..a9b862d41 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessageListener.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessageListener.java @@ -20,6 +20,8 @@ package org.onap.policy.apex.service.engine.engdep; +import com.google.common.eventbus.Subscribe; + import java.util.Collection; import java.util.List; import java.util.concurrent.BlockingQueue; @@ -50,17 +52,14 @@ import org.onap.policy.apex.service.engine.runtime.EngineService; import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; -import com.google.common.eventbus.Subscribe; - /** - * The listener interface for receiving engDepMessage events. The class that is interested in - * processing a engDepMessage event implements this interface, and the object created with that - * class is registered with a component using the component's addEngDepMessageListener - * method. When the engDepMessage event occurs, that object's appropriate method is invoked. + * The listener interface for receiving engDepMessage events. The class that is interested in processing a engDepMessage + * event implements this interface, and the object created with that class is registered with a component using the + * component's addEngDepMessageListener method. When the engDepMessage event occurs, that object's + * appropriate method is invoked. * - *

This class uses a queue to buffer incoming messages. When the listener is called, it places the - * incoming message on the queue. A thread runs which removes the messages from the queue and - * forwards them to the Apex engine. + *

This class uses a queue to buffer incoming messages. When the listener is called, it places the incoming message + * on the queue. A thread runs which removes the messages from the queue and forwards them to the Apex engine. * * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com) */ @@ -83,9 +82,8 @@ public class EngDepMessageListener implements MessageListener, Runnable private final BlockingQueue> messageQueue = new LinkedBlockingDeque<>(); /** - * Instantiates a new EngDep message listener for listening for messages coming in from the - * Deployment client. The apexService is the Apex service to send the messages - * onto. + * Instantiates a new EngDep message listener for listening for messages coming in from the Deployment client. The + * apexService is the Apex service to send the messages onto. * * @param apexService the Apex engine service */ @@ -94,8 +92,8 @@ public class EngDepMessageListener implements MessageListener, Runnable } /** - * This method is an implementation of the message listener. It receives a message and places it - * on the queue for processing by the message listening thread. + * This method is an implementation of the message listener. It receives a message and places it on the queue for + * processing by the message listening thread. * * @param data the data * @see org.onap.policy.apex.core.infrastructure.messaging.MessageListener#onMessage @@ -106,8 +104,8 @@ public class EngDepMessageListener implements MessageListener, Runnable public void onMessage(final MessageBlock data) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("message received from client application {} port {}", - data.getConnection().getRemoteSocketAddress().getAddress(), - data.getConnection().getRemoteSocketAddress().getPort()); + data.getConnection().getRemoteSocketAddress().getAddress(), + data.getConnection().getRemoteSocketAddress().getPort()); } messageQueue.add(data); } @@ -115,8 +113,7 @@ public class EngDepMessageListener implements MessageListener, Runnable /* * (non-Javadoc) * - * @see org.onap.policy.apex.core.infrastructure.messaging.MessageListener#onMessage(java.lang. - * String) + * @see org.onap.policy.apex.core.infrastructure.messaging.MessageListener#onMessage(java.lang. String) */ @Override public void onMessage(final String messageString) { @@ -148,8 +145,7 @@ public class EngDepMessageListener implements MessageListener, Runnable } /** - * Runs the message listening thread. Here, the messages come in on the message queue and are - * processed one by one + * Runs the message listening thread. Here, the messages come in on the message queue and are processed one by one */ @Override public void run() { @@ -173,8 +169,8 @@ public class EngDepMessageListener implements MessageListener, Runnable } /** - * This method handles EngDep messages as they come in. It uses the inevitable switch statement - * to handle the messages. + * This method handles EngDep messages as they come in. It uses the inevitable switch statement to handle the + * messages. * * @param message the incoming EngDep message * @param webSocket the web socket on which the message came in @@ -195,7 +191,7 @@ public class EngDepMessageListener implements MessageListener, Runnable enDepAction = (EngDepAction) message.getAction(); } else { throw new ApexException(message.getAction().getClass().getName() - + "action on received message invalid, action must be of type \"EnDepAction\""); + + "action on received message invalid, action must be of type \"EnDepAction\""); } // Handle each incoming message using the inevitable switch statement for the EngDep @@ -204,12 +200,12 @@ public class EngDepMessageListener implements MessageListener, Runnable case GET_ENGINE_SERVICE_INFO: final GetEngineServiceInfo engineServiceInformationMessage = (GetEngineServiceInfo) message; LOGGER.debug("getting engine service information for engine service " + apexService.getKey().getId() - + " . . ."); + + " . . ."); // Send a reply with the engine service information sendServiceInfoReply(webSocket, engineServiceInformationMessage, apexService.getKey(), - apexService.getEngineKeys(), apexService.getApexModelKey()); - LOGGER.debug( - "returned engine service information for engine service " + apexService.getKey().getId()); + apexService.getEngineKeys(), apexService.getApexModelKey()); + LOGGER.debug("returned engine service information for engine service " + + apexService.getKey().getId()); break; case UPDATE_MODEL: @@ -217,10 +213,10 @@ public class EngDepMessageListener implements MessageListener, Runnable LOGGER.debug("updating model in engine {} . . .", updateModelMessage.getTarget().getId()); // Update the model apexService.updateModel(updateModelMessage.getTarget(), updateModelMessage.getMessageData(), - updateModelMessage.isForceInstall()); + updateModelMessage.isForceInstall()); // Send a reply indicating the message action worked sendReply(webSocket, updateModelMessage, true, - "updated model in engine " + updateModelMessage.getTarget().getId()); + "updated model in engine " + updateModelMessage.getTarget().getId()); LOGGER.debug("updated model in engine service {}", updateModelMessage.getTarget().getId()); break; @@ -231,7 +227,7 @@ public class EngDepMessageListener implements MessageListener, Runnable apexService.start(startEngineMessage.getTarget()); // Send a reply indicating the message action worked sendReply(webSocket, startEngineMessage, true, - "started engine " + startEngineMessage.getTarget().getId()); + "started engine " + startEngineMessage.getTarget().getId()); LOGGER.debug("started engine {}", startEngineMessage.getTarget().getId()); break; @@ -242,33 +238,33 @@ public class EngDepMessageListener implements MessageListener, Runnable apexService.stop(stopEngineMessage.getTarget()); // Send a reply indicating the message action worked sendReply(webSocket, stopEngineMessage, true, - "stopped engine " + stopEngineMessage.getTarget().getId()); + "stopped engine " + stopEngineMessage.getTarget().getId()); LOGGER.debug("stopping engine {}", stopEngineMessage.getTarget().getId()); break; case START_PERIODIC_EVENTS: final StartPeriodicEvents startPeriodicEventsMessage = (StartPeriodicEvents) message; LOGGER.debug("starting periodic events on engine {} . . .", - startPeriodicEventsMessage.getTarget().getId()); + startPeriodicEventsMessage.getTarget().getId()); // Start periodic events with the period specified in the message final Long period = Long.parseLong(startPeriodicEventsMessage.getMessageData()); apexService.startPeriodicEvents(period); // Send a reply indicating the message action worked - sendReply(webSocket, startPeriodicEventsMessage, true, "started periodic events on engine " - + startPeriodicEventsMessage.getTarget().getId() + " with period " + period); - LOGGER.debug("started periodic events on engine " + startPeriodicEventsMessage.getTarget().getId() - + " with period " + period); + String periodicStartedMessage = "started periodic events on engine " + + startPeriodicEventsMessage.getTarget().getId() + " with period " + period; + sendReply(webSocket, startPeriodicEventsMessage, true, periodicStartedMessage); + LOGGER.debug(periodicStartedMessage); break; case STOP_PERIODIC_EVENTS: final StopPeriodicEvents stopPeriodicEventsMessage = (StopPeriodicEvents) message; LOGGER.debug("stopping periodic events on engine {} . . .", - stopPeriodicEventsMessage.getTarget().getId()); + stopPeriodicEventsMessage.getTarget().getId()); // Stop periodic events apexService.stopPeriodicEvents(); // Send a reply indicating the message action worked - sendReply(webSocket, stopPeriodicEventsMessage, true, - "stopped periodic events on engine " + stopPeriodicEventsMessage.getTarget().getId()); + sendReply(webSocket, stopPeriodicEventsMessage, true, "stopped periodic events on engine " + + stopPeriodicEventsMessage.getTarget().getId()); LOGGER.debug("stopped periodic events on engine " + stopPeriodicEventsMessage.getTarget().getId()); break; @@ -277,7 +273,7 @@ public class EngDepMessageListener implements MessageListener, Runnable LOGGER.debug("getting status for engine{} . . .", getEngineStatusMessage.getTarget().getId()); // Send a reply with the engine status sendReply(webSocket, getEngineStatusMessage, true, - apexService.getStatus(getEngineStatusMessage.getTarget())); + apexService.getStatus(getEngineStatusMessage.getTarget())); LOGGER.debug("returned status for engine {}", getEngineStatusMessage.getTarget().getId()); break; @@ -313,7 +309,7 @@ public class EngDepMessageListener implements MessageListener, Runnable * @param messageData the message data */ private void sendReply(final WebSocket client, final Message requestMessage, final boolean result, - final String messageData) { + final String messageData) { LOGGER.entry(result, messageData); if (client == null || !client.isOpen()) { @@ -321,8 +317,9 @@ public class EngDepMessageListener implements MessageListener, Runnable return; } - LOGGER.debug("sending {} to web socket {}", requestMessage.getAction(), - client.getRemoteSocketAddress().toString()); + String replyString = "sending " + requestMessage.getAction() + " to web socket " + + client.getRemoteSocketAddress().toString(); + LOGGER.debug(replyString); final Response responseMessage = new Response(requestMessage.getTarget(), result, requestMessage); responseMessage.setMessageData(messageData); @@ -344,14 +341,15 @@ public class EngDepMessageListener implements MessageListener, Runnable * @param apexModelKey the apex model key */ private void sendServiceInfoReply(final WebSocket client, final Message requestMessage, - final AxArtifactKey engineServiceKey, final Collection engineKeyCollection, - final AxArtifactKey apexModelKey) { + final AxArtifactKey engineServiceKey, final Collection engineKeyCollection, + final AxArtifactKey apexModelKey) { LOGGER.entry(); - LOGGER.debug("sending {} to web socket {}", requestMessage.getAction(), - client.getRemoteSocketAddress().toString()); + String sendingMessage = "sending " + requestMessage.getAction() + " to web socket " + + client.getRemoteSocketAddress().toString(); + LOGGER.debug(sendingMessage); - final EngineServiceInfoResponse responseMessage = - new EngineServiceInfoResponse(requestMessage.getTarget(), true, requestMessage); + final EngineServiceInfoResponse responseMessage = new EngineServiceInfoResponse(requestMessage.getTarget(), + true, requestMessage); responseMessage.setMessageData("engine service information"); responseMessage.setEngineServiceKey(engineServiceKey); responseMessage.setEngineKeyArray(engineKeyCollection); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessagingService.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessagingService.java index 86589ac81..7ebcad830 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessagingService.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/engdep/EngDepMessagingService.java @@ -22,14 +22,13 @@ package org.onap.policy.apex.service.engine.engdep; import java.net.InetSocketAddress; -import org.onap.policy.apex.service.engine.runtime.EngineService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - import org.onap.policy.apex.core.infrastructure.messaging.MessagingService; import org.onap.policy.apex.core.infrastructure.messaging.MessagingServiceFactory; import org.onap.policy.apex.core.infrastructure.messaging.util.MessagingUtils; import org.onap.policy.apex.core.protocols.Message; +import org.onap.policy.apex.service.engine.runtime.EngineService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; /** * The Class EngDepMessagingService is used to encapsulate the server side of EngDep communication. diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java index 38762ea97..8c7911bce 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexEvent.java @@ -37,6 +37,9 @@ import org.slf4j.ext.XLoggerFactory; * @author Liam Fallon (liam.fallon@ericsson.com) */ public class ApexEvent extends HashMap implements Serializable { + // Recurring string constants + private static final String EVENT_PREAMBLE = "event \""; + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexEvent.class); private static final long serialVersionUID = -4451918242101961685L; @@ -111,7 +114,7 @@ public class ApexEvent extends HashMap implements Serializable { // An identifier for the current event execution. The default value here will always be unique // in a single JVM - private long executionID = ApexEvent.getNextExecutionID(); + private long executionId = ApexEvent.getNextExecutionId(); // A string holding a message that indicates why processing of this event threw an exception private String exceptionMessage; @@ -122,7 +125,7 @@ public class ApexEvent extends HashMap implements Serializable { * * @return the next candidate value for a Execution ID */ - private static synchronized long getNextExecutionID() { + private static synchronized long getNextExecutionId() { return nextExecutionID.getAndIncrement(); } @@ -139,11 +142,11 @@ public class ApexEvent extends HashMap implements Serializable { public ApexEvent(final String name, final String version, final String nameSpace, final String source, final String target) throws ApexEventException { // @formatter:off - this.name = validateField("name", name, NAME_REGEXP); - this.version = validateField("version", version, VERSION_REGEXP); - this.nameSpace = validateField("nameSpace", nameSpace, NAMESPACE_REGEXP); - this.source = validateField("source", source, SOURCE_REGEXP); - this.target = validateField("target", target, TARGET_REGEXP); + this.name = validateField(NAME_HEADER_FIELD, name, NAME_REGEXP); + this.version = validateField(VERSION_HEADER_FIELD, version, VERSION_REGEXP); + this.nameSpace = validateField(NAMESPACE_HEADER_FIELD, nameSpace, NAMESPACE_REGEXP); + this.source = validateField(SOURCE_HEADER_FIELD, source, SOURCE_REGEXP); + this.target = validateField(TARGET_HEADER_FIELD, target, TARGET_REGEXP); // @formatter:on } @@ -161,10 +164,10 @@ public class ApexEvent extends HashMap implements Serializable { if (fieldValue.matches(fieldRegexp)) { return fieldValue; } else { - LOGGER.warn("event \"" + name + ": field \"" + fieldName + "=" + fieldValue - + "\" is illegal. It doesn't match regex '" + fieldRegexp + "'"); - throw new ApexEventException( - "event \"" + name + ": field \"" + fieldName + "=" + fieldValue + "\" is illegal"); + String message = EVENT_PREAMBLE + name + ": field \"" + fieldName + "=" + fieldValue + + "\" is illegal. It doesn't match regex '" + fieldRegexp + "'"; + LOGGER.warn(message); + throw new ApexEventException(message); } } @@ -179,8 +182,9 @@ public class ApexEvent extends HashMap implements Serializable { if (key.matches(AxReferenceKey.LOCAL_NAME_REGEXP)) { return key; } else { - LOGGER.warn("event \"" + name + ": key \"" + key + "\" is illegal"); - throw new ApexEventException("event \"" + name + ": key \"" + key + "\" is illegal"); + String message = EVENT_PREAMBLE + name + ": key \"" + key + "\" is illegal"; + LOGGER.warn(message); + throw new ApexEventException(message); } } @@ -234,8 +238,8 @@ public class ApexEvent extends HashMap implements Serializable { * * @return the executionID */ - public long getExecutionID() { - return executionID; + public long getExecutionId() { + return executionId; } /** @@ -243,10 +247,10 @@ public class ApexEvent extends HashMap implements Serializable { * unique in the current JVM. For some applications/deployments this executionID may need to * globally unique * - * @param executionID the executionID + * @param executionId the executionID */ - public void setExecutionID(final long executionID) { - this.executionID = executionID; + public void setExecutionId(final long executionId) { + this.executionId = executionId; } /** @@ -330,7 +334,7 @@ public class ApexEvent extends HashMap implements Serializable { builder.append(",target="); builder.append(target); builder.append(",executionID="); - builder.append(executionID); + builder.append(executionId); builder.append(",exceptionMessage="); builder.append(exceptionMessage); builder.append(","); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java index b34d5185c..32f87a7cc 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGenerator.java @@ -86,7 +86,7 @@ public class ApexPeriodicEventGenerator extends TimerTask { private final EngineServiceEventInterface engineServiceEventInterface; // Timing information - private long period = 0; + private long eventGeneratorPeriod = 0; private long firstEventTime = 0; private long lastEventTime = 0; private long eventCount = 0; @@ -102,7 +102,7 @@ public class ApexPeriodicEventGenerator extends TimerTask { final long period) { // Save the engine service reference and delay this.engineServiceEventInterface = engineServiceEventInterface; - this.period = period; + this.eventGeneratorPeriod = period; timer = new Timer(ApexPeriodicEventGenerator.class.getSimpleName(), true); timer.schedule(this, period, period); @@ -128,7 +128,7 @@ public class ApexPeriodicEventGenerator extends TimerTask { eventCount++; // Set the fields in the periodic event - periodicEventMap.put(PERIODIC_DELAY, period); + periodicEventMap.put(PERIODIC_DELAY, eventGeneratorPeriod); periodicEventMap.put(PERIODIC_FIRST_TIME, firstEventTime); periodicEventMap.put(PERIODIC_LAST_TIME, lastEventTime); periodicEventMap.put(PERIODIC_CURRENT_TIME, currentEventTime); @@ -170,7 +170,7 @@ public class ApexPeriodicEventGenerator extends TimerTask { */ @Override public String toString() { - return "ApexPeriodicEventGenerator [period=" + period + ", firstEventTime=" + firstEventTime + return "ApexPeriodicEventGenerator [period=" + eventGeneratorPeriod + ", firstEventTime=" + firstEventTime + ", lastEventTime=" + lastEventTime + ", eventCount=" + eventCount + "]"; } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/SynchronousEventCache.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/SynchronousEventCache.java index 1830fc0e5..5e48a5894 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/SynchronousEventCache.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/SynchronousEventCache.java @@ -33,9 +33,8 @@ import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /** - * This class holds a cache of the synchronous events sent into Apex and that have not yet been - * replied to. It runs a thread to time out events that have not been replied to in the specified - * timeout. + * This class holds a cache of the synchronous events sent into Apex and that have not yet been replied to. It runs a + * thread to time out events that have not been replied to in the specified timeout. * * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -55,11 +54,10 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { private long synchronousEventTimeout = DEFAULT_SYNCHRONOUS_EVENT_TIMEOUT; // Map holding outstanding synchronous events - private final Map> toApexEventMap = new HashMap>(); + private final Map> toApexEventMap = new HashMap<>(); // Map holding reply events - private final Map> fromApexEventMap = - new HashMap>(); + private final Map> fromApexEventMap = new HashMap<>(); // The message listener thread and stopping flag private final Thread synchronousEventCacheThread; @@ -71,11 +69,10 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { * @param peeredMode the peered mode for which to return the reference * @param consumer the consumer that is populating the cache * @param producer the producer that is emptying the cache - * @param synchronousEventTimeout the time in milliseconds to wait for the reply to a sent - * synchronous event + * @param synchronousEventTimeout the time in milliseconds to wait for the reply to a sent synchronous event */ public SynchronousEventCache(final EventHandlerPeeredMode peeredMode, final ApexEventConsumer consumer, - final ApexEventProducer producer, final long synchronousEventTimeout) { + final ApexEventProducer producer, final long synchronousEventTimeout) { super(peeredMode, consumer, producer); if (synchronousEventTimeout != 0) { @@ -211,7 +208,8 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { // Check if there are any unprocessed events if (!toApexEventMap.isEmpty()) { - LOGGER.warn(toApexEventMap.size() + " synchronous events dropped due to system shutdown"); + String message = toApexEventMap.size() + " synchronous events dropped due to system shutdown"; + LOGGER.warn(message); } toApexEventMap.clear(); @@ -226,7 +224,7 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { * @param event the event to cache */ private void cacheSynchronizedEvent(final Map> eventCacheMap, - final long executionId, final Object event) { + final long executionId, final Object event) { LOGGER.entry("Adding event with execution ID: " + executionId); // Check if the event is already in the cache @@ -234,7 +232,8 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { // If there was no sent event then the event timed out or some unexpected event was // received final String errorMessage = "an event with ID " + executionId - + " already exists in the synchronous event cache, execution IDs must be unique in the system"; + + " already exists in the synchronous event cache, " + + "execution IDs must be unique in the system"; LOGGER.warn(errorMessage); throw new ApexEventRuntimeException(errorMessage); } @@ -243,7 +242,8 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { eventCacheMap.put(executionId, new SimpleEntry(System.currentTimeMillis(), event)); if (LOGGER.isDebugEnabled()) { - LOGGER.debug("event has been cached:" + event); + String message = "event has been cached:" + event; + LOGGER.debug(message); } LOGGER.exit("Added: " + executionId); @@ -257,7 +257,7 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { * @return The removed event */ private Object removeCachedEventIfExists(final Map> eventCacheMap, - final long executionId) { + final long executionId) { LOGGER.entry("Removing: " + executionId); final SimpleEntry removedEventEntry = eventCacheMap.remove(executionId); @@ -273,8 +273,8 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { } /** - * Time out events on an event cache map. Events that have a timeout longer than the configured - * timeout are timed out. + * Time out events on an event cache map. Events that have a timeout longer than the configured timeout are timed + * out. * * @param eventCacheMap the event cache to operate on */ @@ -293,12 +293,13 @@ public class SynchronousEventCache extends PeeredReference implements Runnable { } // Remove timed out events from the map - for (final long timedoutEventExecutionID : timedOutEventSet) { + for (final long timedoutEventExecutionId : timedOutEventSet) { // Remove the map entry and issue a warning - final SimpleEntry timedOutEventEntry = eventCacheMap.remove(timedoutEventExecutionID); + final SimpleEntry timedOutEventEntry = eventCacheMap.remove(timedoutEventExecutionId); - LOGGER.warn("synchronous event timed out, reply not received in " + synchronousEventTimeout - + " milliseconds on event " + timedOutEventEntry.getValue()); + String message = "synchronous event timed out, reply not received in " + synchronousEventTimeout + + " milliseconds on event " + timedOutEventEntry.getValue(); + LOGGER.warn(message); } } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactory.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactory.java index 8f54c049b..5c44f2d7d 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactory.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactory.java @@ -36,11 +36,6 @@ public class EventConsumerFactory { // The logger for this class private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventConsumerFactory.class); - /** - * Empty constructor with no generic overloading. - */ - public EventConsumerFactory() {} - /** * Create an event consumer of the required type for the specified consumer technology. * diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactory.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactory.java index 9bbbad362..727f77995 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactory.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactory.java @@ -36,11 +36,6 @@ public class EventProducerFactory { // The logger for this class private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventProducerFactory.class); - /** - * Empty constructor with no generic overloading. - */ - public EventProducerFactory() {} - /** * Create an event producer of the required type for the specified producer technology. * diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverter.java index 34690cc7d..5fce2c89f 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverter.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverter.java @@ -23,19 +23,18 @@ package org.onap.policy.apex.service.engine.event.impl.enevent; import java.util.ArrayList; import java.util.List; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.event.ApexEventConverter; -import org.onap.policy.apex.service.engine.event.ApexEventException; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - import org.onap.policy.apex.core.engine.engine.ApexEngine; import org.onap.policy.apex.core.engine.event.EnEvent; import org.onap.policy.apex.model.basicmodel.concepts.ApexException; import org.onap.policy.apex.model.basicmodel.service.ModelService; import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.engine.event.ApexEventConverter; +import org.onap.policy.apex.service.engine.event.ApexEventException; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; /** * The Class ApexEvent2EnEventConverter converts externally facing {@link ApexEvent} instances to @@ -90,7 +89,7 @@ public final class ApexEvent2EnEventConverter implements ApexEventConverter { axEvent.getNameSpace(), axEvent.getSource(), axEvent.getTarget()); // Copy the ExecutionID from the EnEvent into the ApexEvent - apexEvent.setExecutionID(enEvent.getExecutionId()); + apexEvent.setExecutionId(enEvent.getExecutionId()); // Copy he exception message to the Apex event if it is set if (enEvent.getExceptionMessage() != null) { @@ -101,7 +100,7 @@ public final class ApexEvent2EnEventConverter implements ApexEventConverter { apexEvent.putAll(enEvent); // Return the event in a single element - final ArrayList eventList = new ArrayList(); + final ArrayList eventList = new ArrayList<>(); eventList.add(apexEvent); return eventList; } @@ -136,7 +135,7 @@ public final class ApexEvent2EnEventConverter implements ApexEventConverter { enEvent.putAll(apexEvent); // copy the ExecutionID from the ApexEvent into the EnEvent - enEvent.setExecutionId(apexEvent.getExecutionID()); + enEvent.setExecutionId(apexEvent.getExecutionId()); return enEvent; } 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 deleted file mode 100644 index 84d19fc62..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FILECarrierTechnologyParameters.java +++ /dev/null @@ -1,217 +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.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. - * - *

- * The following parameters are defined: - *

    - *
  1. fileName: The full path to the file from which to read events or to which to write events. - *
  2. 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 - *
  3. standardError: If this flag is set to true, then standard error is used to write events - *
  4. 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. - *
  5. startDelay: The amount of milliseconds to wait at startup startup before processing the first event. - *
- * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class FILECarrierTechnologyParameters extends CarrierTechnologyParameters { - // @formatter:off - /** The label of this carrier technology. */ - public static final String FILE_CARRIER_TECHNOLOGY_LABEL = "FILE"; - - /** The producer plugin class for the FILE carrier technology. */ - public static final String FILE_EVENT_PRODUCER_PLUGIN_CLASS = ApexFileEventProducer.class.getCanonicalName(); - - /** The consumer plugin class for the FILE carrier technology. */ - public static final String FILE_EVENT_CONSUMER_PLUGIN_CLASS = ApexFileEventConsumer.class.getCanonicalName(); - - private String fileName; - private boolean standardIO = false; - private boolean standardError = false; - private boolean streamingMode = false; - private long startDelay = 0; - // @formatter:on - - /** - * Constructor to create a file carrier technology parameters instance and register the instance with the parameter - * service. - */ - public FILECarrierTechnologyParameters() { - super(); - - // Set the carrier technology properties for the FILE carrier technology - this.setLabel(FILE_CARRIER_TECHNOLOGY_LABEL); - this.setEventProducerPluginClass(FILE_EVENT_PRODUCER_PLUGIN_CLASS); - this.setEventConsumerPluginClass(FILE_EVENT_CONSUMER_PLUGIN_CLASS); - } - - /** - * Gets the file name from which to read or to which to write events. - * - * @return the file name from which to read or to which to write events - */ - public String getFileName() { - return ResourceUtils.getFilePath4Resource(fileName); - } - - /** - * Checks if is standard IO should be used for input or output. - * - * @return true, if standard IO should be used for input or output - */ - public boolean isStandardIO() { - return standardIO; - } - - /** - * Checks if is standard error should be used for output. - * - * @return true, if standard error should be used for output - */ - public boolean isStandardError() { - return standardError; - } - - /** - * Checks if is streaming mode is on. - * - * @return true, if streaming mode is on - */ - public boolean isStreamingMode() { - return streamingMode; - } - - /** - * Sets the file name from which to read or to which to write events. - * - * @param fileName the file name from which to read or to which to write events - */ - public void setFileName(final String fileName) { - this.fileName = fileName; - } - - /** - * Sets if standard IO should be used for event input or output. - * - * @param standardIO if standard IO should be used for event input or output - */ - public void setStandardIO(final boolean standardIO) { - this.standardIO = standardIO; - } - - /** - * Sets if standard error should be used for event output. - * - * @param standardError if standard error should be used for event output - */ - public void setStandardError(final boolean standardError) { - this.standardError = standardError; - } - - /** - * Sets streaming mode. - * - * @param streamingMode the streaming mode value - */ - public void setStreamingMode(final boolean streamingMode) { - this.streamingMode = streamingMode; - } - - /** - * Gets the delay in milliseconds before the plugin starts processing. - * - * @return the delay - */ - public long getStartDelay() { - return startDelay; - } - - /** - * Sets the delay in milliseconds before the plugin starts processing. - * - * @param startDelay the delay - */ - public void setStartDelay(final long startDelay) { - this.startDelay = startDelay; - } - - /* - * (non-Javadoc) - * - * @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 + "]"; - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.common.parameters.ParameterGroup#getName() - */ - @Override - public String getName() { - return this.getLabel(); - } - - /* - * (non-Javadoc) - * - * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() - */ - @Override - public GroupValidationResult validate() { - final GroupValidationResult result = super.validate(); - - if (!standardIO && !standardError && (fileName == null || fileName.trim().length() == 0)) { - 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) { - streamingMode = true; - } - - if (startDelay < 0) { - result.setResult("startDelay", ValidationStatus.INVALID, - "startDelay must be zero or a positive number of milliseconds"); - } - - return result; - } -} 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 new file mode 100644 index 000000000..cbfe18016 --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FileCarrierTechnologyParameters.java @@ -0,0 +1,212 @@ +/*- + * ============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.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. + * + *

The following parameters are defined:

  1. fileName: The full path to the file from which to read events or to + * which to write events.
  2. 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
  3. standardError: If this + * flag is set to true, then standard error is used to write events
  4. 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.
  5. startDelay: + * The amount of milliseconds to wait at startup startup before processing the first event.
+ * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class FileCarrierTechnologyParameters extends CarrierTechnologyParameters { + // @formatter:off + /** The label of this carrier technology. */ + public static final String FILE_CARRIER_TECHNOLOGY_LABEL = "FILE"; + + /** The producer plugin class for the FILE carrier technology. */ + public static final String FILE_EVENT_PRODUCER_PLUGIN_CLASS = ApexFileEventProducer.class.getCanonicalName(); + + /** The consumer plugin class for the FILE carrier technology. */ + public static final String FILE_EVENT_CONSUMER_PLUGIN_CLASS = ApexFileEventConsumer.class.getCanonicalName(); + + private String fileName; + private boolean standardIo = false; + private boolean standardError = false; + private boolean streamingMode = false; + private long startDelay = 0; + // @formatter:on + + /** + * Constructor to create a file carrier technology parameters instance and register the instance with the parameter + * service. + */ + public FileCarrierTechnologyParameters() { + super(); + + // Set the carrier technology properties for the FILE carrier technology + this.setLabel(FILE_CARRIER_TECHNOLOGY_LABEL); + this.setEventProducerPluginClass(FILE_EVENT_PRODUCER_PLUGIN_CLASS); + this.setEventConsumerPluginClass(FILE_EVENT_CONSUMER_PLUGIN_CLASS); + } + + /** + * Gets the file name from which to read or to which to write events. + * + * @return the file name from which to read or to which to write events + */ + public String getFileName() { + return ResourceUtils.getFilePath4Resource(fileName); + } + + /** + * Checks if is standard IO should be used for input or output. + * + * @return true, if standard IO should be used for input or output + */ + public boolean isStandardIo() { + return standardIo; + } + + /** + * Checks if is standard error should be used for output. + * + * @return true, if standard error should be used for output + */ + public boolean isStandardError() { + return standardError; + } + + /** + * Checks if is streaming mode is on. + * + * @return true, if streaming mode is on + */ + public boolean isStreamingMode() { + return streamingMode; + } + + /** + * Sets the file name from which to read or to which to write events. + * + * @param fileName the file name from which to read or to which to write events + */ + public void setFileName(final String fileName) { + this.fileName = fileName; + } + + /** + * Sets if standard IO should be used for event input or output. + * + * @param standardIo if standard IO should be used for event input or output + */ + public void setStandardIo(final boolean standardIo) { + this.standardIo = standardIo; + } + + /** + * Sets if standard error should be used for event output. + * + * @param standardError if standard error should be used for event output + */ + public void setStandardError(final boolean standardError) { + this.standardError = standardError; + } + + /** + * Sets streaming mode. + * + * @param streamingMode the streaming mode value + */ + public void setStreamingMode(final boolean streamingMode) { + this.streamingMode = streamingMode; + } + + /** + * Gets the delay in milliseconds before the plugin starts processing. + * + * @return the delay + */ + public long getStartDelay() { + return startDelay; + } + + /** + * Sets the delay in milliseconds before the plugin starts processing. + * + * @param startDelay the delay + */ + public void setStartDelay(final long startDelay) { + this.startDelay = startDelay; + } + + /* + * (non-Javadoc) + * + * @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 + "]"; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.common.parameters.ParameterGroup#getName() + */ + @Override + public String getName() { + return this.getLabel(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.apps.uservice.parameters.ApexParameterValidator#validate() + */ + @Override + public GroupValidationResult validate() { + final GroupValidationResult result = super.validate(); + + if (!standardIo && !standardError && (fileName == null || fileName.trim().length() == 0)) { + 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) { + streamingMode = true; + } + + if (startDelay < 0) { + result.setResult("startDelay", ValidationStatus.INVALID, + "startDelay must be zero or a positive number of milliseconds"); + } + + return result; + } +} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java index 7521c3a08..0f0996fb8 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumer.java @@ -33,23 +33,25 @@ import org.onap.policy.apex.service.engine.event.ApexEventConsumer; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.ApexEventReceiver; import org.onap.policy.apex.service.engine.event.PeeredReference; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FILECarrierTechnologyParameters; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Concrete implementation an Apex event consumer that reads events from a file. This consumer also - * implements ApexEventProducer and therefore can be used as a synchronous consumer. + * Concrete implementation an Apex event consumer that reads events from a file. This consumer also implements + * ApexEventProducer and therefore can be used as a synchronous consumer. * * @author Liam Fallon (liam.fallon@ericsson.com) */ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { - // Get a reference to the logger private static final Logger LOGGER = LoggerFactory.getLogger(ApexFileEventConsumer.class); + // Recurring string constants + private static final String APEX_FILE_CONSUMER_PREAMBLE = "ApexFileConsumer \""; + // The input stream to read events from private InputStream eventInputStream; @@ -66,35 +68,34 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { private String consumerName = null; // The specific carrier technology parameters for this consumer - private FILECarrierTechnologyParameters fileCarrierTechnologyParameters; + private FileCarrierTechnologyParameters fileCarrierTechnologyParameters; // The peer references for this event handler - private final Map peerReferenceMap = - new EnumMap<>(EventHandlerPeeredMode.class); + private final Map peerReferenceMap = new EnumMap<>( + EventHandlerPeeredMode.class); // Holds the next identifier for event execution. private static AtomicLong nextExecutionID = new AtomicLong(0L); /** - * Private utility to get the next candidate value for a Execution ID. This value will always be - * unique in a single JVM + * Private utility to get the next candidate value for a Execution ID. This value will always be unique in a single + * JVM * * @return the next candidate value for a Execution ID */ - private static synchronized long getNextExecutionID() { + private static synchronized long getNextExecutionId() { return nextExecutionID.getAndIncrement(); } /* * (non-Javadoc) * - * @see - * org.onap.policy.apex.apps.uservice.consumer.ApexEventConsumer#init(org.onap.policy.apex.apps. + * @see org.onap.policy.apex.apps.uservice.consumer.ApexEventConsumer#init(org.onap.policy.apex.apps. * uservice.consumer.ApexEventReceiver) */ @Override public void init(final String name, final EventHandlerParameters consumerParameters, - final ApexEventReceiver incomingEventReceiver) throws ApexEventException { + final ApexEventReceiver incomingEventReceiver) throws ApexEventException { this.eventReceiver = incomingEventReceiver; this.consumerName = name; @@ -106,18 +107,18 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { } // Check and get the file Properties - if (!(consumerParameters.getCarrierTechnologyParameters() instanceof FILECarrierTechnologyParameters)) { + if (!(consumerParameters.getCarrierTechnologyParameters() instanceof FileCarrierTechnologyParameters)) { final String errorMessage = "specified consumer properties for ApexFileConsumer \"" + consumerName - + "\" are not applicable to a File consumer"; + + "\" are not applicable to a File consumer"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } - fileCarrierTechnologyParameters = - (FILECarrierTechnologyParameters) consumerParameters.getCarrierTechnologyParameters(); + fileCarrierTechnologyParameters = (FileCarrierTechnologyParameters) consumerParameters + .getCarrierTechnologyParameters(); // Open the file producing events try { - if (fileCarrierTechnologyParameters.isStandardIO()) { + if (fileCarrierTechnologyParameters.isStandardIo()) { eventInputStream = System.in; } else { eventInputStream = new FileInputStream(fileCarrierTechnologyParameters.getFileName()); @@ -125,10 +126,11 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { // Get an event composer for our event source textBlockReader = new TextBlockReaderFactory().getTaggedReader(eventInputStream, - consumerParameters.getEventProtocolParameters()); + consumerParameters.getEventProtocolParameters()); } catch (final IOException e) { - final String errorMessage = "ApexFileConsumer \"" + consumerName + "\" failed to open file for reading: \"" - + fileCarrierTechnologyParameters.getFileName() + "\""; + final String errorMessage = APEX_FILE_CONSUMER_PREAMBLE + consumerName + + "\" failed to open file for reading: \"" + fileCarrierTechnologyParameters.getFileName() + + "\""; LOGGER.warn(errorMessage, e); throw new ApexEventException(errorMessage, e); } @@ -195,7 +197,7 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { // Check that we have been initialized in async or sync mode if (eventReceiver == null) { LOGGER.warn("\"{}\" has not been initilaized for either asynchronous or synchronous event handling", - consumerName); + consumerName); return; } @@ -209,18 +211,19 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { // Process the event from the text block if there is one there if (textBlock.getText() != null) { - eventReceiver.receiveEvent(getNextExecutionID(), textBlock.getText()); + eventReceiver.receiveEvent(getNextExecutionId(), textBlock.getText()); } - } while (!textBlock.isEndOfText()); + } + while (!textBlock.isEndOfText()); } catch (final Exception e) { LOGGER.warn("\"" + consumerName + "\" failed to read event from file: \"" - + fileCarrierTechnologyParameters.getFileName() + "\"", e); + + fileCarrierTechnologyParameters.getFileName() + "\"", e); } finally { try { eventInputStream.close(); } catch (final IOException e) { - LOGGER.warn("ApexFileConsumer \"" + consumerName + "\" failed to close file: \"" - + fileCarrierTechnologyParameters.getFileName() + "\"", e); + LOGGER.warn(APEX_FILE_CONSUMER_PREAMBLE + consumerName + "\" failed to close file: \"" + + fileCarrierTechnologyParameters.getFileName() + "\"", e); } } @@ -236,8 +239,8 @@ public class ApexFileEventConsumer implements ApexEventConsumer, Runnable { try { eventInputStream.close(); } catch (final IOException e) { - LOGGER.warn("ApexFileConsumer \"" + consumerName + "\" failed to close file for reading: \"" - + fileCarrierTechnologyParameters.getFileName() + "\"", e); + LOGGER.warn(APEX_FILE_CONSUMER_PREAMBLE + consumerName + "\" failed to close file for reading: \"" + + fileCarrierTechnologyParameters.getFileName() + "\"", e); } if (consumerThread.isAlive() && !consumerThread.isInterrupted()) { diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/CharacterDelimitedTextBlockReader.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/CharacterDelimitedTextBlockReader.java index b286f8afe..bd7310d0a 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/CharacterDelimitedTextBlockReader.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/CharacterDelimitedTextBlockReader.java @@ -93,12 +93,29 @@ public class CharacterDelimitedTextBlockReader implements TextBlockReader { return new TextBlock(eofOnInputStream, null); } - // The initial nesting level of incoming text blocks is always zero - int nestingLevel = 0; + // Read the block of text + final StringBuilder textBlockBuilder = readTextBlockText(); + // Condition the text block and return it + final String textBlock = textBlockBuilder.toString().trim(); + if (textBlock.length() > 0) { + return new TextBlock(eofOnInputStream, textBlock); + } else { + return new TextBlock(eofOnInputStream, null); + } + } + + /** + * Read a block of text. + * @return A string builder containing the text + * @throws IOException on read errors + */ + private StringBuilder readTextBlockText() throws IOException { // Holder for the text block final StringBuilder textBlockBuilder = new StringBuilder(); + int nestingLevel = 0; + // Read the next text block while (true) { final char nextChar = (char) inputStream.read(); @@ -106,13 +123,13 @@ public class CharacterDelimitedTextBlockReader implements TextBlockReader { // Check for EOF if (nextChar == (char) -1) { eofOnInputStream = true; - break; + return textBlockBuilder; } if (nextChar == startTagChar) { nestingLevel++; } else if (nestingLevel == 0 && !Character.isWhitespace(nextChar)) { - LOGGER.warn("invalid input on consumer: " + nextChar); + LOGGER.warn("invalid input on consumer: {}", nextChar); continue; } @@ -125,17 +142,9 @@ public class CharacterDelimitedTextBlockReader implements TextBlockReader { } if (nestingLevel == 0) { - break; + return textBlockBuilder; } } } - - // Condition the text block and return it - final String textBlock = textBlockBuilder.toString().trim(); - if (textBlock.length() > 0) { - return new TextBlock(eofOnInputStream, textBlock); - } else { - return new TextBlock(eofOnInputStream, null); - } } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReader.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReader.java index 07185c024..982044022 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReader.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReader.java @@ -162,7 +162,7 @@ public class HeaderDelimitedTextBlockReader implements TextBlockReader, Runnable // Condition the text block and return it final String textBlock = textBlockBuilder.toString().trim(); - final boolean endOfText = (eofOnInputStream && textLineQueue.isEmpty() ? true : false); + final boolean endOfText = eofOnInputStream && textLineQueue.isEmpty(); if (textBlock.length() > 0) { return new TextBlock(endOfText, textBlock); diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducer.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducer.java index d5f9ff1b2..e12b772df 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducer.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducer.java @@ -32,7 +32,7 @@ import org.onap.policy.apex.service.engine.event.ApexEventProducer; import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; import org.onap.policy.apex.service.engine.event.PeeredReference; import org.onap.policy.apex.service.engine.event.SynchronousEventCache; -import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FILECarrierTechnologyParameters; +import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; import org.slf4j.Logger; @@ -74,20 +74,20 @@ public class ApexFileEventProducer implements ApexEventProducer { } // Check and get the file Properties - if (!(producerParameters.getCarrierTechnologyParameters() instanceof FILECarrierTechnologyParameters)) { + if (!(producerParameters.getCarrierTechnologyParameters() instanceof FileCarrierTechnologyParameters)) { final String errorMessage = "specified producer properties for ApexFileProducer \"" + producerName + "\" are not applicable to a FILE producer"; LOGGER.warn(errorMessage); throw new ApexEventException(errorMessage); } - final FILECarrierTechnologyParameters fileCarrierTechnologyParameters = - (FILECarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); + final FileCarrierTechnologyParameters fileCarrierTechnologyParameters = + (FileCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters(); // Now we create a writer for events try { if (fileCarrierTechnologyParameters.isStandardError()) { eventOutputStream = System.err; - } else if (fileCarrierTechnologyParameters.isStandardIO()) { + } else if (fileCarrierTechnologyParameters.isStandardIo()) { eventOutputStream = System.out; } else { eventOutputStream = diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JSONEventConverter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JSONEventConverter.java deleted file mode 100644 index 30e9db722..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JSONEventConverter.java +++ /dev/null @@ -1,438 +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.engine.event.impl.jsonprotocolplugin; - -import java.util.ArrayList; -import java.util.List; - -import org.onap.policy.apex.context.SchemaHelper; -import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory; -import org.onap.policy.apex.model.basicmodel.service.ModelService; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; -import org.onap.policy.apex.model.eventmodel.concepts.AxField; -import org.onap.policy.apex.service.engine.event.ApexEvent; -import org.onap.policy.apex.service.engine.event.ApexEventException; -import org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter; -import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -/** - * The Class Apex2JSONEventConverter converts {@link ApexEvent} instances to and from JSON string - * representations of Apex events. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class Apex2JSONEventConverter implements ApexEventProtocolConverter { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2JSONEventConverter.class); - - // The parameters for the JSON event protocol - private JSONEventProtocolParameters jsonPars; - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter#init(org.onap.policy. - * apex.service.parameters.eventprotocol.EventProtocolParameters) - */ - @Override - public void init(final EventProtocolParameters parameters) { - // Check and get the JSON parameters - if (!(parameters instanceof JSONEventProtocolParameters)) { - final String errorMessage = "specified consumer properties are not applicable to the JSON event protocol"; - LOGGER.warn(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - - jsonPars = (JSONEventProtocolParameters) parameters; - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, - * java.lang.Object) - */ - @Override - public List toApexEvent(final String eventName, final Object eventObject) throws ApexEventException { - // Check the event eventObject - if (eventObject == null) { - LOGGER.warn("event processing failed, event is null"); - throw new ApexEventException("event processing failed, event is null"); - } - - // Cast the event to a string, if our conversion is correctly configured, this cast should - // always work - String jsonEventString = null; - try { - jsonEventString = (String) eventObject; - } catch (final Exception e) { - final String errorMessage = "error converting event \"" + eventObject + "\" to a string"; - LOGGER.debug(errorMessage, e); - throw new ApexEventRuntimeException(errorMessage, e); - } - - // The list of events we will return - final List eventList = new ArrayList<>(); - - try { - // We may have a single JSON object with a single event or an array of JSON objects - final Object decodedJsonObject = - new GsonBuilder().serializeNulls().create().fromJson(jsonEventString, Object.class); - - // Check if we have a list of objects - if (decodedJsonObject instanceof List) { - // Check if it's a list of JSON objects or a list of strings - @SuppressWarnings("unchecked") - final List decodedJsonList = (List) decodedJsonObject; - - // Decode each of the list elements in sequence - for (final Object jsonListObject : decodedJsonList) { - if (jsonListObject instanceof String) { - eventList.add(jsonStringApexEvent(eventName, (String) jsonListObject)); - } else if (jsonListObject instanceof JsonObject) { - eventList.add(jsonObject2ApexEvent(eventName, (JsonObject) jsonListObject)); - } else { - throw new ApexEventException("incoming event (" + jsonEventString - + ") is a JSON object array containing an invalid object " + jsonListObject); - } - } - } else { - eventList.add(jsonStringApexEvent(eventName, jsonEventString)); - } - } catch (final Exception e) { - final String errorString = - "Failed to unmarshal JSON event: " + e.getMessage() + ", event=" + jsonEventString; - LOGGER.warn(errorString, e); - throw new ApexEventException(errorString, e); - } - - // Return the list of events we have unmarshalled - return eventList; - } - - /* - * (non-Javadoc) - * - * @see - * org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent(org.onap.policy. - * apex.service.engine.event.ApexEvent) - */ - @Override - public Object fromApexEvent(final ApexEvent apexEvent) throws ApexEventException { - // Check the Apex event - if (apexEvent == null) { - LOGGER.warn("event processing failed, Apex event is null"); - throw new ApexEventException("event processing failed, Apex event is null"); - } - - // Get the event definition for the event from the model service - final AxEvent eventDefinition = - ModelService.getModel(AxEvents.class).get(apexEvent.getName(), apexEvent.getVersion()); - - // Use a GSON Json object to marshal the Apex event to JSON - final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create(); - final JsonObject jsonObject = new JsonObject(); - - jsonObject.addProperty(ApexEvent.NAME_HEADER_FIELD, apexEvent.getName()); - jsonObject.addProperty(ApexEvent.VERSION_HEADER_FIELD, apexEvent.getVersion()); - jsonObject.addProperty(ApexEvent.NAMESPACE_HEADER_FIELD, apexEvent.getNameSpace()); - jsonObject.addProperty(ApexEvent.SOURCE_HEADER_FIELD, apexEvent.getSource()); - jsonObject.addProperty(ApexEvent.TARGET_HEADER_FIELD, apexEvent.getTarget()); - - if (apexEvent.getExceptionMessage() != null) { - jsonObject.addProperty(ApexEvent.EXCEPTION_MESSAGE_HEADER_FIELD, apexEvent.getExceptionMessage()); - } - - for (final AxField eventField : eventDefinition.getFields()) { - final String fieldName = eventField.getKey().getLocalName(); - - if (!apexEvent.containsKey(fieldName)) { - if (!eventField.getOptional()) { - final String errorMessage = "error parsing " + eventDefinition.getId() + " event to Json. " - + "Field \"" + fieldName + "\" is missing, but is mandatory. Fields: " + apexEvent; - LOGGER.debug(errorMessage); - throw new ApexEventRuntimeException(errorMessage); - } - continue; - } - - final Object fieldValue = apexEvent.get(fieldName); - - // Get the schema helper - final SchemaHelper fieldSchemaHelper = - new SchemaHelperFactory().createSchemaHelper(eventField.getKey(), eventField.getSchema()); - jsonObject.add(fieldName, (JsonElement) fieldSchemaHelper.marshal2Object(fieldValue)); - } - - // Output JSON string in a pretty format - return gson.toJson(jsonObject); - } - - /** - * This method converts a JSON object into an Apex event. - * - * @param eventName the name of the event - * @param jsonEventString the JSON string that holds the event - * @return the apex event that we have converted the JSON object into - * @throws ApexEventException thrown on unmarshaling exceptions - */ - private ApexEvent jsonStringApexEvent(final String eventName, final String jsonEventString) - throws ApexEventException { - // Use GSON to read the event string - final JsonObject jsonObject = - new GsonBuilder().serializeNulls().create().fromJson(jsonEventString, JsonObject.class); - - if (jsonObject == null || !jsonObject.isJsonObject()) { - throw new ApexEventException( - "incoming event (" + jsonEventString + ") is not a JSON object or an JSON object array"); - } - - return jsonObject2ApexEvent(eventName, jsonObject); - } - - /** - * This method converts a JSON object into an Apex event. - * - * @param eventName the name of the event - * @param jsonObject the JSON object that holds the event - * @return the apex event that we have converted the JSON object into - * @throws ApexEventException thrown on unmarshaling exceptions - */ - private ApexEvent jsonObject2ApexEvent(final String eventName, final JsonObject jsonObject) - throws ApexEventException { - // Process the mandatory Apex header - final ApexEvent apexEvent = processApexEventHeader(eventName, jsonObject); - - // Get the event definition for the event from the model service - final AxEvent eventDefinition = - ModelService.getModel(AxEvents.class).get(apexEvent.getName(), apexEvent.getVersion()); - - // Iterate over the input fields in the event - for (final AxField eventField : eventDefinition.getFields()) { - final String fieldName = eventField.getKey().getLocalName(); - if (!hasJSONField(jsonObject, fieldName)) { - if (!eventField.getOptional()) { - final String errorMessage = "error parsing " + eventDefinition.getId() + " event from Json. " - + "Field \"" + fieldName + "\" is missing, but is mandatory."; - LOGGER.debug(errorMessage); - throw new ApexEventException(errorMessage); - } - continue; - } - - final JsonElement fieldValue = getJSONField(jsonObject, fieldName, null, !eventField.getOptional()); - - if (fieldValue != null && !fieldValue.isJsonNull()) { - // Get the schema helper - final SchemaHelper fieldSchemaHelper = - new SchemaHelperFactory().createSchemaHelper(eventField.getKey(), eventField.getSchema()); - apexEvent.put(fieldName, fieldSchemaHelper.createNewInstance(fieldValue)); - } else { - apexEvent.put(fieldName, null); - } - } - return apexEvent; - - } - - /** - * This method processes the event header of an Apex event. - * - * @param eventName the name of the event - * @param jsonObject the JSON object containing the JSON representation of the incoming event - * @return an apex event constructed using the header fields of the event - * @throws ApexEventRuntimeException the apex event runtime exception - * @throws ApexEventException on invalid events with missing header fields - */ - private ApexEvent processApexEventHeader(final String eventName, final JsonObject jsonObject) - throws ApexEventException { - // Get the event header fields - // @formatter:off - String name = getJSONStringField(jsonObject, ApexEvent.NAME_HEADER_FIELD, - jsonPars.getNameAlias(), ApexEvent.NAME_REGEXP, false); - String version = getJSONStringField(jsonObject, ApexEvent.VERSION_HEADER_FIELD, - jsonPars.getVersionAlias(), ApexEvent.VERSION_REGEXP, false); - String namespace = getJSONStringField(jsonObject, ApexEvent.NAMESPACE_HEADER_FIELD, - jsonPars.getNameSpaceAlias(), ApexEvent.NAMESPACE_REGEXP, false); - String source = getJSONStringField(jsonObject, ApexEvent.SOURCE_HEADER_FIELD, - jsonPars.getSourceAlias(), ApexEvent.SOURCE_REGEXP, false); - String target = getJSONStringField(jsonObject, ApexEvent.TARGET_HEADER_FIELD, - jsonPars.getTargetAlias(), ApexEvent.TARGET_REGEXP, false); - // @formatter:on - - // Check that an event name has been specified - if (name == null && eventName == null) { - throw new ApexEventRuntimeException( - "event received without mandatory parameter \"name\" on configuration or on event"); - } - - // Check if an event name was specified on the event parameters - if (eventName != null) { - if (name != null && !eventName.equals(name)) { - LOGGER.warn("The incoming event name \"{}\" does not match the configured event name \"{}\"," - + " using configured event name", name, eventName); - } - name = eventName; - } - - // Now, find the event definition in the model service. If version is null, the newest event - // definition in the model service is used - final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(name, version); - if (eventDefinition == null) { - if (version == null) { - throw new ApexEventRuntimeException( - "an event definition for an event named \"" + name + "\" not found in Apex model"); - } - throw new ApexEventRuntimeException("an event definition for an event named \"" + name - + "\" with version \"" + version + "\" not found in Apex model"); - } - - // Use the defined event version if no version is specified on the incoming fields - if (version == null) { - version = eventDefinition.getKey().getVersion(); - } - - // Check the name space is OK if it is defined, if not, use the name space from the model - if (namespace != null) { - if (!namespace.equals(eventDefinition.getNameSpace())) { - throw new ApexEventRuntimeException( - "namespace \"" + namespace + "\" on event \"" + name + "\" does not match namespace \"" - + eventDefinition.getNameSpace() + "\" for that event in the Apex model"); - } - } else { - namespace = eventDefinition.getNameSpace(); - } - - // For source, use the defined source only if the source is not found on the incoming event - if (source == null) { - source = eventDefinition.getSource(); - } - - // For target, use the defined source only if the source is not found on the incoming event - if (target == null) { - target = eventDefinition.getTarget(); - } - - return new ApexEvent(name, version, namespace, source, target); - } - - /** - * This method gets an event string field from a JSON object. - * - * @param jsonObject the JSON object containing the JSON representation of the incoming event - * @param fieldName the field name to find in the event - * @param fieldAlias the alias for the field to find in the event, overrides the field name if - * it is not null - * @param fieldRE the regular expression to check the field against for validity - * @param mandatory true if the field is mandatory - * @return the value of the field in the JSON object or null if the field is optional - * @throws ApexEventRuntimeException the apex event runtime exception - */ - private String getJSONStringField(final JsonObject jsonObject, final String fieldName, final String fieldAlias, - final String fieldRE, final boolean mandatory) { - // Get the JSON field for the string field - final JsonElement jsonField = getJSONField(jsonObject, fieldName, fieldAlias, mandatory); - - // Null strings are allowed - if (jsonField == null || jsonField.isJsonNull()) { - return null; - } - - // Check if this is a string field - String fieldValueString = null; - try { - fieldValueString = jsonField.getAsString(); - } catch (final Exception e) { - // The element is not a string so throw an error - throw new ApexEventRuntimeException("field \"" + fieldName + "\" with type \"" - + jsonField.getClass().getCanonicalName() + "\" is not a string value"); - } - - // Is regular expression checking required - if (fieldRE == null) { - return fieldValueString; - } - - // Check the event field against its regular expression - if (!fieldValueString.matches(fieldRE)) { - throw new ApexEventRuntimeException( - "field \"" + fieldName + "\" with value \"" + fieldValueString + "\" is invalid"); - } - - return fieldValueString; - } - - /** - * This method gets an event field from a JSON object. - * - * @param jsonObject the JSON object containing the JSON representation of the incoming event - * @param fieldName the field name to find in the event - * @param fieldAlias the alias for the field to find in the event, overrides the field name if - * it is not null - * @param mandatory true if the field is mandatory - * @return the value of the field in the JSON object or null if the field is optional - * @throws ApexEventRuntimeException the apex event runtime exception - */ - private JsonElement getJSONField(final JsonObject jsonObject, final String fieldName, final String fieldAlias, - final boolean mandatory) { - - // Check if we should use the alias for this field - String fieldToFind = fieldName; - if (fieldAlias != null) { - fieldToFind = fieldAlias; - } - - // Get the event field - final JsonElement eventElement = jsonObject.get(fieldToFind); - if (eventElement == null) { - if (!mandatory) { - return null; - } else { - throw new ApexEventRuntimeException("mandatory field \"" + fieldToFind + "\" is missing"); - } - } - - return eventElement; - } - - /** - * This method if a JSON object has a named field. - * - * @param jsonObject the JSON object containing the JSON representation of the incoming event - * @param fieldName the field name to find in the event - * @return true if the field is present - * @throws ApexEventRuntimeException the apex event runtime exception - */ - private boolean hasJSONField(final JsonObject jsonObject, final String fieldName) { - // check for the field - return jsonObject.has(fieldName); - } -} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JsonEventConverter.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JsonEventConverter.java new file mode 100644 index 000000000..ce511be7f --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/Apex2JsonEventConverter.java @@ -0,0 +1,440 @@ +/*- + * ============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.engine.event.impl.jsonprotocolplugin; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.policy.apex.context.SchemaHelper; +import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; +import org.onap.policy.apex.model.eventmodel.concepts.AxField; +import org.onap.policy.apex.service.engine.event.ApexEvent; +import org.onap.policy.apex.service.engine.event.ApexEventException; +import org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter; +import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; +import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class Apex2JSONEventConverter converts {@link ApexEvent} instances to and from JSON string representations of + * Apex events. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class Apex2JsonEventConverter implements ApexEventProtocolConverter { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(Apex2JsonEventConverter.class); + + // The parameters for the JSON event protocol + private JsonEventProtocolParameters jsonPars; + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter#init(org.onap.policy. + * apex.service.parameters.eventprotocol.EventProtocolParameters) + */ + @Override + public void init(final EventProtocolParameters parameters) { + // Check and get the JSON parameters + if (!(parameters instanceof JsonEventProtocolParameters)) { + final String errorMessage = "specified consumer properties are not applicable to the JSON event protocol"; + LOGGER.warn(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + + jsonPars = (JsonEventProtocolParameters) parameters; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#toApexEvent(java.lang.String, java.lang.Object) + */ + @Override + public List toApexEvent(final String eventName, final Object eventObject) throws ApexEventException { + // Check the event eventObject + if (eventObject == null) { + LOGGER.warn("event processing failed, event is null"); + throw new ApexEventException("event processing failed, event is null"); + } + + // Cast the event to a string, if our conversion is correctly configured, this cast should + // always work + String jsonEventString = null; + try { + jsonEventString = (String) eventObject; + } catch (final Exception e) { + final String errorMessage = "error converting event \"" + eventObject + "\" to a string"; + LOGGER.debug(errorMessage, e); + throw new ApexEventRuntimeException(errorMessage, e); + } + + // The list of events we will return + final List eventList = new ArrayList<>(); + + try { + // We may have a single JSON object with a single event or an array of JSON objects + final Object decodedJsonObject = new GsonBuilder().serializeNulls().create().fromJson(jsonEventString, + Object.class); + + // Check if we have a list of objects + if (decodedJsonObject instanceof List) { + // Check if it's a list of JSON objects or a list of strings + @SuppressWarnings("unchecked") + final List decodedJsonList = (List) decodedJsonObject; + + // Decode each of the list elements in sequence + for (final Object jsonListObject : decodedJsonList) { + if (jsonListObject instanceof String) { + eventList.add(jsonStringApexEvent(eventName, (String) jsonListObject)); + } else if (jsonListObject instanceof JsonObject) { + eventList.add(jsonObject2ApexEvent(eventName, (JsonObject) jsonListObject)); + } else { + throw new ApexEventException("incoming event (" + jsonEventString + + ") is a JSON object array containing an invalid object " + jsonListObject); + } + } + } else { + eventList.add(jsonStringApexEvent(eventName, jsonEventString)); + } + } catch (final Exception e) { + final String errorString = "Failed to unmarshal JSON event: " + e.getMessage() + ", event=" + + jsonEventString; + LOGGER.warn(errorString, e); + throw new ApexEventException(errorString, e); + } + + // Return the list of events we have unmarshalled + return eventList; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.service.engine.event.ApexEventConverter#fromApexEvent(org.onap.policy. + * apex.service.engine.event.ApexEvent) + */ + @Override + public Object fromApexEvent(final ApexEvent apexEvent) throws ApexEventException { + // Check the Apex event + if (apexEvent == null) { + LOGGER.warn("event processing failed, Apex event is null"); + throw new ApexEventException("event processing failed, Apex event is null"); + } + + // Get the event definition for the event from the model service + final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(apexEvent.getName(), + apexEvent.getVersion()); + + // Use a GSON Json object to marshal the Apex event to JSON + final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create(); + final JsonObject jsonObject = new JsonObject(); + + jsonObject.addProperty(ApexEvent.NAME_HEADER_FIELD, apexEvent.getName()); + jsonObject.addProperty(ApexEvent.VERSION_HEADER_FIELD, apexEvent.getVersion()); + jsonObject.addProperty(ApexEvent.NAMESPACE_HEADER_FIELD, apexEvent.getNameSpace()); + jsonObject.addProperty(ApexEvent.SOURCE_HEADER_FIELD, apexEvent.getSource()); + jsonObject.addProperty(ApexEvent.TARGET_HEADER_FIELD, apexEvent.getTarget()); + + if (apexEvent.getExceptionMessage() != null) { + jsonObject.addProperty(ApexEvent.EXCEPTION_MESSAGE_HEADER_FIELD, apexEvent.getExceptionMessage()); + } + + for (final AxField eventField : eventDefinition.getFields()) { + final String fieldName = eventField.getKey().getLocalName(); + + if (!apexEvent.containsKey(fieldName)) { + if (!eventField.getOptional()) { + final String errorMessage = "error parsing " + eventDefinition.getId() + " event to Json. " + + "Field \"" + fieldName + "\" is missing, but is mandatory. Fields: " + apexEvent; + LOGGER.debug(errorMessage); + throw new ApexEventRuntimeException(errorMessage); + } + continue; + } + + final Object fieldValue = apexEvent.get(fieldName); + + // Get the schema helper + final SchemaHelper fieldSchemaHelper = new SchemaHelperFactory().createSchemaHelper(eventField.getKey(), + eventField.getSchema()); + jsonObject.add(fieldName, (JsonElement) fieldSchemaHelper.marshal2Object(fieldValue)); + } + + // Output JSON string in a pretty format + return gson.toJson(jsonObject); + } + + /** + * This method converts a JSON object into an Apex event. + * + * @param eventName the name of the event + * @param jsonEventString the JSON string that holds the event + * @return the apex event that we have converted the JSON object into + * @throws ApexEventException thrown on unmarshaling exceptions + */ + private ApexEvent jsonStringApexEvent(final String eventName, final String jsonEventString) + throws ApexEventException { + // Use GSON to read the event string + final JsonObject jsonObject = new GsonBuilder().serializeNulls().create().fromJson(jsonEventString, + JsonObject.class); + + if (jsonObject == null || !jsonObject.isJsonObject()) { + throw new ApexEventException( + "incoming event (" + jsonEventString + ") is not a JSON object or an JSON object array"); + } + + return jsonObject2ApexEvent(eventName, jsonObject); + } + + /** + * This method converts a JSON object into an Apex event. + * + * @param eventName the name of the event + * @param jsonObject the JSON object that holds the event + * @return the apex event that we have converted the JSON object into + * @throws ApexEventException thrown on unmarshaling exceptions + */ + private ApexEvent jsonObject2ApexEvent(final String eventName, final JsonObject jsonObject) + throws ApexEventException { + // Process the mandatory Apex header + final ApexEvent apexEvent = processApexEventHeader(eventName, jsonObject); + + // Get the event definition for the event from the model service + final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(apexEvent.getName(), + apexEvent.getVersion()); + + // Iterate over the input fields in the event + for (final AxField eventField : eventDefinition.getFields()) { + final String fieldName = eventField.getKey().getLocalName(); + if (!hasJsonField(jsonObject, fieldName)) { + if (!eventField.getOptional()) { + final String errorMessage = "error parsing " + eventDefinition.getId() + " event from Json. " + + "Field \"" + fieldName + "\" is missing, but is mandatory."; + LOGGER.debug(errorMessage); + throw new ApexEventException(errorMessage); + } + continue; + } + + final JsonElement fieldValue = getJsonField(jsonObject, fieldName, null, !eventField.getOptional()); + + if (fieldValue != null && !fieldValue.isJsonNull()) { + // Get the schema helper + final SchemaHelper fieldSchemaHelper = new SchemaHelperFactory().createSchemaHelper(eventField.getKey(), + eventField.getSchema()); + apexEvent.put(fieldName, fieldSchemaHelper.createNewInstance(fieldValue)); + } else { + apexEvent.put(fieldName, null); + } + } + return apexEvent; + + } + + /** + * This method processes the event header of an Apex event. + * + * @param eventName the name of the event + * @param jsonObject the JSON object containing the JSON representation of the incoming event + * @return an apex event constructed using the header fields of the event + * @throws ApexEventRuntimeException the apex event runtime exception + * @throws ApexEventException on invalid events with missing header fields + */ + private ApexEvent processApexEventHeader(final String eventName, final JsonObject jsonObject) + throws ApexEventException { + String name = getJsonStringField(jsonObject, ApexEvent.NAME_HEADER_FIELD, jsonPars.getNameAlias(), + ApexEvent.NAME_REGEXP, false); + + // Check that an event name has been specified + if (name == null && eventName == null) { + throw new ApexEventRuntimeException( + "event received without mandatory parameter \"name\" on configuration or on event"); + } + + // Check if an event name was specified on the event parameters + if (eventName != null) { + if (name != null && !eventName.equals(name)) { + LOGGER.warn("The incoming event name \"{}\" does not match the configured event name \"{}\"," + + " using configured event name", name, eventName); + } + name = eventName; + } + + // Now, find the event definition in the model service. If version is null, the newest event + // definition in the model service is used + String version = getJsonStringField(jsonObject, ApexEvent.VERSION_HEADER_FIELD, jsonPars.getVersionAlias(), + ApexEvent.VERSION_REGEXP, false); + final AxEvent eventDefinition = ModelService.getModel(AxEvents.class).get(name, version); + if (eventDefinition == null) { + throwVersionException(name, version); + } + + // Use the defined event version if no version is specified on the incoming fields + if (version == null) { + version = eventDefinition.getKey().getVersion(); + } + + // Check the name space is OK if it is defined, if not, use the name space from the model + String namespace = getJsonStringField(jsonObject, ApexEvent.NAMESPACE_HEADER_FIELD, + jsonPars.getNameSpaceAlias(), ApexEvent.NAMESPACE_REGEXP, false); + if (namespace != null) { + if (!namespace.equals(eventDefinition.getNameSpace())) { + throw new ApexEventRuntimeException("namespace \"" + namespace + "\" on event \"" + name + + "\" does not match namespace \"" + eventDefinition.getNameSpace() + + "\" for that event in the Apex model"); + } + } else { + namespace = eventDefinition.getNameSpace(); + } + + // For source, use the defined source only if the source is not found on the incoming event + String source = getJsonStringField(jsonObject, ApexEvent.SOURCE_HEADER_FIELD, jsonPars.getSourceAlias(), + ApexEvent.SOURCE_REGEXP, false); + if (source == null) { + source = eventDefinition.getSource(); + } + + // For target, use the defined source only if the source is not found on the incoming event + String target = getJsonStringField(jsonObject, ApexEvent.TARGET_HEADER_FIELD, jsonPars.getTargetAlias(), + ApexEvent.TARGET_REGEXP, false); + if (target == null) { + target = eventDefinition.getTarget(); + } + + return new ApexEvent(name, version, namespace, source, target); + } + + /** + * Throw an exception on event name and/or version with the correct text. + * @param name The event name + * @param version The event version + */ + private void throwVersionException(String name, String version) { + if (version == null) { + throw new ApexEventRuntimeException( + "an event definition for an event named \"" + name + "\" not found in Apex model"); + } + else { + throw new ApexEventRuntimeException("an event definition for an event named \"" + name + + "\" with version \"" + version + "\" not found in Apex model"); + } + } + + /** + * This method gets an event string field from a JSON object. + * + * @param jsonObject the JSON object containing the JSON representation of the incoming event + * @param fieldName the field name to find in the event + * @param fieldAlias the alias for the field to find in the event, overrides the field name if it is not null + * @param fieldRegexp the regular expression to check the field against for validity + * @param mandatory true if the field is mandatory + * @return the value of the field in the JSON object or null if the field is optional + * @throws ApexEventRuntimeException the apex event runtime exception + */ + private String getJsonStringField(final JsonObject jsonObject, final String fieldName, final String fieldAlias, + final String fieldRegexp, final boolean mandatory) { + // Get the JSON field for the string field + final JsonElement jsonField = getJsonField(jsonObject, fieldName, fieldAlias, mandatory); + + // Null strings are allowed + if (jsonField == null || jsonField.isJsonNull()) { + return null; + } + + // Check if this is a string field + String fieldValueString = null; + try { + fieldValueString = jsonField.getAsString(); + } catch (final Exception e) { + // The element is not a string so throw an error + throw new ApexEventRuntimeException("field \"" + fieldName + "\" with type \"" + + jsonField.getClass().getCanonicalName() + "\" is not a string value"); + } + + // Is regular expression checking required + if (fieldRegexp == null) { + return fieldValueString; + } + + // Check the event field against its regular expression + if (!fieldValueString.matches(fieldRegexp)) { + throw new ApexEventRuntimeException( + "field \"" + fieldName + "\" with value \"" + fieldValueString + "\" is invalid"); + } + + return fieldValueString; + } + + /** + * This method gets an event field from a JSON object. + * + * @param jsonObject the JSON object containing the JSON representation of the incoming event + * @param fieldName the field name to find in the event + * @param fieldAlias the alias for the field to find in the event, overrides the field name if it is not null + * @param mandatory true if the field is mandatory + * @return the value of the field in the JSON object or null if the field is optional + * @throws ApexEventRuntimeException the apex event runtime exception + */ + private JsonElement getJsonField(final JsonObject jsonObject, final String fieldName, final String fieldAlias, + final boolean mandatory) { + + // Check if we should use the alias for this field + String fieldToFind = fieldName; + if (fieldAlias != null) { + fieldToFind = fieldAlias; + } + + // Get the event field + final JsonElement eventElement = jsonObject.get(fieldToFind); + if (eventElement == null) { + if (!mandatory) { + return null; + } else { + throw new ApexEventRuntimeException("mandatory field \"" + fieldToFind + "\" is missing"); + } + } + + return eventElement; + } + + /** + * This method if a JSON object has a named field. + * + * @param jsonObject the JSON object containing the JSON representation of the incoming event + * @param fieldName the field name to find in the event + * @return true if the field is present + * @throws ApexEventRuntimeException the apex event runtime exception + */ + private boolean hasJsonField(final JsonObject jsonObject, final String fieldName) { + // check for the field + return jsonObject.has(fieldName); + } +} 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 deleted file mode 100644 index 6efcceb43..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JSONEventProtocolParameters.java +++ /dev/null @@ -1,187 +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.engine.event.impl.jsonprotocolplugin; - -import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolTextCharDelimitedParameters; - -/** - * Event protocol parameters for JSON as an event protocol. - * - *

The parameters for this plugin are: - *

    - *
  1. nameAlias: The field in a JSON event to use as an alias for the event name. This parameter is - * optional. - *
  2. versionAlias: The field in a JSON event to use as an alias for the event version. This - * parameter is optional. - *
  3. nameSpaceAlias: The field in a JSON event to use as an alias for the event name space. This - * parameter is optional. - *
  4. sourceAlias: The field in a JSON event to use as an alias for the event source. This - * parameter is optional. - *
  5. targetAlias: The field in a JSON event to use as an alias for the event target. This - * parameter is optional. - *
- * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class JSONEventProtocolParameters extends EventProtocolTextCharDelimitedParameters { - /** The label of this event protocol. */ - public static final String JSON_EVENT_PROTOCOL_LABEL = "JSON"; - - // Constants for text block delimiters - private static final char JSON_TEXT_BLOCK_START_DELIMITER = '{'; - private static final char JSON_TEXT_BLOCK_END_DELIMITER = '}'; - - // Aliases for Apex event header fields - // @formatter:off - private String nameAlias = null; - private String versionAlias = null; - private String nameSpaceAlias = null; - private String sourceAlias = null; - private String targetAlias = null; - // @formatter:on - - /** - * Constructor to create a JSON event protocol parameter instance and register the instance with - * the parameter service. - */ - public JSONEventProtocolParameters() { - this(JSONEventProtocolParameters.class.getCanonicalName(), JSON_EVENT_PROTOCOL_LABEL); - } - - /** - * 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 - */ - public JSONEventProtocolParameters(final String parameterClassName, final String eventProtocolLabel) { - super(parameterClassName); - - // Set the event protocol properties for the JSON event protocol - this.setLabel(eventProtocolLabel); - - // Set the starting and ending delimiters for text blocks of JSON events - this.setStartChar(JSON_TEXT_BLOCK_START_DELIMITER); - this.setEndChar(JSON_TEXT_BLOCK_END_DELIMITER); - - // Set the event protocol plugin class - 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. - * - * @return the name alias - */ - public String getNameAlias() { - return nameAlias; - } - - /** - * Gets the version alias. - * - * @return the version alias - */ - public String getVersionAlias() { - return versionAlias; - } - - /** - * Gets the name space alias. - * - * @return the name space alias - */ - public String getNameSpaceAlias() { - return nameSpaceAlias; - } - - /** - * Gets the source alias. - * - * @return the source alias - */ - public String getSourceAlias() { - return sourceAlias; - } - - /** - * Gets the target alias. - * - * @return the target alias - */ - public String getTargetAlias() { - return targetAlias; - } - - /** - * Sets the name alias. - * - * @param nameAlias the new name alias - */ - public void setNameAlias(String nameAlias) { - this.nameAlias = nameAlias; - } - - /** - * Sets the version alias. - * - * @param versionAlias the new version alias - */ - public void setVersionAlias(String versionAlias) { - this.versionAlias = versionAlias; - } - - /** - * Sets the name space alias. - * - * @param nameSpaceAlias the new name space alias - */ - public void setNameSpaceAlias(String nameSpaceAlias) { - this.nameSpaceAlias = nameSpaceAlias; - } - - /** - * Sets the source alias. - * - * @param sourceAlias the new source alias - */ - public void setSourceAlias(String sourceAlias) { - this.sourceAlias = sourceAlias; - } - - /** - * Sets the target alias. - * - * @param targetAlias the new target alias - */ - public void setTargetAlias(String targetAlias) { - this.targetAlias = targetAlias; - } -} 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 new file mode 100644 index 000000000..8e44ec59b --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/impl/jsonprotocolplugin/JsonEventProtocolParameters.java @@ -0,0 +1,187 @@ +/*- + * ============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.engine.event.impl.jsonprotocolplugin; + +import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolTextCharDelimitedParameters; + +/** + * Event protocol parameters for JSON as an event protocol. + * + *

The parameters for this plugin are: + *

    + *
  1. nameAlias: The field in a JSON event to use as an alias for the event name. This parameter is + * optional. + *
  2. versionAlias: The field in a JSON event to use as an alias for the event version. This + * parameter is optional. + *
  3. nameSpaceAlias: The field in a JSON event to use as an alias for the event name space. This + * parameter is optional. + *
  4. sourceAlias: The field in a JSON event to use as an alias for the event source. This + * parameter is optional. + *
  5. targetAlias: The field in a JSON event to use as an alias for the event target. This + * parameter is optional. + *
+ * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class JsonEventProtocolParameters extends EventProtocolTextCharDelimitedParameters { + /** The label of this event protocol. */ + public static final String JSON_EVENT_PROTOCOL_LABEL = "JSON"; + + // Constants for text block delimiters + private static final char JSON_TEXT_BLOCK_START_DELIMITER = '{'; + private static final char JSON_TEXT_BLOCK_END_DELIMITER = '}'; + + // Aliases for Apex event header fields + // @formatter:off + private String nameAlias = null; + private String versionAlias = null; + private String nameSpaceAlias = null; + private String sourceAlias = null; + private String targetAlias = null; + // @formatter:on + + /** + * Constructor to create a JSON event protocol parameter instance and register the instance with + * the parameter service. + */ + public JsonEventProtocolParameters() { + this(JsonEventProtocolParameters.class.getCanonicalName(), JSON_EVENT_PROTOCOL_LABEL); + } + + /** + * 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 + */ + public JsonEventProtocolParameters(final String parameterClassName, final String eventProtocolLabel) { + super(parameterClassName); + + // Set the event protocol properties for the JSON event protocol + this.setLabel(eventProtocolLabel); + + // Set the starting and ending delimiters for text blocks of JSON events + this.setStartChar(JSON_TEXT_BLOCK_START_DELIMITER); + this.setEndChar(JSON_TEXT_BLOCK_END_DELIMITER); + + // Set the event protocol plugin class + 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. + * + * @return the name alias + */ + public String getNameAlias() { + return nameAlias; + } + + /** + * Gets the version alias. + * + * @return the version alias + */ + public String getVersionAlias() { + return versionAlias; + } + + /** + * Gets the name space alias. + * + * @return the name space alias + */ + public String getNameSpaceAlias() { + return nameSpaceAlias; + } + + /** + * Gets the source alias. + * + * @return the source alias + */ + public String getSourceAlias() { + return sourceAlias; + } + + /** + * Gets the target alias. + * + * @return the target alias + */ + public String getTargetAlias() { + return targetAlias; + } + + /** + * Sets the name alias. + * + * @param nameAlias the new name alias + */ + public void setNameAlias(String nameAlias) { + this.nameAlias = nameAlias; + } + + /** + * Sets the version alias. + * + * @param versionAlias the new version alias + */ + public void setVersionAlias(String versionAlias) { + this.versionAlias = versionAlias; + } + + /** + * Sets the name space alias. + * + * @param nameSpaceAlias the new name space alias + */ + public void setNameSpaceAlias(String nameSpaceAlias) { + this.nameSpaceAlias = nameSpaceAlias; + } + + /** + * Sets the source alias. + * + * @param sourceAlias the new source alias + */ + public void setSourceAlias(String sourceAlias) { + this.sourceAlias = sourceAlias; + } + + /** + * Sets the target alias. + * + * @param targetAlias the new target alias + */ + public void setTargetAlias(String targetAlias) { + this.targetAlias = targetAlias; + } +} diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArguments.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArguments.java index d6d278ebf..bdbd82dc2 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArguments.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArguments.java @@ -42,6 +42,8 @@ import org.onap.policy.common.utils.resources.ResourceUtils; * @author Liam Fallon (liam.fallon@ericsson.com) */ public class ApexCommandLineArguments { + // Recurring string constants + private static final String FILE_PREAMBLE = " file \""; private static final int HELP_LINE_LENGTH = 120; // Apache Commons CLI options @@ -181,12 +183,11 @@ public class ApexCommandLineArguments { * @return the help string */ public String help(final String mainClassName) { - final HelpFormatter helpFormatter = new HelpFormatter(); final StringWriter stringWriter = new StringWriter(); - final PrintWriter stringPW = new PrintWriter(stringWriter); + final PrintWriter stringPrintWriter = new PrintWriter(stringWriter); - helpFormatter.printHelp(stringPW, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0, 0, - ""); + new HelpFormatter().printHelp(stringPrintWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", + options, 0, 0, ""); return stringWriter.toString(); } @@ -268,20 +269,20 @@ public class ApexCommandLineArguments { } // The file name can refer to a resource on the local file system or on the class path - final URL fileURL = ResourceUtils.getUrl4Resource(fileName); - if (fileURL == null) { - throw new ApexException(fileTag + " file \"" + fileName + "\" does not exist"); + final URL fileUrl = ResourceUtils.getUrl4Resource(fileName); + if (fileUrl == null) { + throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" does not exist"); } - final File theFile = new File(fileURL.getPath()); + final File theFile = new File(fileUrl.getPath()); if (!theFile.exists()) { - throw new ApexException(fileTag + " file \"" + fileName + "\" does not exist"); + throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" does not exist"); } if (!theFile.isFile()) { - throw new ApexException(fileTag + " file \"" + fileName + "\" is not a normal file"); + throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" is not a normal file"); } if (!theFile.canRead()) { - throw new ApexException(fileTag + " file \"" + fileName + "\" is ureadable"); + throw new ApexException(fileTag + FILE_PREAMBLE + fileName + "\" is ureadable"); } } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java index 9904847aa..532fdb9c7 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventMarshaller.java @@ -187,19 +187,19 @@ public class ApexEventMarshaller implements ApexEventListener, Runnable { // Process the next Apex event from the queue final Object event = converter.fromApexEvent(apexEvent); - producer.sendEvent(apexEvent.getExecutionID(), apexEvent.getName(), event); + producer.sendEvent(apexEvent.getExecutionId(), apexEvent.getName(), event); if (LOGGER.isTraceEnabled()) { - LOGGER.trace("event sent : " + apexEvent.toString()); + String message = "event sent : " + apexEvent.toString(); + LOGGER.trace(message); } } catch (final InterruptedException e) { // restore the interrupt status Thread.currentThread().interrupt(); LOGGER.debug("Thread interrupted, Reason {}", e.getMessage()); - break; + stopOrderedFlag = true; } catch (final Exception e) { LOGGER.warn("Error while forwarding events for " + marshallerThread.getName(), e); - continue; } } diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java index 7b4188ea1..1d1b64e37 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexEventUnmarshaller.java @@ -44,8 +44,8 @@ import org.slf4j.ext.XLogger; import org.slf4j.ext.XLoggerFactory; /** - * This event unmarshaler handles events coming into Apex, handles threading, event queuing, - * transformation and receiving using the configured receiving technology. + * This event unmarshaler handles events coming into Apex, handles threading, event queuing, transformation and + * receiving using the configured receiving technology. * * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -88,7 +88,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { * @param consumerParameters the consumer parameters for this specific unmarshaler */ public ApexEventUnmarshaller(final String name, final EngineServiceParameters engineServiceParameters, - final EventHandlerParameters consumerParameters) { + final EventHandlerParameters consumerParameters) { this.name = name; this.engineServiceParameters = engineServiceParameters; this.consumerParameters = consumerParameters; @@ -97,8 +97,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { /** * Configure the consumer and initialize the thread for event sending. * - * @param incomingEngineServiceHandler the Apex engine service handler for passing events to - * Apex + * @param incomingEngineServiceHandler the Apex engine service handler for passing events to Apex * @throws ApexEventException on errors initializing event handling */ public void init(final ApexEngineServiceHandler incomingEngineServiceHandler) throws ApexEventException { @@ -119,8 +118,8 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { consumer.start(); // Configure and start the event reception thread - final String threadName = - engineServiceParameters.getEngineKey().getName() + ":" + this.getClass().getName() + ":" + name; + final String threadName = engineServiceParameters.getEngineKey().getName() + ":" + this.getClass().getName() + + ":" + name; unmarshallerThread = new ApplicationThreadFactory(threadName).newThread(this); unmarshallerThread.setDaemon(true); unmarshallerThread.start(); @@ -165,7 +164,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { // To connect a synchronous unmarshaler and marshaler, we create a synchronous event // cache on the consumer/producer pair new SynchronousEventCache(peeredMode, consumer, peeredMarshaller.getProducer(), - consumerParameters.getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); + consumerParameters.getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); return; case REQUESTOR: @@ -180,8 +179,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { /* * (non-Javadoc) * - * @see - * org.onap.policy.apex.service.engine.event.ApexEventReceiver#receiveEvent(java.lang.Object) + * @see org.onap.policy.apex.service.engine.event.ApexEventReceiver#receiveEvent(java.lang.Object) */ @Override public void receiveEvent(final Object event) throws ApexEventException { @@ -191,8 +189,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { /* * (non-Javadoc) * - * @see org.onap.policy.apex.service.engine.event.ApexEventReceiver#receiveEvent(long, - * java.lang.Object) + * @see org.onap.policy.apex.service.engine.event.ApexEventReceiver#receiveEvent(long, java.lang.Object) */ @Override public void receiveEvent(final long executionId, final Object event) throws ApexEventException { @@ -204,15 +201,15 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { * * @param executionId the execution id the incoming execution ID * @param event the event in its native format - * @param generateExecutionId if true, let Apex generate the execution ID, if false, use the - * incoming execution ID + * @param generateExecutionId if true, let Apex generate the execution ID, if false, use the incoming execution ID * @throws ApexEventException on unmarshaling errors on events */ private void receiveEvent(final long executionId, final Object event, final boolean generateExecutionId) - throws ApexEventException { + throws ApexEventException { // Push the event onto the queue if (LOGGER.isTraceEnabled()) { - LOGGER.trace("onMessage(): event received: {}", event.toString()); + String eventString = "onMessage(): event received: " + event.toString(); + LOGGER.trace(eventString); } // Convert the incoming events to Apex events @@ -222,10 +219,10 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { // Check if we are filtering events on this unmarshaler, if so check the event name // against the filter if (consumerParameters.isSetEventNameFilter() - && !apexEvent.getName().matches(consumerParameters.getEventNameFilter())) { + && !apexEvent.getName().matches(consumerParameters.getEventNameFilter())) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("onMessage(): event {} not processed, filtered out by filter", apexEvent, - consumerParameters.getEventNameFilter()); + consumerParameters.getEventNameFilter()); } // Ignore this event @@ -233,7 +230,7 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { } if (!generateExecutionId) { - apexEvent.setExecutionID(executionId); + apexEvent.setExecutionId(executionId); } // Enqueue the event @@ -241,22 +238,22 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { // Cache synchronized events that are sent if (consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS)) { - final SynchronousEventCache synchronousEventCache = - (SynchronousEventCache) consumer.getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS); - synchronousEventCache.cacheSynchronizedEventToApex(apexEvent.getExecutionID(), apexEvent); + final SynchronousEventCache synchronousEventCache = (SynchronousEventCache) consumer + .getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS); + synchronousEventCache.cacheSynchronizedEventToApex(apexEvent.getExecutionId(), apexEvent); } } } catch (final ApexException e) { final String errorMessage = "Error while converting event into an ApexEvent for " + name + ": " - + e.getMessage() + ", Event=" + event; + + e.getMessage() + ", Event=" + event; LOGGER.warn(errorMessage, e); throw new ApexEventException(errorMessage, e); } } /** - * Run a thread that runs forever (well until system termination anyway) and listens for - * incoming events on the queue. + * Run a thread that runs forever (well until system termination anyway) and listens for incoming events on the + * queue. */ @Override public void run() { @@ -270,7 +267,8 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { } if (LOGGER.isTraceEnabled()) { - LOGGER.trace("event received {}", apexEvent.toString()); + String message = apexEvent.toString(); + LOGGER.trace("event received {}", message); } // Pass the event to the activator for forwarding to Apex @@ -279,10 +277,9 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { // restore the interrupt status Thread.currentThread().interrupt(); LOGGER.warn("BatchProcessor thread interrupted, Reason {}", e.getMessage()); - break; + stopOrderedFlag = true; } catch (final Exception e) { LOGGER.warn("Error while forwarding events for " + unmarshallerThread.getName(), e); - continue; } } @@ -309,10 +306,9 @@ public class ApexEventUnmarshaller implements ApexEventReceiver, Runnable { stopOrderedFlag = true; // Order a stop on the synchronous cache if one exists - if (consumerParameters != null && consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS)) { - if (consumer.getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS) != null) { - ((SynchronousEventCache) consumer.getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS)).stop(); - } + if (consumerParameters != null && consumerParameters.isPeeredMode(EventHandlerPeeredMode.SYNCHRONOUS) + && consumer.getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS) != null) { + ((SynchronousEventCache) consumer.getPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS)).stop(); } // Wait for thread shutdown diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java index 436225fc4..2b15b145f 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java @@ -50,7 +50,6 @@ public class ApexMain { * @param args the commaind line arguments */ public ApexMain(final String[] args) { - System.out.println("Starting Apex service with parameters " + Arrays.toString(args) + " . . ."); LOGGER.entry("Starting Apex service with parameters " + Arrays.toString(args) + " . . ."); // Check the arguments @@ -60,16 +59,13 @@ public class ApexMain { final String argumentMessage = arguments.parse(args); if (argumentMessage != null) { LOGGER.info(argumentMessage); - System.out.println(argumentMessage); return; } // Validate that the arguments are sane arguments.validate(); } catch (final ApexException e) { - System.err.println("start of Apex service failed: " + e.getMessage()); LOGGER.error("start of Apex service failed", e); - System.err.println(arguments.help(ApexMain.class.getCanonicalName())); return; } @@ -77,7 +73,6 @@ public class ApexMain { try { parameters = new ApexParameterHandler().getParameters(arguments); } catch (final Exception e) { - System.err.println("start of Apex service failed\n" + e.getMessage()); LOGGER.error("start of Apex service failed", e); return; } @@ -103,8 +98,6 @@ public class ApexMain { try { activator.initialize(); } catch (final ApexActivatorException e) { - System.err.println("start of Apex service failed, used parameters are " + Arrays.toString(args)); - e.printStackTrace(System.err); LOGGER.error("start of Apex service failed, used parameters are " + Arrays.toString(args), e); return; } @@ -112,7 +105,6 @@ public class ApexMain { // Add a shutdown hook to shut everything down in an orderly manner Runtime.getRuntime().addShutdownHook(new ApexMainShutdownHookClass()); LOGGER.exit("Started Apex"); - System.out.println("Started Apex service"); } /** diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/EngineService.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/EngineService.java index 1af0c9d1c..ef17a8eab 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/EngineService.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/EngineService.java @@ -101,7 +101,7 @@ public interface EngineService { void updateModel(AxArtifactKey engineServiceKey, AxPolicyModel apexModel, boolean forceFlag) throws ApexException; /** - * This method returns the state of an engine service or engine. + * Return the state of an engine service or engine. * * @return The engine service or engine state */ 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 04fb8e389..c99987542 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 @@ -63,6 +63,10 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineServiceImpl.class); private static final boolean DEBUG_ENABLED = LOGGER.isDebugEnabled(); + // Recurring string constants + private static final String ENGINE_KEY_PREAMBLE = "engine with key "; + private static final String NOT_FOUND_SUFFIX = " not found in engine service"; + // Constants for timing private static final long MAX_START_WAIT_TIME = 5000; // 5 seconds private static final long MAX_STOP_WAIT_TIME = 5000; // 5 seconds @@ -96,7 +100,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven * @throws ApexException on worker instantiation errors */ private EngineServiceImpl(final AxArtifactKey engineServiceKey, final int incomingThreadCount, - final long periodicEventPeriod) throws ApexException { + final long periodicEventPeriod) { LOGGER.entry(engineServiceKey, incomingThreadCount); this.engineServiceKey = engineServiceKey; @@ -120,26 +124,6 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven LOGGER.exit(); } - /** - * Create an Apex Engine Service instance. This method is deprecated and will be removed in the next version. - * - * @param engineServiceKey the engine service key - * @param threadCount the thread count, the number of engine workers to start - * @return the Engine Service instance - * @throws ApexException on worker instantiation errors - * @deprecated Do not use this version. Use {@link #create(EngineServiceParameters)} - */ - @Deprecated - public static EngineServiceImpl create(final AxArtifactKey engineServiceKey, final int threadCount) - throws ApexException { - // Check if the Apex model specified is sane - if (engineServiceKey == null) { - LOGGER.warn("engine service key is null"); - throw new ApexException("engine service key is null"); - } - return new EngineServiceImpl(engineServiceKey, threadCount, 0); - } - /** * Create an Apex Engine Service instance. This method does not load the policy so * {@link #updateModel(AxArtifactKey, AxPolicyModel, boolean)} or @@ -266,10 +250,10 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven final boolean forceFlag) throws ApexException { // Check if the Apex model specified is sane if (apexModelString == null || apexModelString.trim().length() == 0) { - LOGGER.warn("model for updating on engine service with key " + incomingEngineServiceKey.getId() - + " is empty"); - throw new ApexException("model for updating on engine service with key " + incomingEngineServiceKey.getId() - + " is empty"); + String emptyModelMessage = "model for updating engine service with key " + + incomingEngineServiceKey.getId() + " is empty"; + LOGGER.warn(emptyModelMessage); + throw new ApexException(emptyModelMessage); } // Read the Apex model into memory using the Apex Model Reader @@ -278,15 +262,15 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven final ApexModelReader modelReader = new ApexModelReader<>(AxPolicyModel.class); apexPolicyModel = modelReader.read(new ByteArrayInputStream(apexModelString.getBytes())); } catch (final ApexModelException e) { - LOGGER.error("failed to unmarshal the apex model on engine service " + incomingEngineServiceKey.getId(), e); - throw new ApexException( - "failed to unmarshal the apex model on engine service " + incomingEngineServiceKey.getId(), - e); + String message = "failed to unmarshal the apex model on engine service " + incomingEngineServiceKey.getId(); + LOGGER.error(message, e); + throw new ApexException(message, e); } if (apexPolicyModel == null) { - LOGGER.error("apex model null on engine service " + incomingEngineServiceKey.getId()); - throw new ApexException("apex model null on engine service " + incomingEngineServiceKey.getId()); + String message = "apex model null on engine service " + incomingEngineServiceKey.getId(); + LOGGER.error(message); + throw new ApexException(message); } // Update the model @@ -327,43 +311,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // The current policy model may or may not be defined final AxPolicyModel currentModel = ModelService.getModel(AxPolicyModel.class); if (!currentModel.getKey().isCompatible(apexModel.getKey())) { - if (forceFlag) { - LOGGER.warn("apex model update forced, supplied model with key \"" + apexModel.getKey().getId() - + "\" is not a compatible model update from the existing engine model with key \"" - + currentModel.getKey().getId() + "\""); - } else { - throw new ContextException("apex model update failed, supplied model with key \"" - + apexModel.getKey().getId() - + "\" is not a compatible model update from the existing engine model with key \"" - + currentModel.getKey().getId() + "\""); - } + handleIncompatibility(apexModel, forceFlag, currentModel); } } if (!isStopped()) { - // Stop all engines on this engine service - stop(); - final long stoptime = System.currentTimeMillis(); - while (!isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT_TIME) { - ThreadUtilities.sleep(ENGINE_SERVICE_STOP_START_WAIT_INTERVAL); - } - // Check if all engines are stopped - final StringBuilder notStoppedEngineIdBuilder = new StringBuilder(); - for (final Entry engineWorkerEntry : engineWorkerMap.entrySet()) { - if (engineWorkerEntry.getValue().getState() != AxEngineState.STOPPED) { - notStoppedEngineIdBuilder.append(engineWorkerEntry.getKey().getId()); - notStoppedEngineIdBuilder.append('('); - notStoppedEngineIdBuilder.append(engineWorkerEntry.getValue().getState()); - notStoppedEngineIdBuilder.append(") "); - } - } - if (notStoppedEngineIdBuilder.length() > 0) { - final String errorString = "cannot update model on engine service with key " - + incomingEngineServiceKey.getId() + ", engines not stopped after " + MAX_STOP_WAIT_TIME - + "ms are: " + notStoppedEngineIdBuilder.toString().trim(); - LOGGER.warn(errorString); - throw new ApexException(errorString); - } + stopEngines(incomingEngineServiceKey); } // Update the engines @@ -400,6 +353,58 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven LOGGER.exit(); } + /** + * Stop engines for a model update. + * @param incomingEngineServiceKey the engine service key for the engines that are to be stopped + * @throws ApexException on errors stopping engines + */ + private void stopEngines(final AxArtifactKey incomingEngineServiceKey) throws ApexException { + // Stop all engines on this engine service + stop(); + final long stoptime = System.currentTimeMillis(); + while (!isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT_TIME) { + ThreadUtilities.sleep(ENGINE_SERVICE_STOP_START_WAIT_INTERVAL); + } + // Check if all engines are stopped + final StringBuilder notStoppedEngineIdBuilder = new StringBuilder(); + for (final Entry engineWorkerEntry : engineWorkerMap.entrySet()) { + if (engineWorkerEntry.getValue().getState() != AxEngineState.STOPPED) { + notStoppedEngineIdBuilder.append(engineWorkerEntry.getKey().getId()); + notStoppedEngineIdBuilder.append('('); + notStoppedEngineIdBuilder.append(engineWorkerEntry.getValue().getState()); + notStoppedEngineIdBuilder.append(") "); + } + } + if (notStoppedEngineIdBuilder.length() > 0) { + final String errorString = "cannot update model on engine service with key " + + incomingEngineServiceKey.getId() + ", engines not stopped after " + MAX_STOP_WAIT_TIME + + "ms are: " + notStoppedEngineIdBuilder.toString().trim(); + LOGGER.warn(errorString); + throw new ApexException(errorString); + } + } + + /** + * Issue compatibility warning or error message. + * @param apexModel The model name + * @param forceFlag true if we are forcing the update + * @param currentModel the existing model that is loaded + * @throws ContextException on compatibility errors + */ + private void handleIncompatibility(final AxPolicyModel apexModel, final boolean forceFlag, + final AxPolicyModel currentModel) throws ContextException { + if (forceFlag) { + LOGGER.warn("apex model update forced, supplied model with key \"" + apexModel.getKey().getId() + + "\" is not a compatible model update from the existing engine model with key \"" + + currentModel.getKey().getId() + "\""); + } else { + throw new ContextException("apex model update failed, supplied model with key \"" + + apexModel.getKey().getId() + + "\" is not a compatible model update from the existing engine model with key \"" + + currentModel.getKey().getId() + "\""); + } + } + /* * (non-Javadoc) * @@ -446,8 +451,9 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); - throw new ApexException("engine with key " + engineKey.getId() + " not found in engine service"); + String message = ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX; + LOGGER.warn(message); + throw new ApexException(message); } // Start the engine @@ -487,8 +493,8 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); - throw new ApexException("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } // Stop the engine @@ -528,8 +534,8 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); - throw new ApexException("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } // Clear the engine @@ -566,7 +572,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public boolean isStarted(final AxArtifactKey engineKey) { // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } return engineWorkerMap.get(engineKey).isStarted(); } @@ -597,7 +603,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public boolean isStopped(final AxArtifactKey engineKey) { // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } return engineWorkerMap.get(engineKey).isStopped(); } @@ -611,10 +617,10 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public void startPeriodicEvents(final long period) throws ApexException { // Check if periodic events are already started if (periodicEventGenerator != null) { - LOGGER.warn("Peiodic event geneation already running on engine " + engineServiceKey.getId() + ", " - + periodicEventGenerator.toString()); - throw new ApexException("Peiodic event geneation already running on engine " + engineServiceKey.getId() - + ", " + periodicEventGenerator.toString()); + String message = "Peiodic event geneation already running on engine " + engineServiceKey.getId() + ", " + + periodicEventGenerator.toString(); + LOGGER.warn(message); + throw new ApexException(message); } // Set up periodic event execution, its a Java Timer/TimerTask @@ -653,8 +659,8 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public String getStatus(final AxArtifactKey engineKey) throws ApexException { // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); - throw new ApexException("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } // Return the information for this worker @@ -671,8 +677,8 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public String getRuntimeInfo(final AxArtifactKey engineKey) throws ApexException { // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn("engine with key " + engineKey.getId() + " not found in engine service"); - throw new ApexException("engine with key " + engineKey.getId() + " not found in engine service"); + LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); } // Return the information for this worker diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java index b9a405b44..dc5e91979 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java @@ -75,6 +75,13 @@ final class EngineWorker implements EngineService { // Logger for this class private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineService.class); + // Recurring string constants + private static final String IS_NULL_SUFFIX = " is null"; + private static final String ENGINE_FOR_KEY_PREFIX = "apex engine for engine key "; + private static final String ENGINE_SUFFIX = " of this engine"; + private static final String BAD_KEY_MATCH_TAG = " does not match the key"; + private static final String ENGINE_KEY_PREFIX = "engine key "; + // The ID of this engine private final AxArtifactKey engineWorkerKey; @@ -102,7 +109,7 @@ final class EngineWorker implements EngineService { * @throws ApexException thrown on errors on worker instantiation */ EngineWorker(final AxArtifactKey engineWorkerKey, final BlockingQueue queue, - final ApplicationThreadFactory threadFactory) throws ApexException { + final ApplicationThreadFactory threadFactory) { LOGGER.entry(engineWorkerKey); this.engineWorkerKey = engineWorkerKey; @@ -252,10 +259,10 @@ final class EngineWorker implements EngineService { // Check if the key on the update request is correct if (!engineWorkerKey.equals(engineKey)) { - LOGGER.warn("engine key " + engineKey.getId() + " does not match the key" + engineWorkerKey.getId() - + " of this engine"); - throw new ApexException("engine key " + engineKey.getId() + " does not match the key" - + engineWorkerKey.getId() + " of this engine"); + String message = ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + + ENGINE_SUFFIX; + LOGGER.warn(message); + throw new ApexException(message); } // Sanity checks on the Apex model @@ -323,23 +330,24 @@ final class EngineWorker implements EngineService { // Check if the key on the start request is correct if (!engineWorkerKey.equals(engineKey)) { - LOGGER.warn("engine key " + engineKey.getId() + " does not match the key" + engineWorkerKey.getId() - + " of this engine"); - throw new ApexException("engine key " + engineKey.getId() + " does not match the key" - + engineWorkerKey.getId() + " of this engine"); + LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + + ENGINE_SUFFIX); + throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + + engineWorkerKey.getId() + ENGINE_SUFFIX); } if (engine == null) { - LOGGER.error("apex engine for engine key" + engineWorkerKey.getId() + " null"); - throw new ApexException("apex engine for engine key" + engineWorkerKey.getId() + " null"); + String message = ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is null"; + LOGGER.error(message); + throw new ApexException(message); } // Starts the event processing thread that handles incoming events if (processorThread != null && processorThread.isAlive()) { - LOGGER.error("apex engine for engine key" + engineWorkerKey.getId() + " is already running with state " - + getState()); - throw new ApexException("apex engine for engine key" + engineWorkerKey.getId() - + " is already running with state " + getState()); + String message = ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already running with state " + + getState(); + LOGGER.error(message); + throw new ApexException(message); } // Start the engine @@ -373,22 +381,23 @@ final class EngineWorker implements EngineService { public void stop(final AxArtifactKey engineKey) throws ApexException { // Check if the key on the start request is correct if (!engineWorkerKey.equals(engineKey)) { - LOGGER.warn("engine key " + engineKey.getId() + " does not match the key" + engineWorkerKey.getId() - + " of this engine"); - throw new ApexException("engine key " + engineKey.getId() + " does not match the key" - + engineWorkerKey.getId() + " of this engine"); + LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + + ENGINE_SUFFIX); + throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + + engineWorkerKey.getId() + ENGINE_SUFFIX); } if (engine == null) { - LOGGER.error("apex engine for engine key" + engineWorkerKey.getId() + " null"); - throw new ApexException("apex engine for engine key" + engineWorkerKey.getId() + " null"); + String message = ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is null"; + LOGGER.error(message); + throw new ApexException(message); } // Interrupt the worker to stop its thread if (processorThread == null || !processorThread.isAlive()) { processorThread = null; - LOGGER.warn("apex engine for engine key" + engineWorkerKey.getId() + " is already stopped with state " + LOGGER.warn(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already stopped with state " + getState()); return; } @@ -424,20 +433,20 @@ final class EngineWorker implements EngineService { public void clear(final AxArtifactKey engineKey) throws ApexException { // Check if the key on the start request is correct if (!engineWorkerKey.equals(engineKey)) { - LOGGER.warn("engine key " + engineKey.getId() + " does not match the key" + engineWorkerKey.getId() - + " of this engine"); - throw new ApexException("engine key " + engineKey.getId() + " does not match the key" - + engineWorkerKey.getId() + " of this engine"); + LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId() + + ENGINE_SUFFIX); + throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + + engineWorkerKey.getId() + ENGINE_SUFFIX); } if (engine == null) { - LOGGER.error("apex engine for engine key" + engineWorkerKey.getId() + " null"); - throw new ApexException("apex engine for engine key" + engineWorkerKey.getId() + " null"); + LOGGER.error(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + IS_NULL_SUFFIX); + throw new ApexException(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + IS_NULL_SUFFIX); } // Interrupt the worker to stop its thread if (processorThread != null && !processorThread.isAlive()) { - LOGGER.warn("apex engine for engine key" + engineWorkerKey.getId() + " is not stopped with state " + LOGGER.warn(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is not stopped with state " + getState()); return; } @@ -653,7 +662,7 @@ final class EngineWorker implements EngineService { final JsonElement jsonElement = jsonParser.parse(runtimeJsonStringBuilder.toString()); final String tidiedRuntimeString = gson.toJson(jsonElement); - LOGGER.debug("runtime information=" + tidiedRuntimeString); + LOGGER.debug("runtime information={}", tidiedRuntimeString); return tidiedRuntimeString; } @@ -691,7 +700,8 @@ final class EngineWorker implements EngineService { // Take events from the event processing queue of the worker and pass them to the engine // for processing - while (!processorThread.isInterrupted()) { + boolean stopFlag = false; + while (!processorThread.isInterrupted() && ! stopFlag) { ApexEvent event = null; try { event = eventProcessingQueue.take(); @@ -714,7 +724,7 @@ final class EngineWorker implements EngineService { LOGGER.warn("Engine {} failed to process event {}", engineWorkerKey, event.toString(), e); } catch (final Exception e) { LOGGER.warn("Engine {} terminated processing event {}", engineWorkerKey, event.toString(), e); - break; + stopFlag = true; } } LOGGER.debug("Engine {} completed processing", engineWorkerKey); 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 2e8e66ae8..4312793e4 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 @@ -20,18 +20,18 @@ package org.onap.policy.apex.service.parameters; -import java.io.FileReader; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import java.io.FileReader; + import org.onap.policy.apex.core.engine.EngineParameters; import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments; import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters; -import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParametersJSONAdapter; -import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParametersJSONAdapter; +import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParametersJsonAdapter; +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.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; @@ -56,7 +56,7 @@ public class ApexParameterHandler { public ApexParameters getParameters(final ApexCommandLineArguments arguments) throws ParameterException { // Clear all existing parameters ParameterService.clear(); - + ApexParameters parameters = null; // Read the parameters @@ -65,11 +65,11 @@ public class ApexParameterHandler { // @formatter:off final Gson gson = new GsonBuilder() .registerTypeAdapter(EngineParameters .class, - new EngineServiceParametersJSONAdapter()) + new EngineServiceParametersJsonAdapter()) .registerTypeAdapter(CarrierTechnologyParameters.class, - new CarrierTechnologyParametersJSONAdapter()) + new CarrierTechnologyParametersJsonAdapter()) .registerTypeAdapter(EventProtocolParameters .class, - new EventProtocolParametersJSONAdapter()) + new EventProtocolParametersJsonAdapter()) .create(); // @formatter:on parameters = gson.fromJson(new FileReader(arguments.getFullConfigurationFilePath()), ApexParameters.class); @@ -114,12 +114,13 @@ public class ApexParameterHandler { // Register the parameters with the parameter service registerParameters(parameters); - + return parameters; } /** - * Register all the incoming parameters with the parameter service + * Register all the incoming parameters with the parameter service. + * * @param parameters The parameters to register */ private void registerParameters(ApexParameters parameters) { @@ -127,9 +128,13 @@ public class ApexParameterHandler { 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()); + 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/ApexParameters.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/ApexParameters.java index 87b86a897..907baad40 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 @@ -37,16 +37,11 @@ import org.onap.policy.common.parameters.ValidationStatus; /** * The main container parameter class for an Apex service. * - *

- * The following parameters are defined: - *

    - *
  1. 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. - *
  2. eventOutputParameters: A map of parameters for event outputs that Apex will use to emit events. Apex emits events - * on all outputs + *

    The following parameters are defined:

    1. 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.
    2. eventOutputParameters: + * A map of parameters for event outputs that Apex will use to emit events. Apex emits events on all outputs *
    3. eventInputParameters: A map or parameters for event inputs from which Apex will consume events. Apex reads events - * from all its event inputs. - *
    + * from all its event inputs.
* * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -59,13 +54,13 @@ public class ApexParameters implements ParameterGroup { 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. */ public ApexParameters() { super(); - + // Set the name for the parameters this.name = ApexParameterConstants.MAIN_GROUP_NAME; } @@ -235,9 +230,8 @@ public class ApexParameters implements ParameterGroup { } } else { if (peer != null) { - result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, - messagePreamble + " peer is illegal on " + eventHandlerType + " \"" - + parameterEntry.getKey() + "\" "); + result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, messagePreamble + + " peer is illegal on " + eventHandlerType + " \"" + parameterEntry.getKey() + "\" "); } if (parameterEntry.getValue().getPeerTimeout(peeredMode) != 0) { result.setResult(eventHandlerType, parameterEntry.getKey(), ValidationStatus.INVALID, @@ -315,10 +309,10 @@ public class ApexParameters implements ParameterGroup { final String rightSidePeer = rightModeParameters.getPeer(peeredMode); if (!rightSidePeer.equals(leftModeParameterEntry.getKey())) { 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() - + "\""); + 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)) { @@ -339,12 +333,12 @@ public class ApexParameters implements ParameterGroup { 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() + "\""); + 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() + "\""); } } 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 593c6d86f..bab76b59b 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 @@ -29,14 +29,10 @@ 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 following parameters are defined: - *

    - *
  1. label: The label of the carrier technology. + *

    The following parameters are defined:

    1. label: The label of the carrier technology. *
    2. eventProducerPluginClass: The name of the plugin class that will be used by Apex to produce and emit output - * events for this carrier technology - *
    3. 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 - *
    + * events for this carrier technology
  2. 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
* * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -160,7 +156,7 @@ public abstract class CarrierTechnologyParameters implements ParameterGroup { return result; } - + @Override public String getName() { return this.getLabel(); @@ -168,7 +164,8 @@ public abstract class CarrierTechnologyParameters implements ParameterGroup { @Override public void setName(final String name) { - throw new ParameterRuntimeException("the name/label of this carrier technology is always \"" + getLabel() + "\""); + 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 deleted file mode 100644 index b4e342f17..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJSONAdapter.java +++ /dev/null @@ -1,177 +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.carriertechnology; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -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.common.parameters.ParameterRuntimeException; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class deserialises various type of carrier technology parameters from JSON. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class CarrierTechnologyParametersJSONAdapter - implements JsonSerializer, JsonDeserializer { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(CarrierTechnologyParametersJSONAdapter.class); - - private static final String PARAMETER_CLASS_NAME = "parameterClassName"; - - private static final String CARRIER_TECHNOLOGY_TOKEN = "carrierTechnology"; - private static final String CARRIER_TECHNOLOGY_PARAMETERS = "parameters"; - - // Built in technology parameters - private static final Map BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP = new HashMap<>(); - - static { - BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("FILE", - FILECarrierTechnologyParameters.class.getCanonicalName()); - BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("EVENT_REQUESTOR", - EventRequestorCarrierTechnologyParameters.class.getCanonicalName()); - } - - /* - * (non-Javadoc) - * - * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, - * com.google.gson.JsonSerializationContext) - */ - @Override - public JsonElement serialize(final CarrierTechnologyParameters src, final Type typeOfSrc, - final JsonSerializationContext context) { - final String returnMessage = "serialization of Apex carrier technology parameters to Json is not supported"; - LOGGER.error(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) - */ - @Override - public CarrierTechnologyParameters deserialize(final JsonElement json, final Type typeOfT, - final JsonDeserializationContext context) { - final JsonObject jsonObject = json.getAsJsonObject(); - - // Get the carrier technology label primitive - final JsonPrimitive labelJsonPrimitive = (JsonPrimitive) jsonObject.get(CARRIER_TECHNOLOGY_TOKEN); - - // Check if we found our carrier technology - if (labelJsonPrimitive == null) { - LOGGER.warn("carrier technology parameter \"" + CARRIER_TECHNOLOGY_TOKEN + "\" not found in JSON file"); - return null; - } - - // Get and check the carrier technology label - final String carrierTechnologyLabel = labelJsonPrimitive.getAsString().replaceAll("\\s+", ""); - if (carrierTechnologyLabel == null || carrierTechnologyLabel.length() == 0) { - final String errorMessage = "carrier technology parameter \"" + CARRIER_TECHNOLOGY_TOKEN + "\" value \"" - + labelJsonPrimitive.getAsString() + "\" invalid in JSON file"; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - // We now get the technology carrier parameter class - String carrierTechnologyParameterClassName = null; - - // Get the technology carrier parameter class for the carrier technology plugin class from - // the configuration parameters - final JsonPrimitive classNameJsonPrimitive = (JsonPrimitive) jsonObject.get(PARAMETER_CLASS_NAME); - - // If no technology carrier parameter class was specified, we try to use a built in carrier - // technology - if (classNameJsonPrimitive == null) { - carrierTechnologyParameterClassName = - BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.get(carrierTechnologyLabel); - } else { - // We use the specified one - carrierTechnologyParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", ""); - } - - // Check the carrier technology parameter class - if (carrierTechnologyParameterClassName == null || carrierTechnologyParameterClassName.length() == 0) { - final String errorMessage = "carrier technology \"" + carrierTechnologyLabel + "\" parameter \"" - + PARAMETER_CLASS_NAME + "\" value \"" - + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null") - + "\" invalid in JSON file"; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - // Get the class for the carrier technology - Class carrierTechnologyParameterClass = null; - try { - carrierTechnologyParameterClass = Class.forName(carrierTechnologyParameterClassName); - } catch (final ClassNotFoundException e) { - final String errorMessage = - "carrier technology \"" + carrierTechnologyLabel + "\" parameter \"" + PARAMETER_CLASS_NAME - + "\" value \"" + carrierTechnologyParameterClassName + "\", could not find class"; - LOGGER.warn(errorMessage, e); - throw new ParameterRuntimeException(errorMessage, e); - } - - // Deserialise the class - CarrierTechnologyParameters carrierTechnologyParameters = - context.deserialize(jsonObject.get(CARRIER_TECHNOLOGY_PARAMETERS), carrierTechnologyParameterClass); - if (carrierTechnologyParameters == null) { - // OK no parameters for the carrier technology have been specified, just instantiate the - // default parameters - try { - carrierTechnologyParameters = - (CarrierTechnologyParameters) carrierTechnologyParameterClass.newInstance(); - } catch (final Exception e) { - final String errorMessage = "could not create default parameters for carrier technology \"" - + carrierTechnologyLabel + "\"\n" + e.getMessage(); - LOGGER.warn(errorMessage, e); - throw new ParameterRuntimeException(errorMessage, e); - } - } - - // Check that the carrier technology label matches the label in the carrier technology - // parameters object - if (!carrierTechnologyParameters.getLabel().equals(carrierTechnologyLabel)) { - final String errorMessage = "carrier technology \"" + carrierTechnologyLabel + "\" does not match plugin \"" - + carrierTechnologyParameters.getLabel() + "\" in \"" + carrierTechnologyParameterClassName - + "\", specify correct carrier technology parameter plugin in parameter \"" + PARAMETER_CLASS_NAME - + "\""; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - return carrierTechnologyParameters; - } -} 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 new file mode 100644 index 000000000..5e320b1bb --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/carriertechnology/CarrierTechnologyParametersJsonAdapter.java @@ -0,0 +1,184 @@ +/*- + * ============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.carriertechnology; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; +import java.util.HashMap; +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.common.parameters.ParameterRuntimeException; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class deserialises various type of carrier technology parameters from JSON. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class CarrierTechnologyParametersJsonAdapter + implements JsonSerializer, JsonDeserializer { + + private static final XLogger LOGGER = XLoggerFactory.getXLogger(CarrierTechnologyParametersJsonAdapter.class); + + // Recurring string constants + private static final String VALUE_TAG = "\" value \""; + private static final String CARRIER_TECHNOLOGY_PREAMBLE = "carrier technology \""; + + + private static final String PARAMETER_CLASS_NAME = "parameterClassName"; + + private static final String CARRIER_TECHNOLOGY_TOKEN = "carrierTechnology"; + private static final String CARRIER_TECHNOLOGY_PARAMETERS = "parameters"; + + // Built in technology parameters + private static final Map BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP = new HashMap<>(); + + static { + BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("FILE", + FileCarrierTechnologyParameters.class.getCanonicalName()); + BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.put("EVENT_REQUESTOR", + EventRequestorCarrierTechnologyParameters.class.getCanonicalName()); + } + + /* + * (non-Javadoc) + * + * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, + * com.google.gson.JsonSerializationContext) + */ + @Override + public JsonElement serialize(final CarrierTechnologyParameters src, final Type typeOfSrc, + final JsonSerializationContext context) { + final String returnMessage = "serialization of Apex carrier technology parameters to Json is not supported"; + LOGGER.error(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) + */ + @Override + public CarrierTechnologyParameters deserialize(final JsonElement json, final Type typeOfT, + final JsonDeserializationContext context) { + final JsonObject jsonObject = json.getAsJsonObject(); + + // Get the carrier technology label primitive + final JsonPrimitive labelJsonPrimitive = (JsonPrimitive) jsonObject.get(CARRIER_TECHNOLOGY_TOKEN); + + // Check if we found our carrier technology + if (labelJsonPrimitive == null) { + LOGGER.warn("carrier technology parameter \"" + CARRIER_TECHNOLOGY_TOKEN + "\" not found in JSON file"); + return null; + } + + // Get and check the carrier technology label + final String carrierTechnologyLabel = labelJsonPrimitive.getAsString().replaceAll("\\s+", ""); + if (carrierTechnologyLabel == null || carrierTechnologyLabel.length() == 0) { + final String errorMessage = "carrier technology parameter \"" + CARRIER_TECHNOLOGY_TOKEN + VALUE_TAG + + labelJsonPrimitive.getAsString() + "\" invalid in JSON file"; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + // We now get the technology carrier parameter class + String carrierTechnologyParameterClassName = null; + + // Get the technology carrier parameter class for the carrier technology plugin class from + // the configuration parameters + final JsonPrimitive classNameJsonPrimitive = (JsonPrimitive) jsonObject.get(PARAMETER_CLASS_NAME); + + // If no technology carrier parameter class was specified, we try to use a built in carrier + // technology + if (classNameJsonPrimitive == null) { + carrierTechnologyParameterClassName = + BUILT_IN_CARRIER_TECHNOLOGY_PARMETER_CLASS_MAP.get(carrierTechnologyLabel); + } else { + // We use the specified one + carrierTechnologyParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", ""); + } + + // Check the carrier technology parameter class + if (carrierTechnologyParameterClassName == null || carrierTechnologyParameterClassName.length() == 0) { + final String errorMessage = CARRIER_TECHNOLOGY_PREAMBLE + carrierTechnologyLabel + "\" parameter \"" + + PARAMETER_CLASS_NAME + VALUE_TAG + + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null") + + "\" invalid in JSON file"; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + // Get the class for the carrier technology + Class carrierTechnologyParameterClass = null; + try { + carrierTechnologyParameterClass = Class.forName(carrierTechnologyParameterClassName); + } catch (final ClassNotFoundException e) { + final String errorMessage = + CARRIER_TECHNOLOGY_PREAMBLE + carrierTechnologyLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + + VALUE_TAG + carrierTechnologyParameterClassName + "\", could not find class"; + LOGGER.warn(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); + } + + // Deserialise the class + CarrierTechnologyParameters carrierTechnologyParameters = + context.deserialize(jsonObject.get(CARRIER_TECHNOLOGY_PARAMETERS), carrierTechnologyParameterClass); + if (carrierTechnologyParameters == null) { + // OK no parameters for the carrier technology have been specified, just instantiate the + // default parameters + try { + carrierTechnologyParameters = + (CarrierTechnologyParameters) carrierTechnologyParameterClass.newInstance(); + } catch (final Exception e) { + final String errorMessage = "could not create default parameters for carrier technology \"" + + carrierTechnologyLabel + "\"\n" + e.getMessage(); + LOGGER.warn(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); + } + } + + // Check that the carrier technology label matches the label in the carrier technology + // parameters object + if (!carrierTechnologyParameters.getLabel().equals(carrierTechnologyLabel)) { + final String errorMessage = CARRIER_TECHNOLOGY_PREAMBLE + carrierTechnologyLabel + + "\" does not match plugin \"" + + carrierTechnologyParameters.getLabel() + "\" in \"" + carrierTechnologyParameterClassName + + "\", specify correct carrier technology parameter plugin in parameter \"" + PARAMETER_CLASS_NAME + + "\""; + LOGGER.warn(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 ba065d3ef..faa6d79b3 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 @@ -23,6 +23,7 @@ package org.onap.policy.apex.service.parameters.engineservice; import java.io.File; import java.net.URL; +import org.onap.policy.apex.core.engine.EngineParameters; import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.basicmodel.concepts.AxKey; import org.onap.policy.apex.service.parameters.ApexParameterConstants; @@ -31,8 +32,6 @@ 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. * @@ -315,7 +314,7 @@ public class EngineServiceParameters implements ParameterGroup { } /** - * Validate the policy model file name parameter + * 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) { @@ -327,11 +326,11 @@ public class EngineServiceParameters implements ParameterGroup { // 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) { + 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()); + 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 deleted file mode 100644 index 50f4925f3..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJSONAdapter.java +++ /dev/null @@ -1,283 +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.engineservice; - -import java.lang.reflect.Type; -import java.util.Map.Entry; - -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.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.DistributorParameters; -import org.onap.policy.apex.context.parameters.LockManagerParameters; -import org.onap.policy.apex.context.parameters.PersistorParameters; -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.common.parameters.ParameterGroup; -import org.onap.policy.common.parameters.ParameterRuntimeException; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * 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. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EngineServiceParametersJSONAdapter - implements JsonSerializer, JsonDeserializer { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineServiceParametersJSONAdapter.class); - - private static final String PARAMETER_CLASS_NAME = "parameterClassName"; - - // @formatter:off - private static final String CONTEXT_PARAMETERS = "contextParameters"; - private static final String DISTRIBUTOR_PARAMETERS = "distributorParameters"; - private static final String LOCK_MANAGER_PARAMETERS = "lockManagerParameters"; - private static final String PERSISTOR_PARAMETERS = "persistorParameters"; - private static final String SCHEMA_PARAMETERS = "schemaParameters"; - private static final String EXECUTOR_PARAMETERS = "executorParameters"; - // @formatter:on - - /* - * (non-Javadoc) - * - * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, - * com.google.gson.JsonSerializationContext) - */ - @Override - public JsonElement serialize(final EngineParameters src, final Type typeOfSrc, - final JsonSerializationContext context) { - final String returnMessage = "serialization of Apex parameters to Json is not supported"; - LOGGER.error(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) - */ - @Override - public EngineParameters deserialize(final JsonElement json, final Type typeOfT, - 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)); - - // Context parameter wrangling - getContextParameters(engineParametersJsonObject, engineParameters, context); - - // Executor parameter wrangling - getExecutorParameters(engineParametersJsonObject, engineParameters, context); - - return engineParameters; - } - - /** - * Get the context parameters for Apex. - * - * @param engineParametersJsonObject The input JSON - * @param engineParameters The output parameters - * @param context the JSON context - */ - private void getContextParameters(final JsonObject engineParametersJsonObject, - 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 - if (contextParametersElement == null) { - return; - } - - // We do this because the JSON parameters may be for a subclass of ContextParameters - 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 - final JsonObject contextParametersObject = engineParametersJsonObject.get(CONTEXT_PARAMETERS).getAsJsonObject(); - - // 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)); - } - - final JsonElement lockManagerParametersElement = contextParametersObject.get(LOCK_MANAGER_PARAMETERS); - if (lockManagerParametersElement != null) { - 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)); - } - - // Schema Handler parameter wrangling - getSchemaHandlerParameters(contextParametersObject, contextParameters, context); - - // Get the engine plugin parameters - engineParameters.setContextParameters(contextParameters); - } - - /** - * Get the executor parameters for Apex. - * - * @param engineParametersJsonObject The input JSON - * @param engineParameters The output parameters - * @param context the JSON context - */ - private void getExecutorParameters(final JsonObject engineParametersJsonObject, - 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"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - // Deserialize the executor parameters - final JsonObject executorParametersJsonObject = engineParametersJsonObject.get(EXECUTOR_PARAMETERS) - .getAsJsonObject(); - - for (final Entry executorEntries : executorParametersJsonObject.entrySet()) { - final ExecutorParameters executorParameters = (ExecutorParameters) deserializeParameters( - EXECUTOR_PARAMETERS + ':' + executorEntries.getKey(), executorEntries.getValue(), context); - engineParameters.getExecutorParameterMap().put(executorEntries.getKey(), executorParameters); - } - } - - /** - * Get the schema parameters for Apex. - * - * @param contextParametersJsonObject The input JSON - * @param contextParameters The output parameters - * @param context the JSON context - */ - private void getSchemaHandlerParameters(final JsonObject contextParametersJsonObject, - 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()); - - // Context parameters are optional so if the element does not exist, just return - if (schemaParametersElement == null) { - return; - } - - // Deserialize the executor parameters - final JsonObject schemaHelperParametersJsonObject = contextParametersJsonObject.get(SCHEMA_PARAMETERS) - .getAsJsonObject(); - - for (final Entry schemaHelperEntries : schemaHelperParametersJsonObject.entrySet()) { - contextParameters.getSchemaParameters().getSchemaHelperParameterMap().put(schemaHelperEntries.getKey(), - (SchemaHelperParameters) deserializeParameters( - SCHEMA_PARAMETERS + ':' + schemaHelperEntries.getKey(), - schemaHelperEntries.getValue(), context)); - } - } - - /** - * Deserialize a parameter object that's a superclass of the AbstractParameters class. - * - * @param parametersLabel Label to use for error messages - * @param parametersElement The JSON object holding the parameters - * @param context The GSON context - * @return the parameters - * @throws ParameterRuntimeException on errors reading the parameters - */ - private ParameterGroup deserializeParameters(final String parametersLabel, final JsonElement parametersElement, - final JsonDeserializationContext context) { - JsonObject parametersObject = null; - - // Check that the JSON element is a JSON object - if (parametersElement.isJsonObject()) { - parametersObject = parametersElement.getAsJsonObject(); - } else { - final String returnMessage = "value of \"" + parametersLabel + "\" entry is not a parameter JSON object"; - LOGGER.error(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"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - // Check the parameter is a JSON primitive - if (!parameterClassNameElement.isJsonPrimitive()) { - final String returnMessage = "value for field \"" + PARAMETER_CLASS_NAME + "\" of \"" + parametersLabel - + "\" entry is not a plain string"; - LOGGER.error(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"; - LOGGER.error(returnMessage); - throw new ParameterRuntimeException(returnMessage); - } - - // Deserialize the parameters using GSON - 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(); - LOGGER.error(returnMessage, e); - throw new ParameterRuntimeException(returnMessage, e); - } - - return parameters; - } -} 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 new file mode 100644 index 000000000..06cbd416f --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/engineservice/EngineServiceParametersJsonAdapter.java @@ -0,0 +1,283 @@ +/*- + * ============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.engineservice; + +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.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; +import java.util.Map.Entry; + +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.DistributorParameters; +import org.onap.policy.apex.context.parameters.LockManagerParameters; +import org.onap.policy.apex.context.parameters.PersistorParameters; +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.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ParameterRuntimeException; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * 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. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class EngineServiceParametersJsonAdapter + implements JsonSerializer, JsonDeserializer { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineServiceParametersJsonAdapter.class); + + private static final String PARAMETER_CLASS_NAME = "parameterClassName"; + + // @formatter:off + private static final String CONTEXT_PARAMETERS = "contextParameters"; + private static final String DISTRIBUTOR_PARAMETERS = "distributorParameters"; + private static final String LOCK_MANAGER_PARAMETERS = "lockManagerParameters"; + private static final String PERSISTOR_PARAMETERS = "persistorParameters"; + private static final String SCHEMA_PARAMETERS = "schemaParameters"; + private static final String EXECUTOR_PARAMETERS = "executorParameters"; + // @formatter:on + + /* + * (non-Javadoc) + * + * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, + * com.google.gson.JsonSerializationContext) + */ + @Override + public JsonElement serialize(final EngineParameters src, final Type typeOfSrc, + final JsonSerializationContext context) { + final String returnMessage = "serialization of Apex parameters to Json is not supported"; + LOGGER.error(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) + */ + @Override + public EngineParameters deserialize(final JsonElement json, final Type typeOfT, + 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)); + + // Context parameter wrangling + getContextParameters(engineParametersJsonObject, engineParameters, context); + + // Executor parameter wrangling + getExecutorParameters(engineParametersJsonObject, engineParameters, context); + + return engineParameters; + } + + /** + * Get the context parameters for Apex. + * + * @param engineParametersJsonObject The input JSON + * @param engineParameters The output parameters + * @param context the JSON context + */ + private void getContextParameters(final JsonObject engineParametersJsonObject, + 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 + if (contextParametersElement == null) { + return; + } + + // We do this because the JSON parameters may be for a subclass of ContextParameters + 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 + final JsonObject contextParametersObject = engineParametersJsonObject.get(CONTEXT_PARAMETERS).getAsJsonObject(); + + // 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)); + } + + final JsonElement lockManagerParametersElement = contextParametersObject.get(LOCK_MANAGER_PARAMETERS); + if (lockManagerParametersElement != null) { + 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)); + } + + // Schema Handler parameter wrangling + getSchemaHandlerParameters(contextParametersObject, contextParameters, context); + + // Get the engine plugin parameters + engineParameters.setContextParameters(contextParameters); + } + + /** + * Get the executor parameters for Apex. + * + * @param engineParametersJsonObject The input JSON + * @param engineParameters The output parameters + * @param context the JSON context + */ + private void getExecutorParameters(final JsonObject engineParametersJsonObject, + 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"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + // Deserialize the executor parameters + final JsonObject executorParametersJsonObject = engineParametersJsonObject.get(EXECUTOR_PARAMETERS) + .getAsJsonObject(); + + for (final Entry executorEntries : executorParametersJsonObject.entrySet()) { + final ExecutorParameters executorParameters = (ExecutorParameters) deserializeParameters( + EXECUTOR_PARAMETERS + ':' + executorEntries.getKey(), executorEntries.getValue(), context); + engineParameters.getExecutorParameterMap().put(executorEntries.getKey(), executorParameters); + } + } + + /** + * Get the schema parameters for Apex. + * + * @param contextParametersJsonObject The input JSON + * @param contextParameters The output parameters + * @param context the JSON context + */ + private void getSchemaHandlerParameters(final JsonObject contextParametersJsonObject, + 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()); + + // Context parameters are optional so if the element does not exist, just return + if (schemaParametersElement == null) { + return; + } + + // Deserialize the executor parameters + final JsonObject schemaHelperParametersJsonObject = contextParametersJsonObject.get(SCHEMA_PARAMETERS) + .getAsJsonObject(); + + for (final Entry schemaHelperEntries : schemaHelperParametersJsonObject.entrySet()) { + contextParameters.getSchemaParameters().getSchemaHelperParameterMap().put(schemaHelperEntries.getKey(), + (SchemaHelperParameters) deserializeParameters( + SCHEMA_PARAMETERS + ':' + schemaHelperEntries.getKey(), + schemaHelperEntries.getValue(), context)); + } + } + + /** + * Deserialize a parameter object that's a superclass of the AbstractParameters class. + * + * @param parametersLabel Label to use for error messages + * @param parametersElement The JSON object holding the parameters + * @param context The GSON context + * @return the parameters + * @throws ParameterRuntimeException on errors reading the parameters + */ + private ParameterGroup deserializeParameters(final String parametersLabel, final JsonElement parametersElement, + final JsonDeserializationContext context) { + JsonObject parametersObject = null; + + // Check that the JSON element is a JSON object + if (parametersElement.isJsonObject()) { + parametersObject = parametersElement.getAsJsonObject(); + } else { + final String returnMessage = "value of \"" + parametersLabel + "\" entry is not a parameter JSON object"; + LOGGER.error(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"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + // Check the parameter is a JSON primitive + if (!parameterClassNameElement.isJsonPrimitive()) { + final String returnMessage = "value for field \"" + PARAMETER_CLASS_NAME + "\" of \"" + parametersLabel + + "\" entry is not a plain string"; + LOGGER.error(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"; + LOGGER.error(returnMessage); + throw new ParameterRuntimeException(returnMessage); + } + + // Deserialize the parameters using GSON + 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(); + LOGGER.error(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 996899052..afd877fd2 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 @@ -33,26 +33,20 @@ import org.onap.policy.common.parameters.ValidationStatus; /** * The parameters for a single event producer, event consumer or synchronous event handler. * - *

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. + *

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. * - *

The following parameters are defined: - *

    - *
  1. carrierTechnologyParameters: The carrier technology is the type of messaging infrastructure used to carry events. - * Examples are File, Kafka or REST. - *
  2. eventProtocolParameters: The format that the events are in when being carried. Examples are JSON, XML, or Java - * Beans. carrier technology - *
  3. synchronousMode: true if the event handler is working in synchronous mode, defaults to false - *
  4. synchronousPeer: the peer event handler (consumer for producer or producer for consumer) of this event handler in - * synchronous mode + *

    The following parameters are defined:

    1. carrierTechnologyParameters: The carrier technology is the type of + * messaging infrastructure used to carry events. Examples are File, Kafka or REST.
    2. eventProtocolParameters: The + * format that the events are in when being carried. Examples are JSON, XML, or Java Beans. carrier technology + *
    3. synchronousMode: true if the event handler is working in synchronous mode, defaults to false
    4. synchronousPeer: + * the peer event handler (consumer for producer or producer for consumer) of this event handler in synchronous mode *
    5. synchronousTimeout: the amount of time to wait for the reply to synchronous events before they are timed out - *
    6. requestorMode: true if the event handler is working in requestor mode, defaults to false - *
    7. requestorPeer: the peer event handler (consumer for producer or producer for consumer) of this event handler in - * requestor mode + *
    8. requestorMode: true if the event handler is working in requestor mode, defaults to false
    9. requestorPeer: the + * peer event handler (consumer for producer or producer for consumer) of this event handler in requestor mode *
    10. requestorTimeout: the amount of time to wait for the reply to synchronous events before they are timed out *
    11. 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. - *
    + * the given regular expression are ignored. If it is null, all events are handledDefaults to null.
* * @author Liam Fallon (liam.fallon@ericsson.com) */ @@ -340,7 +334,7 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * Check if we're using synchronous mode + * Check if we're using synchronous mode. * * @return true if if we're using synchronous mode */ @@ -349,7 +343,8 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * The synchronous peer for this event handler + * The synchronous peer for this event handler. + * * @return the synchronous peer for this event handler */ public String getSynchronousPeer() { @@ -357,7 +352,8 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * Get the timeout for synchronous operations + * Get the timeout for synchronous operations. + * * @return the timeout for synchronous operations */ public long getSynchronousTimeout() { @@ -365,7 +361,8 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * Check if this event handler will use requestor mode + * Check if this event handler will use requestor mode. + * * @return true if this event handler will use requestor mode */ public boolean isRequestorMode() { @@ -373,7 +370,8 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * The requestor peer for this event handler + * The requestor peer for this event handler. + * * @return the requestor peer for this event handler */ public String getRequestorPeer() { @@ -381,7 +379,8 @@ public class EventHandlerParameters implements ParameterGroup { } /** - * @return the requestorTimeout + * Get the requestor timeout. + * @return the requestorTimeout. */ public long getRequestorTimeout() { return requestorTimeout; 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 deleted file mode 100644 index 645368509..000000000 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJSONAdapter.java +++ /dev/null @@ -1,173 +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.eventprotocol; - -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.JsonSerializer; - -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.common.parameters.ParameterRuntimeException; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class serialises and deserialises various type of event protocol parameters to and from - * JSON. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EventProtocolParametersJSONAdapter - implements JsonSerializer, JsonDeserializer { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventProtocolParametersJSONAdapter.class); - - private static final String PARAMETER_CLASS_NAME = "parameterClassName"; - - private static final String EVENT_PROTOCOL_TOKEN = "eventProtocol"; - private static final String EVENT_PROTOCOL_PARAMETERS = "parameters"; - - // Built in event protocol parameters - private static final Map BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP = new HashMap<>(); - - static { - BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.put("JSON", JSONEventProtocolParameters.class.getCanonicalName()); - BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.put("APEX", ApexEventProtocolParameters.class.getCanonicalName()); - } - - /* - * (non-Javadoc) - * - * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, - * com.google.gson.JsonSerializationContext) - */ - @Override - public JsonElement serialize(final EventProtocolParameters src, final Type typeOfSrc, - final JsonSerializationContext context) { - final String returnMessage = "serialization of Apex event protocol parameters to Json is not supported"; - LOGGER.error(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) - */ - @Override - public EventProtocolParameters deserialize(final JsonElement json, final Type typeOfT, - final JsonDeserializationContext context) { - final JsonObject jsonObject = json.getAsJsonObject(); - - // Get the event protocol label primitive - final JsonPrimitive labelJsonPrimitive = (JsonPrimitive) jsonObject.get(EVENT_PROTOCOL_TOKEN); - - // Check if we found our event protocol - if (labelJsonPrimitive == null) { - LOGGER.warn("event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" not found in JSON file"); - return null; - } - - // Get and check the event protocol label - final String eventProtocolLabel = labelJsonPrimitive.getAsString().replaceAll("\\s+", ""); - if (eventProtocolLabel == null || eventProtocolLabel.length() == 0) { - final String errorMessage = "event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" value \"" - + labelJsonPrimitive.getAsString() + "\" invalid in JSON file"; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - // We now get the event protocol parameter class - String eventProtocolParameterClassName = null; - - // Get the event protocol parameter class for the event protocol plugin class from the - // configuration parameters - final JsonPrimitive classNameJsonPrimitive = (JsonPrimitive) jsonObject.get(PARAMETER_CLASS_NAME); - - // If no event protocol parameter class was specified, we use the default - if (classNameJsonPrimitive == null) { - eventProtocolParameterClassName = BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.get(eventProtocolLabel); - } else { - // We use the specified one - eventProtocolParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", ""); - } - - // Check the event protocol parameter class - if (eventProtocolParameterClassName == null || eventProtocolParameterClassName.length() == 0) { - final String errorMessage = - "event protocol \"" + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + "\" value \"" - + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null") - + "\" invalid in JSON file"; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - // Get the class for the event protocol - Class eventProtocolParameterClass = null; - try { - eventProtocolParameterClass = Class.forName(eventProtocolParameterClassName); - } catch (final ClassNotFoundException e) { - final String errorMessage = - "event protocol \"" + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + "\" value \"" - + eventProtocolParameterClassName + "\", could not find class"; - LOGGER.warn(errorMessage, e); - throw new ParameterRuntimeException(errorMessage, e); - } - - // Deserialise the class - EventProtocolParameters eventProtocolParameters = - context.deserialize(jsonObject.get(EVENT_PROTOCOL_PARAMETERS), eventProtocolParameterClass); - if (eventProtocolParameters == null) { - // OK no parameters for the event protocol have been specified, just instantiate the - // default parameters - try { - eventProtocolParameters = (EventProtocolParameters) eventProtocolParameterClass.newInstance(); - } catch (final Exception e) { - final String errorMessage = "could not create default parameters for event protocol \"" - + eventProtocolLabel + "\"\n" + e.getMessage(); - LOGGER.warn(errorMessage, e); - throw new ParameterRuntimeException(errorMessage, e); - } - } - - // Check that the event protocol label matches the label in the event protocol parameters - // object - if (!eventProtocolParameters.getLabel().equals(eventProtocolLabel)) { - final String errorMessage = "event protocol \"" + eventProtocolLabel + "\" does not match plugin \"" - + eventProtocolParameters.getLabel() + "\" in \"" + eventProtocolParameterClassName - + "\", specify correct event protocol parameter plugin in parameter \"" + PARAMETER_CLASS_NAME - + "\""; - LOGGER.warn(errorMessage); - throw new ParameterRuntimeException(errorMessage); - } - - return eventProtocolParameters; - } -} 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 new file mode 100644 index 000000000..ba37fe80c --- /dev/null +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/parameters/eventprotocol/EventProtocolParametersJsonAdapter.java @@ -0,0 +1,177 @@ +/*- + * ============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.eventprotocol; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; +import java.util.HashMap; +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.common.parameters.ParameterRuntimeException; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class serialises and deserialises various type of event protocol parameters to and from + * JSON. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class EventProtocolParametersJsonAdapter + implements JsonSerializer, JsonDeserializer { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(EventProtocolParametersJsonAdapter.class); + + // Recurring string constants + private static final String EVENT_PROTOCOL_PREFIX = "event protocol \""; + private static final String VALUE_TAG = "\" value \""; + + private static final String PARAMETER_CLASS_NAME = "parameterClassName"; + + private static final String EVENT_PROTOCOL_TOKEN = "eventProtocol"; + private static final String EVENT_PROTOCOL_PARAMETERS = "parameters"; + + // Built in event protocol parameters + private static final Map BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP = new HashMap<>(); + + static { + BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.put("JSON", JsonEventProtocolParameters.class.getCanonicalName()); + BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.put("APEX", ApexEventProtocolParameters.class.getCanonicalName()); + } + + /* + * (non-Javadoc) + * + * @see com.google.gson.JsonSerializer#serialize(java.lang.Object, java.lang.reflect.Type, + * com.google.gson.JsonSerializationContext) + */ + @Override + public JsonElement serialize(final EventProtocolParameters src, final Type typeOfSrc, + final JsonSerializationContext context) { + final String returnMessage = "serialization of Apex event protocol parameters to Json is not supported"; + LOGGER.error(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) + */ + @Override + public EventProtocolParameters deserialize(final JsonElement json, final Type typeOfT, + final JsonDeserializationContext context) { + final JsonObject jsonObject = json.getAsJsonObject(); + + // Get the event protocol label primitive + final JsonPrimitive labelJsonPrimitive = (JsonPrimitive) jsonObject.get(EVENT_PROTOCOL_TOKEN); + + // Check if we found our event protocol + if (labelJsonPrimitive == null) { + LOGGER.warn("event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + "\" not found in JSON file"); + return null; + } + + // Get and check the event protocol label + final String eventProtocolLabel = labelJsonPrimitive.getAsString().replaceAll("\\s+", ""); + if (eventProtocolLabel == null || eventProtocolLabel.length() == 0) { + final String errorMessage = "event protocol parameter \"" + EVENT_PROTOCOL_TOKEN + VALUE_TAG + + labelJsonPrimitive.getAsString() + "\" invalid in JSON file"; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + // We now get the event protocol parameter class + String eventProtocolParameterClassName = null; + + // Get the event protocol parameter class for the event protocol plugin class from the + // configuration parameters + final JsonPrimitive classNameJsonPrimitive = (JsonPrimitive) jsonObject.get(PARAMETER_CLASS_NAME); + + // If no event protocol parameter class was specified, we use the default + if (classNameJsonPrimitive == null) { + eventProtocolParameterClassName = BUILT_IN_EVENT_PROTOCOL_PARMETER_CLASS_MAP.get(eventProtocolLabel); + } else { + // We use the specified one + eventProtocolParameterClassName = classNameJsonPrimitive.getAsString().replaceAll("\\s+", ""); + } + + // Check the event protocol parameter class + if (eventProtocolParameterClassName == null || eventProtocolParameterClassName.length() == 0) { + final String errorMessage = + EVENT_PROTOCOL_PREFIX + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + VALUE_TAG + + (classNameJsonPrimitive != null ? classNameJsonPrimitive.getAsString() : "null") + + "\" invalid in JSON file"; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + // Get the class for the event protocol + Class eventProtocolParameterClass = null; + try { + eventProtocolParameterClass = Class.forName(eventProtocolParameterClassName); + } catch (final ClassNotFoundException e) { + final String errorMessage = + EVENT_PROTOCOL_PREFIX + eventProtocolLabel + "\" parameter \"" + PARAMETER_CLASS_NAME + VALUE_TAG + + eventProtocolParameterClassName + "\", could not find class"; + LOGGER.warn(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); + } + + // Deserialise the class + EventProtocolParameters eventProtocolParameters = + context.deserialize(jsonObject.get(EVENT_PROTOCOL_PARAMETERS), eventProtocolParameterClass); + if (eventProtocolParameters == null) { + // OK no parameters for the event protocol have been specified, just instantiate the + // default parameters + try { + eventProtocolParameters = (EventProtocolParameters) eventProtocolParameterClass.newInstance(); + } catch (final Exception e) { + final String errorMessage = "could not create default parameters for event protocol \"" + + eventProtocolLabel + "\"\n" + e.getMessage(); + LOGGER.warn(errorMessage, e); + throw new ParameterRuntimeException(errorMessage, e); + } + } + + // Check that the event protocol label matches the label in the event protocol parameters + // object + if (!eventProtocolParameters.getLabel().equals(eventProtocolLabel)) { + final String errorMessage = EVENT_PROTOCOL_PREFIX + eventProtocolLabel + "\" does not match plugin \"" + + eventProtocolParameters.getLabel() + "\" in \"" + eventProtocolParameterClassName + + "\", specify correct event protocol parameter plugin in parameter \"" + PARAMETER_CLASS_NAME + + "\""; + LOGGER.warn(errorMessage); + throw new ParameterRuntimeException(errorMessage); + } + + return eventProtocolParameters; + } +} -- cgit 1.2.3-korg