diff options
author | 2020-09-08 17:23:34 +0000 | |
---|---|---|
committer | 2020-09-08 17:23:34 +0000 | |
commit | d350fd659d716ca0b1678029230cc799cead2056 (patch) | |
tree | 52ea7d451c1110cb3b5b4109104d5608e4ef63f8 /core/core-deployment | |
parent | badd13edc9a11f67c28ef5e0be8ceef0ebf1e496 (diff) | |
parent | 25e3f7a0d6cd5e364e4fd69eef310fcdb8a58b55 (diff) |
Merge "Remove client code from apex-pdp"
Diffstat (limited to 'core/core-deployment')
16 files changed, 0 insertions, 2633 deletions
diff --git a/core/core-deployment/pom.xml b/core/core-deployment/pom.xml deleted file mode 100644 index a844f5354..000000000 --- a/core/core-deployment/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ -<!-- - ============LICENSE_START======================================================= - Copyright (C) 2018 Ericsson. All rights reserved. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - 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========================================================= ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>org.onap.policy.apex-pdp.core</groupId> - <artifactId>core</artifactId> - <version>2.4.1-SNAPSHOT</version> - </parent> - - <artifactId>core-deployment</artifactId> - <name>${project.artifactId}</name> - <description>The Apex policy deployer</description> - - <dependencies> - <dependency> - <groupId>org.onap.policy.apex-pdp.model</groupId> - <artifactId>policy-model</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>org.onap.policy.apex-pdp.model</groupId> - <artifactId>engine-model</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>org.onap.policy.apex-pdp.core</groupId> - <artifactId>core-infrastructure</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>org.onap.policy.apex-pdp.core</groupId> - <artifactId>core-protocols</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>org.mockito</groupId> - <artifactId>mockito-all</artifactId> - <scope>test</scope> - </dependency> - </dependencies> -</project> diff --git a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/ApexDeploymentException.java b/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/ApexDeploymentException.java deleted file mode 100644 index 5944b9f0d..000000000 --- a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/ApexDeploymentException.java +++ /dev/null @@ -1,51 +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.core.deployment; - -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; - -/** - * The Class ApexDeploymentException is an exception that may be thrown on deployment errors in Apex. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexDeploymentException extends ApexException { - private static final long serialVersionUID = 1816909564890470707L; - - /** - * Instantiates a new apex deployment exception. - * - * @param message the message - */ - public ApexDeploymentException(final String message) { - super(message); - } - - /** - * Instantiates a new apex deployment exception. - * - * @param message the message - * @param exception the e - */ - public ApexDeploymentException(final String message, final Exception exception) { - super(message, exception); - } -} diff --git a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/BatchDeployer.java b/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/BatchDeployer.java deleted file mode 100644 index 517deeb57..000000000 --- a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/BatchDeployer.java +++ /dev/null @@ -1,161 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * 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.core.deployment; - -import java.io.PrintStream; -import java.util.Arrays; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class {@link BatchDeployer} deploys an Apex model held as an XML or Json - * file onto an Apex engine. It uses the EngDep protocol to communicate with the - * engine, with the EngDep protocol being carried on Java web sockets. - * - * <p>This deployer is a simple command line deployer that reads the - * communication parameters and the location of the Apex model file as - * arguments. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class BatchDeployer { - private static final int NUM_ARGUMENTS = 3; - - // Get a reference to the logger - private static final XLogger LOGGER = XLoggerFactory.getXLogger(BatchDeployer.class); - - // The facade that is handling messaging to the engine service - private EngineServiceFacade engineServiceFacade = null; - - private String hostName; - private int port; - - /** - * Instantiates a new deployer. - * - * @param hostName the apex host name - * @param port the apex EngDep port - * @param outputStream the output stream - */ - public BatchDeployer(final String hostName, final int port, final PrintStream outputStream) { - this.hostName = hostName; - this.port = port; - - engineServiceFacade = new EngineServiceFacade(hostName, port); - } - - /** - * Initializes the deployer, opens an EngDep communication session with the Apex - * engine. - * - * @throws ApexDeploymentException thrown on deployment and communication errors - */ - public void init() throws ApexDeploymentException { - try { - engineServiceFacade.init(); - } catch (final ApexException e) { - final String errorMessage = "model deployment failed on parameters " + hostName + " " + port; - throw new ApexDeploymentException(errorMessage, e); - } - } - - /** - * Close the EngDep connection to the Apex server. - */ - public void close() { - if (engineServiceFacade != null) { - engineServiceFacade.close(); - } - } - - /** - * Deploy an Apex model on the Apex server. - * - * @param modelFileName the name of the model file containing the model to - * deploy - * @param ignoreConflicts true if conflicts between context in polices is to be - * ignored - * @param force true if the model is to be applied even if it is - * incompatible with the existing model - * @throws ApexException on Apex errors - */ - public void deployModel(final String modelFileName, final boolean ignoreConflicts, final boolean force) - throws ApexException { - engineServiceFacade.deployModel(modelFileName, ignoreConflicts, force); - } - - /** - * Deploy an Apex model on the Apex server. - * - * @param policyModel the model to deploy - * @param ignoreConflicts true if conflicts between context in polices is to be - * ignored - * @param force true if the model is to be applied even if it is - * incompatible with the existing model - * @throws ApexException on Apex errors - */ - public void deployModel(final AxPolicyModel policyModel, final boolean ignoreConflicts, final boolean force) - throws ApexException { - engineServiceFacade.deployModel(policyModel, ignoreConflicts, force); - } - - /** - * Get the engine service facade of the event manager. This method is used for - * testing only. - * - * @return the engine service facade - */ - protected EngineServiceFacade getEngineServiceFacade() { - return engineServiceFacade; - } - - /** - * The main method, reads the Apex server host address, port and location of the - * Apex model file from the command line arguments. - * - * @param args the arguments that specify the Apex engine and the Apex model - * file - * @throws ApexException on deployment errors - */ - public static void main(final String[] args) throws ApexException { - if (args.length != NUM_ARGUMENTS) { - final String message = "invalid arguments: " + Arrays.toString(args) - + "\nusage: BatchDeployer <server address> <port address> <model file path"; - LOGGER.error(message); - throw new ApexDeploymentException(message); - } - - int port; - try { - port = Integer.parseInt(args[1]); - } catch (final NumberFormatException nfe) { - throw new ApexDeploymentException("argument port is invalid", nfe); - } - - final BatchDeployer deployer = new BatchDeployer(args[0], port, System.out); - deployer.init(); - deployer.deployModel(args[2], false, false); - deployer.close(); - } -} diff --git a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/DeploymentClient.java b/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/DeploymentClient.java deleted file mode 100644 index c3246643e..000000000 --- a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/DeploymentClient.java +++ /dev/null @@ -1,277 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2020 Bell Canada. 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.core.deployment; - -import com.google.common.eventbus.Subscribe; -import java.net.InetAddress; -import java.net.URI; -import java.net.UnknownHostException; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import lombok.Getter; -import lombok.Setter; -import org.onap.policy.apex.core.infrastructure.messaging.MessageHolder; -import org.onap.policy.apex.core.infrastructure.messaging.MessageListener; -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.impl.ws.messageblock.MessageBlock; -import org.onap.policy.apex.core.infrastructure.messaging.util.MessagingUtils; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.core.protocols.Message; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class DeploymentClient handles the client side of an EngDep communication session with an Apex server. It runs a - * thread to handle message sending and session monitoring. It uses a sending queue to queue messages for sending by the - * client thread and a receiving queue to queue messages received from the Apex engine. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class DeploymentClient implements Runnable { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(DeploymentClient.class); - - private static final int CLIENT_STOP_WAIT_INTERVAL = 100; - private static final int CLIENT_SEND_QUEUE_TIMEOUT = 50; - - // Host and port to use for EngDep messaging - private String host = null; - private int port = 0; - - // Messaging service is used to transmit and receive messages over the web socket - private static MessagingServiceFactory<Message> factory = new MessagingServiceFactory<>(); - private MessagingService<Message> service = null; - - // Send and receive queues for message buffering - private final BlockingQueue<Message> sendQueue = new LinkedBlockingQueue<>(); - private final BlockingQueue<Message> receiveQueue = new LinkedBlockingQueue<>(); - - // Thread management fields - private boolean started = false; - private Thread thisThread = null; - - // Number of messages processed - private long messagesSent = 0; - private long messagesReceived = 0; - @Getter - @Setter - private AtomicReference<CountDownLatch> countDownLatch = new AtomicReference<>(); - - /** - * Instantiates a new deployment client. - * - * @param host the host name that the EngDep server is running on - * @param port the port the port the EngDep server is using - */ - public DeploymentClient(final String host, final int port) { - this.host = host; - this.port = port; - countDownLatch.set(new CountDownLatch(1)); - } - - /** - * {@inheritDoc}. - */ - @Override - public void run() { - LOGGER.debug("engine<-->deployment to \"ws://{}:{}\" thread starting . . .", host, port); - - // Set up the thread name - thisThread = Thread.currentThread(); - thisThread.setName(DeploymentClient.class.getName() + "-" + host + ":" + port); - - try { - // Establish a connection to the Apex server for EngDep message communication over Web - // Sockets - service = factory.createClient(new URI("ws://" + host + ":" + port)); - service.addMessageListener(new DeploymentClientListener()); - - service.startConnection(); - started = true; - countDownLatch.get().countDown(); - LOGGER.debug("engine<-->deployment client thread started"); - } catch (final Exception e) { - LOGGER.error("engine<-->deployment client thread exception", e); - return; - } - // Loop forever, sending messages as they appear on the queue - while (started && !thisThread.isInterrupted()) { - started = sendMessages(); - } - - // Thread has been interrupted - thisThread = null; - LOGGER.debug("engine<-->deployment client thread finished"); - } - - /** - * Send messages off the queue. - */ - private boolean sendMessages() { - try { - final Message messageForSending = sendQueue.poll(CLIENT_SEND_QUEUE_TIMEOUT, TimeUnit.MILLISECONDS); - if (messageForSending == null) { - return true; - } - - // Send the message in its message holder - InetAddress local = getLocalAddress(); - final MessageHolder<Message> messageHolder = new MessageHolder<>(local); - messageHolder.addMessage(messageForSending); - service.send(messageHolder); - messagesSent++; - } catch (final InterruptedException e) { - // Message sending has been interrupted, we are finished - LOGGER.debug("engine<-->deployment client interrupted"); - // restore the interrupt status - thisThread.interrupt(); - return false; - } - - return true; - } - - /** - * Get the local address for the WS MessageHolder, or null if there is a problem. - */ - private InetAddress getLocalAddress() { - try { - return MessagingUtils.getLocalHostLanAddress(); - } catch (UnknownHostException e) { - LOGGER.debug("engine<-->deployment client failed to find the localhost address - continuing ...", e); - return null; - } - } - - /** - * Gets the host. - * - * @return the host - */ - public String getHost() { - return host; - } - - /** - * Gets the port. - * - * @return the port - */ - public int getPort() { - return port; - } - - /** - * Send an EngDep message to the Apex server. - * - * @param message the message to send to the Apex server - */ - public void sendMessage(final Message message) { - sendQueue.add(message); - } - - /** - * Stop the deployment client. - */ - public void stopClient() { - LOGGER.debug("engine<-->deployment test client stopping . . ."); - thisThread.interrupt(); - - // Wait for the thread to stop - ThreadUtilities.sleep(CLIENT_STOP_WAIT_INTERVAL); - - // Close the Web Services connection - if (service != null) { - service.stopConnection(); - } - started = false; - countDownLatch.set(new CountDownLatch(1)); - LOGGER.debug("engine<-->deployment test client stopped . . ."); - } - - /** - * Checks if the client thread is started. - * - * @return true, if the client thread is started - */ - public boolean isStarted() { - return started; - } - - /** - * Allows users of this class to get a reference to the receive queue to receove messages. - * - * @return the receive queue - */ - public BlockingQueue<Message> getReceiveQueue() { - return receiveQueue; - } - - /** - * Get the number of messages received by the client. - * @return the number of messages received by the client - */ - public long getMessagesReceived() { - return messagesReceived; - } - - /** - * Get the number of messages sent by the client. - * @return the number of messages sent by the client - */ - public long getMessagesSent() { - return messagesSent; - } - - /** - * The listener interface for receiving deploymentClient events. The class that is interested in processing a - * deploymentClient event implements this interface, and the object created with that class is registered with a - * component using the component's {@code addDeploymentClientListener} method. When the deploymentClient event - * occurs, that object's appropriate method is invoked. - * - * @see DeploymentClientEvent - */ - private class DeploymentClientListener implements MessageListener<Message> { - /** - * {@inheritDoc}. - */ - @Subscribe - @Override - public void onMessage(final MessageBlock<Message> messageData) { - messagesReceived++; - receiveQueue.addAll(messageData.getMessages()); - } - - /** - * {@inheritDoc}. - */ - @Override - public void onMessage(final String messageString) { - messagesReceived++; - throw new UnsupportedOperationException("String mesages are not supported on the EngDep protocol"); - } - } -} diff --git a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/EngineServiceFacade.java b/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/EngineServiceFacade.java deleted file mode 100644 index 7d70960de..000000000 --- a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/EngineServiceFacade.java +++ /dev/null @@ -1,499 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. - * Modifications Copyright (C) 2020 Bell Canada. 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.core.deployment; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.net.URL; -import java.util.concurrent.TimeUnit; -import org.onap.policy.apex.core.protocols.Message; -import org.onap.policy.apex.core.protocols.engdep.messages.EngineServiceInfoResponse; -import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineInfo; -import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineServiceInfo; -import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineStatus; -import org.onap.policy.apex.core.protocols.engdep.messages.Response; -import org.onap.policy.apex.core.protocols.engdep.messages.StartEngine; -import org.onap.policy.apex.core.protocols.engdep.messages.StartPeriodicEvents; -import org.onap.policy.apex.core.protocols.engdep.messages.StopEngine; -import org.onap.policy.apex.core.protocols.engdep.messages.StopPeriodicEvents; -import org.onap.policy.apex.core.protocols.engdep.messages.UpdateModel; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter; -import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.common.utils.resources.ResourceUtils; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class Deployer deploys an Apex model held as an XML file onto an Apex - * engine. It uses the EngDep protocol to communicate with the engine, with the - * EngDep protocol being carried on Java web sockets. - * - * <p>This deployer is a simple command line deployer that reads the - * communication parameters and the location of the XML model file as arguments. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class EngineServiceFacade { - // Get a reference to the logger - private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineServiceFacade.class); - - // Repeated string constants - private static final String RECEIVED_FROM_SERVER = " received from server"; - private static final String FAILED_RESPONSE = "failed response "; - - // The default message timeout and timeout increment (the amount of time between - // polls) in - // milliseconds - private static final int REPLY_MESSAGE_TIMEOUT_DEFAULT = 10000; - private static final int REPLY_MESSAGE_TIMEOUT_INCREMENT = 100; - - // The Apex engine host and EngDep port - private final String hostName; - private final int port; - - // The deployment client handles the EngDep communication session towards the - // Apex server - private DeploymentClient client = null; - private Thread clientThread = null; - - // Information about the Engine service we are connected to - private AxArtifactKey engineServiceKey = null; - private AxArtifactKey[] engineKeyArray = null; - private AxArtifactKey apexModelKey = null; - - /** - * Instantiates a new deployer. - * - * @param hostName the host name of the host running the Apex Engine - * @param port the port to use for EngDep communication with the Apex engine - */ - public EngineServiceFacade(final String hostName, final int port) { - this.hostName = hostName; - this.port = port; - - // Use the deployment client to handle the EngDep communication towards the Apex - // server. - client = new DeploymentClient(hostName, port); - } - - /** - * Initializes the facade, opens an EngDep communication session with the Apex - * engine. - * - * @throws ApexDeploymentException thrown on deployment and communication errors - */ - public void init() throws ApexDeploymentException { - - if (client.isStarted()) { - throw new ApexDeploymentException("connection already active to " + hostName + ":" + port); - } - - try { - LOGGER.debug("handshaking with server {}:{} . . .", hostName, port); - - // Use the deployment client to handle the EngDep communication towards the Apex - // server. - // The deployment client runs a thread to monitor the session and to send - // messages - clientThread = new Thread(client); - clientThread.start(); - - // Wait for the connection to come up - if (!client.getCountDownLatch().get().await(5L, TimeUnit.SECONDS)) { - throw new ApexDeploymentException("could not handshake with server " + hostName + ":" + port); - } - - LOGGER.debug("opened connection to server {}:{} . . .", hostName, port); - - // Get engine service information to see what engines we're dealing with - final GetEngineServiceInfo engineServiceInfo = new GetEngineServiceInfo(null); - LOGGER.debug("sending get engine service info message {} to server {}:{} . . .", engineServiceInfo, - hostName, port); - client.sendMessage(engineServiceInfo); - LOGGER.debug("sent get engine service info message to server {}:{} . . .", hostName, port); - - final EngineServiceInfoResponse engineServiceInfoResponse = (EngineServiceInfoResponse) getResponse( - engineServiceInfo); - if (engineServiceInfoResponse.isSuccessful()) { - engineServiceKey = engineServiceInfoResponse.getEngineServiceKey(); - engineKeyArray = engineServiceInfoResponse.getEngineKeyArray(); - apexModelKey = engineServiceInfoResponse.getApexModelKey(); - } else { - throw new ApexDeploymentException( - "could not get engine service information from server " + hostName + ":" + port); - } - - } catch (final Exception e) { - client.stopClient(); - throw new ApexDeploymentException("could not handshake with server " + hostName + ":" + port, e); - } - - } - - /** - * Get the engine service key. - * - * @return the engine service key - */ - public AxArtifactKey getApexModelKey() { - return apexModelKey; - } - - /** - * Get the keys of the engines on this engine service. - * - * @return the engine key array - */ - public AxArtifactKey[] getEngineKeyArray() { - return engineKeyArray; - } - - /** - * Get the engine service key. - * - * @return the engine service key - */ - public AxArtifactKey getKey() { - return engineServiceKey; - } - - /** - * Close the EngDep connection to the Apex server. - */ - public void close() { - LOGGER.debug("closing connection to server {}:{} . . .", hostName, port); - - if (client.isStarted()) { - client.stopClient(); - } - - LOGGER.debug("closed connection to server {}:{} . . .", hostName, port); - } - - /** - * Deploy an Apex model on the Apex engine service. - * - * @param modelFileName the name of the model file containing the model to - * deploy - * @param ignoreConflicts true if conflicts between context in polices is to be - * ignored - * @param force true if the model is to be applied even if it is - * incompatible with the existing model - * @throws ApexException on Apex errors - */ - public void deployModel(final String modelFileName, final boolean ignoreConflicts, final boolean force) - throws ApexException { - if (engineServiceKey == null || engineKeyArray == null || engineKeyArray.length == 0) { - throw new ApexDeploymentException("could not deploy apex model, deployer is not initialized"); - } - - // Get the model file as a string - URL apexModelUrl = ResourceUtils.getLocalFile(modelFileName); - if (apexModelUrl == null) { - apexModelUrl = ResourceUtils.getUrlResource(modelFileName); - if (apexModelUrl == null) { - throw new ApexDeploymentException( - "could not create apex model, could not read from file " + modelFileName); - } - } - - try { - deployModel(modelFileName, apexModelUrl.openStream(), ignoreConflicts, force); - } catch (final Exception deployException) { - final String errorMessage = "could not deploy apex model from " + modelFileName; - throw new ApexDeploymentException(errorMessage, deployException); - } - } - - /** - * Deploy an Apex model on the Apex engine service. - * - * @param modelFileName the name of the model file containing the model to - * deploy - * @param modelInputStream the stream that holds the Apex model - * @param ignoreConflicts true if conflicts between context in polices is to be - * ignored - * @param force true if the model is to be applied even if it is - * incompatible with the existing model - * @throws ApexException on model deployment errors - */ - public void deployModel(final String modelFileName, final InputStream modelInputStream, - final boolean ignoreConflicts, final boolean force) throws ApexException { - // Read the policy model from the stream - final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class); - modelReader.setValidateFlag(!ignoreConflicts); - final AxPolicyModel apexPolicyModel = modelReader.read(modelInputStream); - - // Deploy the model - deployModel(apexPolicyModel, ignoreConflicts, force); - } - - /** - * Deploy an Apex model on the Apex engine service. - * - * @param apexPolicyModel the name of the model to deploy - * @param ignoreConflicts true if conflicts between context in polices is to be - * ignored - * @param force true if the model is to be applied even if it is - * incompatible with the existing model - * @throws ApexException on model deployment errors - */ - public void deployModel(final AxPolicyModel apexPolicyModel, final boolean ignoreConflicts, final boolean force) - throws ApexException { - // Write the model into a byte array - final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); - final ApexModelWriter<AxPolicyModel> modelWriter = new ApexModelWriter<>(AxPolicyModel.class); - modelWriter.write(apexPolicyModel, baOutputStream); - - // Create and send Update message - final UpdateModel umMessage = new UpdateModel(engineServiceKey, baOutputStream.toString(), ignoreConflicts, - force); - - LOGGER.debug("sending update message {} to server {}:{} . . .", umMessage, hostName, port); - client.sendMessage(umMessage); - LOGGER.debug("sent update message to server {}:{} . . .", hostName, port); - - // Check if we got a response - final Response response = getResponse(umMessage); - if (!response.isSuccessful()) { - throw new ApexException( - FAILED_RESPONSE + response.getMessageData() + RECEIVED_FROM_SERVER + hostName + ':' + port); - } - } - - /** - * Start an Apex engine on the engine service. - * - * @param engineKey the key of the engine to start - * @throws ApexDeploymentException on messaging errors - */ - public void startEngine(final AxArtifactKey engineKey) throws ApexDeploymentException { - final StartEngine startEngineMessage = new StartEngine(engineKey); - LOGGER.debug("sending start engine {} to server {}:{} . . .", startEngineMessage, hostName, port); - client.sendMessage(startEngineMessage); - LOGGER.debug("sent start engine message to server {}:{} . . .", hostName, port); - - // Check if we got a response - final Response response = getResponse(startEngineMessage); - if (!response.isSuccessful()) { - final String message = FAILED_RESPONSE + response.getMessageData() + RECEIVED_FROM_SERVER + hostName + ':' - + port; - throw new ApexDeploymentException(message); - } - } - - /** - * Stop an Apex engine on the engine service. - * - * @param engineKey the key of the engine to stop - * @throws ApexDeploymentException on messaging errors - */ - public void stopEngine(final AxArtifactKey engineKey) throws ApexDeploymentException { - final StopEngine stopEngineMessage = new StopEngine(engineKey); - LOGGER.debug("sending stop engine {} to server {}:{} . . .", stopEngineMessage, hostName, port); - client.sendMessage(stopEngineMessage); - LOGGER.debug("sent stop engine message to server {}:{} . . .", hostName, port); - - // Check if we got a response - final Response response = getResponse(stopEngineMessage); - if (!response.isSuccessful()) { - final String message = FAILED_RESPONSE + response.getMessageData() + RECEIVED_FROM_SERVER + hostName + ':' - + port; - throw new ApexDeploymentException(message); - } - } - - /** - * Start periodic events on an Apex engine on the engine service. - * - * @param engineKey the key of the engine to start periodic events on - * @param period the period in milliseconds between periodic events - * @throws ApexDeploymentException on messaging errors - */ - public void startPerioidicEvents(final AxArtifactKey engineKey, final long period) throws ApexDeploymentException { - final StartPeriodicEvents startPerioidicEventsMessage = new StartPeriodicEvents(engineKey); - startPerioidicEventsMessage.setMessageData(Long.toString(period)); - LOGGER.debug("sending start perioidic events {} to server {}:{} . . .", startPerioidicEventsMessage, hostName, - port); - client.sendMessage(startPerioidicEventsMessage); - LOGGER.debug("sent start perioidic events message to server {}:{} . . .", hostName, port); - - // Check if we got a response - final Response response = getResponse(startPerioidicEventsMessage); - if (!response.isSuccessful()) { - final String message = FAILED_RESPONSE + response.getMessageData() + RECEIVED_FROM_SERVER + hostName + ':' - + port; - throw new ApexDeploymentException(message); - } - } - - /** - * Stop periodic events on an Apex engine on the engine service. - * - * @param engineKey the key of the engine to stop periodic events on - * @throws ApexDeploymentException on messaging errors - */ - public void stopPerioidicEvents(final AxArtifactKey engineKey) throws ApexDeploymentException { - final StopPeriodicEvents stopPerioidicEventsMessage = new StopPeriodicEvents(engineKey); - LOGGER.debug("sending stop perioidic events {} to server {}:{} . . .", stopPerioidicEventsMessage, hostName, - port); - client.sendMessage(stopPerioidicEventsMessage); - LOGGER.debug("sent stop perioidic events message to server {}:{} . . .", hostName, port); - - // Check if we got a response - final Response response = getResponse(stopPerioidicEventsMessage); - if (!response.isSuccessful()) { - final String message = FAILED_RESPONSE + response.getMessageData() + RECEIVED_FROM_SERVER + hostName + ':' - + port; - throw new ApexDeploymentException(message); - } - } - - /** - * Get the status of an Apex engine. - * - * @param engineKey the key of the engine to get the status of - * @return an engine model containing the status of the engine for the given key - * @throws ApexException the apex exception - */ - public AxEngineModel getEngineStatus(final AxArtifactKey engineKey) throws ApexException { - final GetEngineStatus engineStatusMessage = new GetEngineStatus(engineKey); - LOGGER.debug("sending get engine status message {} to server {}:{} . . .", engineStatusMessage, hostName, port); - client.sendMessage(engineStatusMessage); - LOGGER.debug("sent get engine status message to server {}:{} . . .", hostName, port); - - // Check if we got a response - final Response response = getResponse(engineStatusMessage); - if (!response.isSuccessful()) { - final String message = FAILED_RESPONSE + response.getMessageData() + RECEIVED_FROM_SERVER + hostName + ':' - + port; - throw new ApexException(message); - } - - final ByteArrayInputStream baInputStream = new ByteArrayInputStream(response.getMessageData().getBytes()); - final ApexModelReader<AxEngineModel> modelReader = new ApexModelReader<>(AxEngineModel.class); - modelReader.setValidateFlag(false); - return modelReader.read(baInputStream); - } - - /** - * Get the runtime information of an Apex engine. - * - * @param engineKey the key of the engine to get information for - * @return an engine model containing information on the engine for the given - * key - * @throws ApexException the apex exception - */ - public String getEngineInfo(final AxArtifactKey engineKey) throws ApexException { - final GetEngineInfo engineInfoMessage = new GetEngineInfo(engineKey); - LOGGER.debug("sending get engine information message {} to server {}:{} . . .", engineInfoMessage, hostName, - port); - client.sendMessage(engineInfoMessage); - LOGGER.debug("sent get engine information message to server {}:{} . . .", hostName, port); - - // Check if we got a response - final Response response = getResponse(engineInfoMessage); - if (!response.isSuccessful()) { - final String message = FAILED_RESPONSE + response.getMessageData() + RECEIVED_FROM_SERVER + hostName + ':' - + port; - throw new ApexException(message); - } - - return response.getMessageData(); - } - - /** - * Check the response to a model deployment message from the Apex server. - * - * @param sentMessage the sent message - * @return the response message - * @throws ApexDeploymentException the apex deployment exception - */ - private Response getResponse(final Message sentMessage) throws ApexDeploymentException { - // Get the amount of milliseconds we should wait for a timeout - int timeoutTime = sentMessage.getReplyTimeout(); - if (timeoutTime <= 0) { - timeoutTime = REPLY_MESSAGE_TIMEOUT_DEFAULT; - } - - // Wait for the required amount of milliseconds for the response from the Apex - // server - Message receivedMessage = null; - for (int timeWaitedSoFar = 0; receivedMessage == null - && timeWaitedSoFar < timeoutTime; timeWaitedSoFar += REPLY_MESSAGE_TIMEOUT_INCREMENT) { - try { - receivedMessage = client.getReceiveQueue().poll(REPLY_MESSAGE_TIMEOUT_INCREMENT, TimeUnit.MILLISECONDS); - } catch (final InterruptedException e) { - // restore the interrupt status - Thread.currentThread().interrupt(); - throw new ApexDeploymentException( - "reception of response from server interrupted " + hostName + ':' + port, e); - } - } - - // Check if response to sent message - if (receivedMessage == null) { - throw new ApexDeploymentException("no response received to sent message " + sentMessage.getAction()); - } - - // Check instance is a response message - if (!(receivedMessage instanceof Response)) { - throw new ApexDeploymentException("response received from server is of incorrect type " - + receivedMessage.getClass().getName() + ", should be of type " + Response.class.getName()); - } - - // Cast the response message - final Response responseMessage = (Response) receivedMessage; - - // Check if response to sent message - if (!responseMessage.getResponseTo().equals(sentMessage)) { - throw new ApexDeploymentException( - "response received is not correct response to sent message " + sentMessage.getAction()); - } - - // Check if successful - if (responseMessage.isSuccessful()) { - LOGGER.debug("response received: {} message was succssful: {}", sentMessage.getAction(), - responseMessage.getMessageData()); - } else { - LOGGER.debug("response received: {} message failed: {}", sentMessage.getAction(), - responseMessage.getMessageData()); - } - - return responseMessage; - } - - /** - * Set a deployment client for this facade. This method is for testing. - * - * @param deploymentClient the deployment client to set - */ - protected void setDeploymentClient(final DeploymentClient deploymentClient) { - this.client = deploymentClient; - } -} diff --git a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/PeriodicEventManager.java b/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/PeriodicEventManager.java deleted file mode 100644 index 385640050..000000000 --- a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/PeriodicEventManager.java +++ /dev/null @@ -1,185 +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.core.deployment; - -import java.io.PrintStream; -import java.util.Arrays; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This utility class is used to start and stop periodic events on Apex engines over the EngDep protocol. - */ -public class PeriodicEventManager { - // Get a reference to the logger - private static final XLogger LOGGER = XLoggerFactory.getXLogger(BatchDeployer.class); - - private static final int NUM_ARGUMENTS = 4; - - // The facade that is handling messaging to the engine service - private EngineServiceFacade engineServiceFacade = null; - - // Host name and port of the Apex service - private String hostName; - private int port; - - // Should we start or stop periodic events - private boolean startFlag; - - // The period for periodic events - private long period; - - /** - * Instantiates a new periodic event manager. - * - * @param args the command parameters - * @param outputStream the output stream - * @throws ApexDeploymentException on messaging exceptions - */ - public PeriodicEventManager(final String[] args, final PrintStream outputStream) throws ApexDeploymentException { - if (args.length != NUM_ARGUMENTS) { - String message = "invalid arguments: " + Arrays.toString(args) - + "\nusage: PeriodicEventManager <server address> <port address> " - + "<start/stop> <periods in ms>"; - LOGGER.error(message); - outputStream.println(message); - throw new ApexDeploymentException(message); - } - - this.hostName = args[0]; - - try { - this.port = Integer.parseInt(args[1]); - } catch (NumberFormatException nfe) { - throw new ApexDeploymentException("argument port is invalid", nfe); - } - - if ("start".equalsIgnoreCase(args[2])) { - startFlag = true; - } else if ("stop".equalsIgnoreCase(args[2])) { - startFlag = false; - } else { - throw new ApexDeploymentException("argument " + args[2] + " must be \"start\" or \"stop\""); - } - - try { - this.period = Long.parseLong(args[3]); - } catch (NumberFormatException nfe) { - throw new ApexDeploymentException("argument period is invalid", nfe); - } - - // Use an engine service facade to handle periodic event setting - engineServiceFacade = new EngineServiceFacade(hostName, port); - } - - /** - * Initializes the manager, opens an EngDep communication session with the Apex engine. - * - * @throws ApexDeploymentException thrown on messaging and communication errors - */ - public void init() throws ApexDeploymentException { - try { - engineServiceFacade.init(); - } catch (final ApexException e) { - String errorMessage = "periodic event setting failed on parameters " + hostName + " " + port + " " - + startFlag; - LOGGER.error(errorMessage, e); - throw new ApexDeploymentException(errorMessage); - } - } - - /** - * Close the EngDep connection to the Apex server. - */ - public void close() { - if (engineServiceFacade != null) { - engineServiceFacade.close(); - } - } - - /** - * Execute the periodic event command. - * - * @throws ApexDeploymentException on periodic event exceptions - */ - public void runCommand() throws ApexDeploymentException { - if (startFlag) { - startPerioidicEvents(); - } else { - stopPerioidicEvents(); - } - } - - /** - * Start the Apex engines on the engine service. - * - * @throws ApexDeploymentException on messaging errors - */ - private void startPerioidicEvents() throws ApexDeploymentException { - if (engineServiceFacade.getEngineKeyArray() == null) { - throw new ApexDeploymentException("connection to apex is not initialized"); - } - - for (final AxArtifactKey engineKey : engineServiceFacade.getEngineKeyArray()) { - engineServiceFacade.startPerioidicEvents(engineKey, period); - } - } - - /** - * Stop the Apex engines on the engine service. - * - * @throws ApexDeploymentException on messaging errors - */ - private void stopPerioidicEvents() throws ApexDeploymentException { - if (engineServiceFacade.getEngineKeyArray() == null) { - throw new ApexDeploymentException("connection to apex is not initialized"); - } - - for (final AxArtifactKey engineKey : engineServiceFacade.getEngineKeyArray()) { - engineServiceFacade.stopPerioidicEvents(engineKey); - } - } - - /** - * Get the engine service facade of the event manager. This method is used for testing only. - * - * @return the engine service facade - */ - protected EngineServiceFacade getEngineServiceFacade() { - return engineServiceFacade; - } - - /** - * The main method, reads the Apex server host address, port and location of the Apex model XML file from the - * command line arguments. - * - * @param args the arguments that specify the Apex engine and the Apex model file - * @throws ApexDeploymentException on messaging errors - */ - public static void main(final String[] args) throws ApexDeploymentException { - PeriodicEventManager peManager = new PeriodicEventManager(args, System.out); - peManager.init(); - peManager.runCommand(); - peManager.close(); - } -} diff --git a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/package-info.java b/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/package-info.java deleted file mode 100644 index b2b7fda2d..000000000 --- a/core/core-deployment/src/main/java/org/onap/policy/apex/core/deployment/package-info.java +++ /dev/null @@ -1,28 +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========================================================= - */ - -/** - * Provides a facade and client that allows Apex engines to be managed and monitored over the EngDep protocol. Some - * utility classes for deployment are also provided. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ - -package org.onap.policy.apex.core.deployment; diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/ApexDeploymentExceptionTest.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/ApexDeploymentExceptionTest.java deleted file mode 100644 index 3a22fad12..000000000 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/ApexDeploymentExceptionTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.core.deployment; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; -import org.junit.Test; - -/** - * Test the Apex deployment Exception. - * - */ -public class ApexDeploymentExceptionTest { - - @Test - public void testDeploymentException() { - ApexDeploymentException ade0 = new ApexDeploymentException("a message"); - assertNotNull(ade0); - assertEquals("a message", ade0.getMessage()); - - ApexDeploymentException ade1 = new ApexDeploymentException("a message", new IOException()); - assertNotNull(ade1); - assertEquals("a message", ade0.getMessage()); - } -} diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/BatchDeployerTest.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/BatchDeployerTest.java deleted file mode 100644 index 7e17cacdc..000000000 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/BatchDeployerTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation - * ================================================================================ - * 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.core.deployment; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.PrintStream; -import java.time.Duration; -import org.awaitility.Awaitility; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -/** - * Test the periodic event manager utility. - */ -public class BatchDeployerTest { - @Test - public void testBatchDeployerBad() { - final String[] eventArgs = { "-h" }; - - assertThatThrownBy(() -> BatchDeployer.main(eventArgs)) - .hasMessageContaining("invalid arguments: [-h]"); - } - - @Test - public void testBatchDeployerBadPort() { - final String[] eventArgs = { "localhost", "aport", "afile" }; - - assertThatThrownBy(() -> BatchDeployer.main(eventArgs)) - .hasMessage("argument port is invalid"); - } - - @Test - public void testBatchDeployerOk() { - final String[] eventArgs = { "Host", "43443", - "src/test/resources/models/SamplePolicyModelJAVASCRIPT.json" }; - - assertThatThrownBy(() -> BatchDeployer.main(eventArgs)) - .hasMessage("model deployment failed on parameters Host 43443"); - } - - @Test - public void testBatchDeployerDeployString() throws ApexException { - final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); - - BatchDeployer deployer = new BatchDeployer("localhost", 12345, new PrintStream(baosOut, true)); - final DummyDeploymentClient dummyDeploymentClient = new DummyDeploymentClient("aHost", 54553); - deployer.getEngineServiceFacade().setDeploymentClient(dummyDeploymentClient); - - // We are testing towards a dummy client, make it return a failed initiation - dummyDeploymentClient.setInitSuccessful(false); - assertThatThrownBy(deployer::init).hasMessage("model deployment failed on parameters localhost 12345"); - // Wait until the connection to the server closes following the bad connection - // attempt - Awaitility.await().atLeast(Duration.ofMillis(500)); - - // We are testing towards a dummy client, make it return a successful initiation - dummyDeploymentClient.setInitSuccessful(true); - deployer.init(); - - assertThatThrownBy(() -> deployer.deployModel("src/test/resources/models/SmallModel.json", false, false)) - .hasMessage("could not deploy apex model from src/test/resources/models/SmallModel.json"); - deployer.deployModel("src/test/resources/models/SmallModel.json", false, false); - - deployer.close(); - } - - @Test - public void testBatchDeployerStream() throws FileNotFoundException, ApexException { - - final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); - - BatchDeployer deployer = new BatchDeployer("localhost", 12345, new PrintStream(baosOut, true)); - final DummyDeploymentClient dummyDeploymentClient = new DummyDeploymentClient("aHost", 54553); - deployer.getEngineServiceFacade().setDeploymentClient(dummyDeploymentClient); - - dummyDeploymentClient.setInitSuccessful(false); - assertThatThrownBy(deployer::init) - .hasMessage("model deployment failed on parameters localhost 12345"); - // Wait until the connection to the server closes following the bad connection - // attempt - Awaitility.await().atLeast(Duration.ofMillis(500)); - - dummyDeploymentClient.setInitSuccessful(true); - - deployer.init(); - - final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class); - modelReader.setValidateFlag(false); - final AxPolicyModel apexPolicyModel = modelReader - .read(new FileInputStream(new File("src/test/resources/models/SmallModel.json"))); - - assertThatThrownBy(() -> deployer.deployModel(apexPolicyModel, false, false)) - .hasMessage("failed response Operation failed received from serverlocalhost:12345"); - - deployer.deployModel(apexPolicyModel, false, false); - - deployer.close(); - } - - @Test - public void testBatchDeployerUninitialized() { - final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); - - BatchDeployer deployer = new BatchDeployer("localhost", 12345, new PrintStream(baosOut, true)); - deployer.getEngineServiceFacade().setDeploymentClient(new DummyDeploymentClient("aHost", 54553)); - - assertThatThrownBy(() -> deployer.deployModel("src/test/resources/models/SamplePolicyModelJAVASCRIPT.json", - false, false)) - .hasMessage("could not deploy apex model, deployer is not initialized"); - assertThatThrownBy(() -> deployer.deployModel("src/test/resources/models/SamplePolicyModelJAVASCRIPT.json", - false, false)) - .hasMessage("could not deploy apex model, deployer is not initialized"); - - deployer.close(); - } - - @Test - public void testBatchDeployerStreamUninitialized() throws ApexModelException, FileNotFoundException { - final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); - - BatchDeployer deployer = new BatchDeployer("localhost", 12345, new PrintStream(baosOut, true)); - deployer.getEngineServiceFacade().setDeploymentClient(new DummyDeploymentClient("aHost", 54553)); - - final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class); - modelReader.setValidateFlag(false); - final AxPolicyModel apexPolicyModel = modelReader - .read(new FileInputStream(new File("src/test/resources/models/SmallModel.json"))); - - assertThatThrownBy(() -> deployer.deployModel(apexPolicyModel, false, false)) - .hasMessage("failed response Operation failed received from serverlocalhost:12345"); - deployer.close(); - } -} diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/DeploymentClientTest.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/DeploymentClientTest.java deleted file mode 100644 index 96b553a30..000000000 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/DeploymentClientTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * 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.core.deployment; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.awaitility.Awaitility.await; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyObject; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.onap.policy.apex.core.infrastructure.messaging.MessageHolder; -import org.onap.policy.apex.core.infrastructure.messaging.MessageListener; -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.impl.ws.messageblock.MessageBlock; -import org.onap.policy.apex.core.protocols.Message; -import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineStatus; -import org.onap.policy.apex.core.protocols.engdep.messages.Response; -import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; - -/** - * Test the deployment web socket client. - */ -@RunWith(MockitoJUnitRunner.class) -public class DeploymentClientTest { - @Mock - private static MessagingServiceFactory<Message> mockServiceFactory; - - @Mock - private static MessagingService<Message> mockService; - - @SuppressWarnings("rawtypes") - ArgumentCaptor<MessageListener> messageListener = ArgumentCaptor.forClass(MessageListener.class); - - @SuppressWarnings("unchecked") - @Test - public void testDeploymentClientStart() throws Exception { - DeploymentClient deploymentClient = new DeploymentClient("localhost", 51332); - - final Field factoryField = deploymentClient.getClass().getDeclaredField("factory"); - factoryField.setAccessible(true); - factoryField.set(deploymentClient, mockServiceFactory); - - Mockito.doReturn(mockService).when(mockServiceFactory).createClient(anyObject()); - - Mockito.doNothing().when(mockService).addMessageListener(messageListener.capture()); - Mockito.doNothing().when(mockService).startConnection(); - - Mockito.doNothing().when(mockService).send((MessageHolder<Message>) anyObject()); - - Thread clientThread = new Thread(deploymentClient); - clientThread.start(); - - await().atMost(200, TimeUnit.MILLISECONDS).until(() -> deploymentClient.isStarted()); - - assertTrue(deploymentClient.isStarted()); - assertTrue(clientThread.isAlive()); - - AxArtifactKey engineKey = new AxArtifactKey("MyEngine", "0.0.1"); - GetEngineStatus getEngineStatus = new GetEngineStatus(engineKey); - deploymentClient.sendMessage(new GetEngineStatus(engineKey)); - - Response response = new Response(engineKey, true, getEngineStatus); - List<Message> messageList = new ArrayList<>(); - messageList.add(response); - - MessageBlock<Message> responseBlock = new MessageBlock<>(messageList, null); - messageListener.getValue().onMessage(responseBlock); - - assertThatThrownBy(() -> messageListener.getValue().onMessage("StringMessage")) - .hasMessage("String mesages are not supported on the EngDep protocol"); - - await().atMost(300, TimeUnit.MILLISECONDS).until(() -> deploymentClient.getMessagesReceived() == 2); - assertEquals(2, deploymentClient.getMessagesReceived()); - - deploymentClient.stopClient(); - } - - @Test - public void testDeploymentClientStartException() throws Exception { - DeploymentClient deploymentClient = new DeploymentClient("localhost", 51273); - - final Field factoryField = deploymentClient.getClass().getDeclaredField("factory"); - factoryField.setAccessible(true); - factoryField.set(deploymentClient, mockServiceFactory); - - Mockito.doReturn(mockService).when(mockServiceFactory).createClient(anyObject()); - - Mockito.doNothing().when(mockService).addMessageListener(anyObject()); - Mockito.doThrow(new ApexRuntimeException("connection start failed")).when(mockService).startConnection(); - - Thread clientThread = new Thread(deploymentClient); - clientThread.start(); - - await().atLeast(50, TimeUnit.MILLISECONDS).until(() -> !deploymentClient.isStarted()); - - assertFalse(deploymentClient.isStarted()); - assertFalse(clientThread.isAlive()); - assertEquals(0, deploymentClient.getReceiveQueue().size()); - - deploymentClient.stopClient(); - } -} diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/DummyDeploymentClient.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/DummyDeploymentClient.java deleted file mode 100644 index 553380944..000000000 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/DummyDeploymentClient.java +++ /dev/null @@ -1,220 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation. - * Modifications Copyright (C) 2020 Bell Canada. 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.core.deployment; - -import static org.awaitility.Awaitility.await; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import lombok.Getter; -import lombok.Setter; -import org.onap.policy.apex.core.protocols.Message; -import org.onap.policy.apex.core.protocols.engdep.messages.EngineServiceInfoResponse; -import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineInfo; -import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineServiceInfo; -import org.onap.policy.apex.core.protocols.engdep.messages.GetEngineStatus; -import org.onap.policy.apex.core.protocols.engdep.messages.Response; -import org.onap.policy.apex.core.protocols.engdep.messages.StartEngine; -import org.onap.policy.apex.core.protocols.engdep.messages.StartPeriodicEvents; -import org.onap.policy.apex.core.protocols.engdep.messages.StopEngine; -import org.onap.policy.apex.core.protocols.engdep.messages.StopPeriodicEvents; -import org.onap.policy.apex.core.protocols.engdep.messages.UpdateModel; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.common.utils.resources.TextFileUtils; - -/** - * Dummy deployment client. - */ -@Getter -@Setter -public class DummyDeploymentClient extends DeploymentClient implements Runnable { - private static final AxArtifactKey MODEL_KEY = new AxArtifactKey("Model", "0.0.1"); - private static final AxArtifactKey ENGINE_KEY = new AxArtifactKey("Engine", "0.0.1"); - private static final AxArtifactKey ENGINE_SERVICE_KEY = new AxArtifactKey("EngineService", "0.0.1"); - - private Thread thisThread; - - private final BlockingQueue<Message> receiveQueue = new LinkedBlockingQueue<>(); - - private boolean started = false; - - private boolean initSuccessful = false; - private boolean deployModelSuccessful = false; - private boolean startEngineSuccessful = false; - private boolean stopEngineSuccessful = false; - private boolean startPeriodicSuccessful = false; - private boolean stopPeriodicSuccessful = false; - private boolean statusSuccessful = false; - private boolean infoSuccessful = false; - - public DummyDeploymentClient(String host, int port) { - super(host, port); - } - - /** - * {@inheritDoc}. - */ - @Override - public void run() { - // Set up the thread name - thisThread = Thread.currentThread(); - thisThread.setName(DeploymentClient.class.getName() + "-" + getHost() + ":" + getPort()); - - started = true; - getCountDownLatch().get().countDown(); - // Loop forever, sending messages as they appear on the queue - await().atLeast(50, TimeUnit.MILLISECONDS).until(() -> !(started && !thisThread.isInterrupted())); - // Thread has been interrupted - thisThread = null; - started = false; - } - - /** - * Send an EngDep message to the Apex server. - * - * @param message the message to send to the Apex server - */ - @Override - public void sendMessage(final Message message) { - if (message instanceof GetEngineServiceInfo) { - handleEngineServiceInfo(message); - } else if (message instanceof UpdateModel) { - deployModelSuccessful = handleAndReturnMessage(message, deployModelSuccessful); - } else if (message instanceof StartEngine) { - startEngineSuccessful = handleAndReturnMessage(message, startEngineSuccessful); - } else if (message instanceof StopEngine) { - stopEngineSuccessful = handleAndReturnMessage(message, stopEngineSuccessful); - } else if (message instanceof StartPeriodicEvents) { - startPeriodicSuccessful = handleAndReturnMessage(message, startPeriodicSuccessful); - } else if (message instanceof StopPeriodicEvents) { - stopPeriodicSuccessful = handleAndReturnMessage(message, stopPeriodicSuccessful); - } else if (message instanceof GetEngineStatus) { - statusSuccessful = handleAndReturnEngineStatus(message, statusSuccessful); - } else if (message instanceof GetEngineInfo) { - infoSuccessful = handleAndReturnMessage(message, infoSuccessful); - } - } - - /** - * Handle the EngineServiceInfo message. - * - * @param message the EngineServiceInfo message - */ - private void handleEngineServiceInfo(final Message message) { - EngineServiceInfoResponse infoResponse = new EngineServiceInfoResponse(ENGINE_KEY, initSuccessful, message); - infoResponse.setApexModelKey(MODEL_KEY); - - List<AxArtifactKey> engineKeyList = new ArrayList<>(); - engineKeyList.add(ENGINE_KEY); - infoResponse.setEngineKeyArray(engineKeyList); - - infoResponse.setEngineServiceKey(ENGINE_SERVICE_KEY); - - receiveQueue.add(infoResponse); - } - - /** - * Handle and return the response to the engine status message. - * - * @param message the incoming status message - * @param successFlag true if the result should be successful - * @return engine status success or not - */ - private boolean handleAndReturnEngineStatus(Message message, boolean successFlag) { - if ("DoNotRespond".equals(message.getTarget().getName())) { - return !successFlag; - } - - if ("ReturnBadMessage".equals(message.getTarget().getName())) { - receiveQueue.add(message); - return !successFlag; - } - - if ("ReturnBadResponse".equals(message.getTarget().getName())) { - Response badResponse = new Response(ENGINE_KEY, successFlag, new StartEngine(message.getTarget())); - receiveQueue.add(badResponse); - return !successFlag; - } - - Response response = new Response(ENGINE_KEY, successFlag, message); - - if (successFlag) { - try { - response.setMessageData(TextFileUtils.getTextFileAsString("src/test/resources/models/SmallModel.json")); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - response.setMessageData("Operation failed"); - } - - receiveQueue.add(response); - return !successFlag; - } - - /** - * Handle and return a message. - * - * @param message the message - */ - private boolean handleAndReturnMessage(final Message message, final boolean successFlag) { - Response response = new Response(ENGINE_KEY, successFlag, message); - - if (successFlag) { - response.setMessageData("Operation was successful"); - } else { - response.setMessageData("Operation failed"); - } - - receiveQueue.add(response); - return !successFlag; - } - - /** - * Stop the deployment client. - */ - @Override - public void stopClient() { - if (thisThread != null) { - thisThread.interrupt(); - } - started = false; - getCountDownLatch().set(new CountDownLatch(1)); - } - - /** - * Allows users of this class to get a reference to the receive queue to receove - * messages. - * - * @return the receive queue - */ - @Override - public BlockingQueue<Message> getReceiveQueue() { - return receiveQueue; - } -} diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/EngineServiceFacadeTest.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/EngineServiceFacadeTest.java deleted file mode 100644 index 1740c7e55..000000000 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/EngineServiceFacadeTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. - * ================================================================================ - * 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.core.deployment; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.time.Duration; -import org.awaitility.Awaitility; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; - -/** - * Test the deployment web socket client. - */ -public class EngineServiceFacadeTest { - @Test - public void testEngineServiceFacade() throws Exception { - EngineServiceFacade facade = new EngineServiceFacade("localhost", 51273); - - final DummyDeploymentClient dummyDeploymentClient = new DummyDeploymentClient("aHost", 54553); - facade.setDeploymentClient(dummyDeploymentClient); - - // First init should fail due to our dummy client - dummyDeploymentClient.setInitSuccessful(false); - assertThatThrownBy(facade::init) - .hasMessage("could not handshake with server localhost:51273"); - assertNull(facade.getKey()); - assertNull(facade.getApexModelKey()); - assertNull(facade.getEngineKeyArray()); - - assertThatThrownBy(() -> facade.deployModel("src/test/resources/models/SamplePolicyModelJAVASCRIPT.json", - false, false)) - .hasMessage("could not deploy apex model, deployer is not initialized"); - - // Second init should work - Awaitility.await().atLeast(Duration.ofMillis(1000)); - dummyDeploymentClient.setInitSuccessful(true); - facade.init(); - - assertEquals("EngineService:0.0.1", facade.getKey().getId()); - assertEquals("Model:0.0.1", facade.getApexModelKey().getId()); - assertEquals("Engine:0.0.1", facade.getEngineKeyArray()[0].getId()); - - assertThatThrownBy(() -> facade.deployModel("src/test/resources/models/NonExistantModel.json", - false, false)) - .hasMessage("could not create apex model, could not read from file " - + "src/test/resources/models/NonExistantModel.json"); - assertThatThrownBy(() -> facade.deployModel("src/test/resources/models/JunkModel.json", - false, false)) - .hasMessage("could not deploy apex model from src/test/resources/models/JunkModel.json"); - - InputStream badStream = new ByteArrayInputStream("".getBytes()); - assertThatThrownBy(() -> facade.deployModel("MyModel", badStream, false, false)) - .hasMessage("format of input for Apex concept is neither JSON nor XML"); - InputStream closedStream = new ByteArrayInputStream("".getBytes()); - closedStream.close(); - - assertThatThrownBy(() -> facade.deployModel("MyModel", closedStream, false, false)) - .hasMessage("format of input for Apex concept is neither JSON nor XML"); - assertThatThrownBy(() -> facade.deployModel("src/test/resources/models/SmallModel.json", false, false)) - .hasMessage("could not deploy apex model from src/test/resources/models/SmallModel.json"); - facade.deployModel("src/test/resources/models/SmallModel.json", false, false); - - assertThatThrownBy(() -> facade.startEngine(facade.getEngineKeyArray()[0])) - .hasMessage("failed response Operation failed received from serverlocalhost:51273"); - facade.startEngine(facade.getEngineKeyArray()[0]); - - assertThatThrownBy(() -> facade.stopEngine(facade.getEngineKeyArray()[0])) - .hasMessage("failed response Operation failed received from serverlocalhost:51273"); - facade.stopEngine(facade.getEngineKeyArray()[0]); - - assertThatThrownBy(() -> facade.startPerioidicEvents(facade.getEngineKeyArray()[0], 1000)) - .hasMessage("failed response Operation failed received from serverlocalhost:51273"); - facade.startPerioidicEvents(facade.getEngineKeyArray()[0], 1000); - - assertThatThrownBy(() -> facade.stopPerioidicEvents(facade.getEngineKeyArray()[0])) - .hasMessage("failed response Operation failed received from serverlocalhost:51273"); - facade.stopPerioidicEvents(facade.getEngineKeyArray()[0]); - - assertThatThrownBy(() -> facade.getEngineStatus(facade.getEngineKeyArray()[0])) - .hasMessage("failed response Operation failed received from serverlocalhost:51273"); - facade.getEngineStatus(facade.getEngineKeyArray()[0]); - - assertThatThrownBy(() -> facade.getEngineInfo(facade.getEngineKeyArray()[0])) - .hasMessage("failed response Operation failed received from serverlocalhost:51273"); - facade.getEngineInfo(facade.getEngineKeyArray()[0]); - - assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("ReturnBadMessage", "0.0.1"))) - .hasMessage("response received from server is of incorrect type " - + "org.onap.policy.apex.core.protocols.engdep.messages.GetEngineStatus, should be of type " - + "org.onap.policy.apex.core.protocols.engdep.messages.Response"); - assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("ReturnBadResponse", "0.0.1"))) - .hasMessage("response received is not correct response to sent message GET_ENGINE_STATUS"); - assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("DoNotRespond", "0.0.1"))) - .hasMessage("no response received to sent message GET_ENGINE_STATUS"); - assertThatThrownBy(() -> facade.stopPerioidicEvents(facade.getEngineKeyArray()[0])) - .hasMessage("failed response Operation failed received from serverlocalhost:51273"); - - facade.stopPerioidicEvents(facade.getEngineKeyArray()[0]); - - facade.getEngineStatus(facade.getEngineKeyArray()[0]); - - assertThatThrownBy(() -> facade.getEngineInfo(facade.getEngineKeyArray()[0])) - .hasMessage("failed response Operation failed received from serverlocalhost:51273"); - - facade.getEngineInfo(facade.getEngineKeyArray()[0]); - - assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("ReturnBadMessage", "0.0.1"))) - .hasMessage("response received from server is of incorrect type " - + "org.onap.policy.apex.core.protocols.engdep.messages.GetEngineStatus, should be of type " - + "org.onap.policy.apex.core.protocols.engdep.messages.Response"); - assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("ReturnBadResponse", "0.0.1"))) - .hasMessage("response received is not correct response to sent message GET_ENGINE_STATUS"); - assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("DoNotRespond", "0.0.1"))) - .hasMessage("no response received to sent message GET_ENGINE_STATUS"); - facade.close(); - } -} diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/PeriodicEventManagerTest.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/PeriodicEventManagerTest.java deleted file mode 100644 index 99c95465f..000000000 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/PeriodicEventManagerTest.java +++ /dev/null @@ -1,213 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation. - * ================================================================================ - * 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.core.deployment; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.io.PrintStream; -import org.junit.Test; - -/** - * Test the periodic event manager utility. - */ -public class PeriodicEventManagerTest { - @Test - public void testPeroidicEventManagerBad() { - final String[] eventArgs = { "-h" }; - - assertThatThrownBy(() -> PeriodicEventManager.main(eventArgs)) - .hasMessageContaining("invalid arguments: [-h]"); - } - - @Test - public void testPeroidicEventManagerOk() { - final String[] eventArgs = { "Host", "43443", "start", "1000" }; - - assertThatThrownBy(() -> PeriodicEventManager.main(eventArgs)) - .hasMessage("periodic event setting failed on parameters Host 43443 true"); - } - - @Test - public void testPeroidicEventManagerNoOptions() { - final String[] eventArgs = new String[] {}; - - final String outputString = testPeriodicEventManagerConstructor(eventArgs); - - assertTrue(outputString - .contains("usage: PeriodicEventManager <server address> <port address> <start/stop> <periods in ms>")); - } - - @Test - public void testPeroidicEventManagerBadOptions() { - final String[] eventArgs = { "-zabbu" }; - - final String outputString = testPeriodicEventManagerConstructor(eventArgs); - - assertTrue(outputString - .contains("usage: PeriodicEventManager <server address> <port address> <start/stop> <periods in ms>")); - } - - @Test - public void testPeroidicEventManagerNonNumeric3() { - final String[] eventArgs = { "aaa", "bbb", "ccc", "ddd" }; - - final String outputString = testPeriodicEventManagerConstructor(eventArgs); - - assertTrue(outputString.contains("argument port is invalid")); - } - - @Test - public void testPeroidicEventManagerNonNumeric2() { - final String[] eventArgs = { "aaa", "12345", "start", "stop" }; - - final String outputString = testPeriodicEventManagerConstructor(eventArgs); - - assertTrue(outputString.contains("argument period is invalid")); - } - - @Test - public void testPeroidicEventManagerNotStartStop() { - final String[] eventArgs = { "aaa", "12345", "1000", "1000" }; - - final String outputString = testPeriodicEventManagerConstructor(eventArgs); - - assertTrue(outputString.contains("argument 1000 must be \"start\" or \"stop\"")); - } - - @Test - public void testPeroidicEventManagerStart() throws ApexDeploymentException { - final String[] eventArgs = { "localhost", "12345", "start", "1000" }; - - final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); - - PeriodicEventManager peManager = null; - final DummyDeploymentClient dummyDeploymentClient = new DummyDeploymentClient("aHost", 54553); - peManager = new PeriodicEventManager(eventArgs, new PrintStream(baosOut, true)); - peManager.getEngineServiceFacade().setDeploymentClient(dummyDeploymentClient); - - dummyDeploymentClient.setInitSuccessful(false); - assertThatThrownBy(peManager::init) - .hasMessage("periodic event setting failed on parameters localhost 12345 true"); - dummyDeploymentClient.setInitSuccessful(true); - peManager.init(); - - assertThatThrownBy(peManager::runCommand) - .hasMessage("failed response Operation failed received from serverlocalhost:12345"); - - peManager.close(); - } - - @Test - public void testPeroidicEventManagerStop() throws ApexDeploymentException { - - final String[] eventArgs = { "localhost", "12345", "stop", "1000" }; - - final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); - - PeriodicEventManager peManager = null; - final DummyDeploymentClient dummyDeploymentClient = new DummyDeploymentClient("aHost", 54553); - peManager = new PeriodicEventManager(eventArgs, new PrintStream(baosOut, true)); - peManager.getEngineServiceFacade().setDeploymentClient(dummyDeploymentClient); - - dummyDeploymentClient.setInitSuccessful(false); - assertThatThrownBy(peManager::init) - .hasMessage("periodic event setting failed on parameters localhost 12345 false"); - dummyDeploymentClient.setInitSuccessful(true); - peManager.init(); - - assertThatThrownBy(peManager::runCommand) - .hasMessage("failed response Operation failed received from serverlocalhost:12345"); - peManager.runCommand(); - - peManager.close(); - } - - @Test - public void testPeroidicEventManagerStartUninitialized() throws ApexDeploymentException { - - final String[] eventArgs = { "localhost", "12345", "start", "1000" }; - - final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); - - PeriodicEventManager peManager = null; - final DummyDeploymentClient dummyDeploymentClient = new DummyDeploymentClient("aHost", 54553); - peManager = new PeriodicEventManager(eventArgs, new PrintStream(baosOut, true)); - peManager.getEngineServiceFacade().setDeploymentClient(dummyDeploymentClient); - - dummyDeploymentClient.setInitSuccessful(false); - assertThatThrownBy(peManager::runCommand) - .hasMessage("connection to apex is not initialized"); - dummyDeploymentClient.setInitSuccessful(true); - assertThatThrownBy(peManager::runCommand) - .hasMessage("connection to apex is not initialized"); - - peManager.close(); - } - - @Test - public void testPeroidicEventManagerStopUninitialized() throws ApexDeploymentException { - - final String[] eventArgs = { "localhost", "12345", "stop", "1000" }; - - final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); - - PeriodicEventManager peManager = null; - peManager = new PeriodicEventManager(eventArgs, new PrintStream(baosOut, true)); - peManager.getEngineServiceFacade().setDeploymentClient(new DummyDeploymentClient("aHost", 54553)); - - assertThatThrownBy(peManager::runCommand) - .hasMessage("connection to apex is not initialized"); - peManager.close(); - } - - /** - * Run the application. - * - * @param eventArgs the command arguments - * @return a string containing the command output - */ - private String testPeriodicEventManagerConstructor(final String[] eventArgs) { - final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); - final ByteArrayOutputStream baosErr = new ByteArrayOutputStream(); - - String exceptionString = ""; - try { - PeriodicEventManager peManager = new PeriodicEventManager(eventArgs, new PrintStream(baosOut, true)); - peManager.getEngineServiceFacade().setDeploymentClient(new DummyDeploymentClient("aHost", 54553)); - } catch (ApexDeploymentException ade) { - exceptionString = ade.getCascadedMessage(); - } - - InputStream testInput = new ByteArrayInputStream("Test Data for Input to WS".getBytes()); - System.setIn(testInput); - - String outString = baosOut.toString(); - String errString = baosErr.toString(); - - return "*** StdOut ***\n" + outString + "\n*** StdErr ***\n" + errString + "\n*** exception ***\n" - + exceptionString; - } -} diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/SupportMessageListenerTester.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/SupportMessageListenerTester.java deleted file mode 100644 index 3ee6a4b51..000000000 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/SupportMessageListenerTester.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.core.deployment; - -import static org.junit.Assert.fail; - -import org.onap.policy.apex.core.infrastructure.messaging.MessageListener; -import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlock; -import org.onap.policy.apex.core.protocols.Message; - -/** - * A test message listener. - */ -public class SupportMessageListenerTester implements MessageListener<Message> { - @Override - public void onMessage(String messageString) { - fail("Message should not be received"); - } - - @Override - public void onMessage(MessageBlock<Message> data) { - fail("Message should not be received"); - } -} diff --git a/core/core-deployment/src/test/resources/models/JunkModel.json b/core/core-deployment/src/test/resources/models/JunkModel.json deleted file mode 100644 index 7a73a41bf..000000000 --- a/core/core-deployment/src/test/resources/models/JunkModel.json +++ /dev/null @@ -1,2 +0,0 @@ -{ -}
\ No newline at end of file diff --git a/core/core-deployment/src/test/resources/models/SmallModel.json b/core/core-deployment/src/test/resources/models/SmallModel.json deleted file mode 100644 index 5c0628809..000000000 --- a/core/core-deployment/src/test/resources/models/SmallModel.json +++ /dev/null @@ -1,416 +0,0 @@ -{ - "apexPolicyModel" : { - "key" : { - "name" : "SmallModel", - "version" : "0.0.1" - }, - "keyInformation" : { - "key" : { - "name" : "SmallModel_KeyInfo", - "version" : "0.0.1" - }, - "keyInfoMap" : { - "entry" : [ { - "key" : { - "name" : "BasicContextAlbum", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "BasicContextAlbum", - "version" : "0.0.1" - }, - "UUID" : "fec1b353-b35f-4384-b7d9-69622059c248", - "description" : "Generated description for a concept called \"BasicContextAlbum\" with version \"0.0.1\" and UUID \"fec1b353-b35f-4384-b7d9-69622059c248\"" - } - }, { - "key" : { - "name" : "BasicEvent", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "BasicEvent", - "version" : "0.0.1" - }, - "UUID" : "cc8d3c1a-e975-459a-bcd2-69f423eaa1f3", - "description" : "Generated description for a concept called \"BasicEvent\" with version \"0.0.1\" and UUID \"cc8d3c1a-e975-459a-bcd2-69f423eaa1f3\"" - } - }, { - "key" : { - "name" : "BasicPolicy", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "BasicPolicy", - "version" : "0.0.1" - }, - "UUID" : "d0c5d8ee-5fe7-4978-89ce-4a3e69cad043", - "description" : "Generated description for a concept called \"BasicPolicy\" with version \"0.0.1\" and UUID \"d0c5d8ee-5fe7-4978-89ce-4a3e69cad043\"" - } - }, { - "key" : { - "name" : "BasicTask", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "BasicTask", - "version" : "0.0.1" - }, - "UUID" : "c5651414-fc1c-493b-878d-75f0ce685c36", - "description" : "Generated description for a concept called \"BasicTask\" with version \"0.0.1\" and UUID \"c5651414-fc1c-493b-878d-75f0ce685c36\"" - } - }, { - "key" : { - "name" : "IntType", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "IntType", - "version" : "0.0.1" - }, - "UUID" : "790ff718-8dc0-44e0-89d8-1b3bbe238310", - "description" : "Generated description for a concept called \"IntType\" with version \"0.0.1\" and UUID \"790ff718-8dc0-44e0-89d8-1b3bbe238310\"" - } - }, { - "key" : { - "name" : "SmallModel", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "SmallModel", - "version" : "0.0.1" - }, - "UUID" : "a1bd1f4e-713b-456b-b1a8-bb48beee28e8", - "description" : "Generated description for a concept called \"SmallModel\" with version \"0.0.1\" and UUID \"a1bd1f4e-713b-456b-b1a8-bb48beee28e8\"" - } - }, { - "key" : { - "name" : "SmallModel_Albums", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "SmallModel_Albums", - "version" : "0.0.1" - }, - "UUID" : "72bed9af-ab7d-3379-b9f7-b5eca5c9ef22", - "description" : "Generated description for concept referred to by key \"SmallModel_Albums:0.0.1\"" - } - }, { - "key" : { - "name" : "SmallModel_Events", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "SmallModel_Events", - "version" : "0.0.1" - }, - "UUID" : "796dc6b0-627d-34ae-a5e2-1bc4b4b486b8", - "description" : "Generated description for concept referred to by key \"SmallModel_Events:0.0.1\"" - } - }, { - "key" : { - "name" : "SmallModel_KeyInfo", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "SmallModel_KeyInfo", - "version" : "0.0.1" - }, - "UUID" : "b4876774-6907-3d27-a2b8-f05737c5ee4a", - "description" : "Generated description for concept referred to by key \"SmallModel_KeyInfo:0.0.1\"" - } - }, { - "key" : { - "name" : "SmallModel_Policies", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "SmallModel_Policies", - "version" : "0.0.1" - }, - "UUID" : "5bcf946b-67be-3190-a906-f954896f999f", - "description" : "Generated description for concept referred to by key \"SmallModel_Policies:0.0.1\"" - } - }, { - "key" : { - "name" : "SmallModel_Schemas", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "SmallModel_Schemas", - "version" : "0.0.1" - }, - "UUID" : "c25bf5c3-7f1e-3667-b8a9-971ba21517bc", - "description" : "Generated description for concept referred to by key \"SmallModel_Schemas:0.0.1\"" - } - }, { - "key" : { - "name" : "SmallModel_Tasks", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "SmallModel_Tasks", - "version" : "0.0.1" - }, - "UUID" : "43b015ca-2ed1-3a35-b103-e8a5aa68f1ef", - "description" : "Generated description for concept referred to by key \"SmallModel_Tasks:0.0.1\"" - } - } ] - } - }, - "policies" : { - "key" : { - "name" : "SmallModel_Policies", - "version" : "0.0.1" - }, - "policyMap" : { - "entry" : [ { - "key" : { - "name" : "BasicPolicy", - "version" : "0.0.1" - }, - "value" : { - "policyKey" : { - "name" : "BasicPolicy", - "version" : "0.0.1" - }, - "template" : "FREEFORM", - "state" : { - "entry" : [ { - "key" : "OnlyState", - "value" : { - "stateKey" : { - "parentKeyName" : "BasicPolicy", - "parentKeyVersion" : "0.0.1", - "parentLocalName" : "NULL", - "localName" : "OnlyState" - }, - "trigger" : { - "name" : "BasicEvent", - "version" : "0.0.1" - }, - "stateOutputs" : { - "entry" : [ { - "key" : "OnlyOutput", - "value" : { - "key" : { - "parentKeyName" : "BasicPolicy", - "parentKeyVersion" : "0.0.1", - "parentLocalName" : "OnlyState", - "localName" : "OnlyOutput" - }, - "outgoingEvent" : { - "name" : "BasicEvent", - "version" : "0.0.1" - }, - "nextState" : { - "parentKeyName" : "NULL", - "parentKeyVersion" : "0.0.0", - "parentLocalName" : "NULL", - "localName" : "NULL" - } - } - } ] - }, - "contextAlbumReference" : [ { - "name" : "BasicContextAlbum", - "version" : "0.0.1" - } ], - "taskSelectionLogic" : { - "key" : "NULL", - "logicFlavour" : "UNDEFINED", - "logic" : "" - }, - "stateFinalizerLogicMap" : { - "entry" : [ ] - }, - "defaultTask" : { - "name" : "BasicTask", - "version" : "0.0.1" - }, - "taskReferences" : { - "entry" : [ { - "key" : { - "name" : "BasicTask", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "parentKeyName" : "BasicPolicy", - "parentKeyVersion" : "0.0.1", - "parentLocalName" : "OnlyState", - "localName" : "BasicTask" - }, - "outputType" : "DIRECT", - "output" : { - "parentKeyName" : "BasicPolicy", - "parentKeyVersion" : "0.0.1", - "parentLocalName" : "OnlyState", - "localName" : "OnlyOutput" - } - } - } ] - } - } - } ] - }, - "firstState" : "OnlyState" - } - } ] - } - }, - "tasks" : { - "key" : { - "name" : "SmallModel_Tasks", - "version" : "0.0.1" - }, - "taskMap" : { - "entry" : [ { - "key" : { - "name" : "BasicTask", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "BasicTask", - "version" : "0.0.1" - }, - "inputFields" : { - "entry" : [ { - "key" : "intPar", - "value" : { - "key" : "intPar", - "fieldSchemaKey" : { - "name" : "IntType", - "version" : "0.0.1" - }, - "optional" : false - } - } ] - }, - "outputFields" : { - "entry" : [ { - "key" : "intPar", - "value" : { - "key" : "intPar", - "fieldSchemaKey" : { - "name" : "IntType", - "version" : "0.0.1" - }, - "optional" : false - } - } ] - }, - "taskParameters" : { - "entry" : [ ] - }, - "contextAlbumReference" : [ { - "name" : "BasicContextAlbum", - "version" : "0.0.1" - } ], - "taskLogic" : { - "key" : "TaskLogic", - "logicFlavour" : "JAVASCRIPT", - "logic" : "executor.logger.debug(executor.subject.id);\nvar gc = executor.getContextAlbum(\"BasicContextAlbum\");\nexecutor.logger.debug(gc.name);\nexecutor.logger.debug(executor.inFields);\n\nexecutor.logger.debug(executor.eo);\n\nvar returnValue = executor.isTrue;" - } - } - } ] - } - }, - "events" : { - "key" : { - "name" : "SmallModel_Events", - "version" : "0.0.1" - }, - "eventMap" : { - "entry" : [ { - "key" : { - "name" : "BasicEvent", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "BasicEvent", - "version" : "0.0.1" - }, - "nameSpace" : "org.onap.policy.apex.events", - "source" : "source", - "target" : "target", - "parameter" : { - "entry" : [ { - "key" : "intPar", - "value" : { - "key" : "intPar", - "fieldSchemaKey" : { - "name" : "IntType", - "version" : "0.0.1" - }, - "optional" : false - } - } ] - } - } - } ] - } - }, - "albums" : { - "key" : { - "name" : "SmallModel_Albums", - "version" : "0.0.1" - }, - "albums" : { - "entry" : [ { - "key" : { - "name" : "BasicContextAlbum", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "BasicContextAlbum", - "version" : "0.0.1" - }, - "scope" : "GLOBAL", - "isWritable" : true, - "itemSchema" : { - "name" : "IntType", - "version" : "0.0.1" - } - } - } ] - } - }, - "schemas" : { - "key" : { - "name" : "SmallModel_Schemas", - "version" : "0.0.1" - }, - "schemas" : { - "entry" : [ { - "key" : { - "name" : "IntType", - "version" : "0.0.1" - }, - "value" : { - "key" : { - "name" : "IntType", - "version" : "0.0.1" - }, - "schemaFlavour" : "Java", - "schemaDefinition" : "java.lang.Integer" - } - } ] - } - } - } -} |