diff options
author | mmis <michael.morris@ericsson.com> | 2018-07-19 13:21:08 +0100 |
---|---|---|
committer | mmis <michael.morris@ericsson.com> | 2018-07-25 09:14:33 +0100 |
commit | 64f53ef14f5a9ea98208fd2b835bfb01fda9a5f9 (patch) | |
tree | 60afa251c126287a85c89e0b1dc7fd5d1a766439 | |
parent | e8f1b7235f8338fbb9eba28d8cff29d3d6adf6e7 (diff) |
Copy policy-endpoints from drools-pdp to common
Removed policy-endpoints, and 3 classes from policy-core. Replaced
refenences to the deleted classes with references to the corresponding
classes in policy-common
Issue-ID: POLICY-967
Change-Id: I547cde4894424b8f40b7ddd4e2342ebb729cb588
Signed-off-by: mmis <michael.morris@ericsson.com>
92 files changed, 7607 insertions, 16498 deletions
diff --git a/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureAPI.java b/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureAPI.java index 107b207e..3afd0c74 100644 --- a/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureAPI.java +++ b/api-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeatureAPI.java @@ -24,185 +24,189 @@ import java.util.Observer; import javax.validation.constraints.NotNull; +import org.onap.policy.common.capabilities.Lockable; import org.onap.policy.common.im.AllSeemsWellException; import org.onap.policy.common.im.StateManagement; -import org.onap.policy.drools.properties.Lockable; import org.onap.policy.drools.utils.OrderedService; import org.onap.policy.drools.utils.OrderedServiceImpl; /** - * This interface provides a way to invoke optional features at various - * points in the code. At appropriate points in the - * application, the code iterates through this list, invoking these optional - * methods. Most of the methods here are notification only -- these tend to - * return a 'void' value. In other cases, such as 'activatePolicySession', - * may + * This interface provides a way to invoke optional features at various points in the code. At + * appropriate points in the application, the code iterates through this list, invoking these + * optional methods. Most of the methods here are notification only -- these tend to return a 'void' + * value. In other cases, such as 'activatePolicySession', may */ -public interface StateManagementFeatureAPI extends OrderedService, Lockable -{ - - public static final String LOCKED = StateManagement.LOCKED; - public static final String UNLOCKED = StateManagement.UNLOCKED; - public static final String ENABLED = StateManagement.ENABLED; - public static final String DISABLED = StateManagement.DISABLED; - public static final String ENABLE_NOT_FAILED = StateManagement.ENABLE_NOT_FAILED; - public static final String DISABLE_FAILED = StateManagement.DISABLE_FAILED; - public static final String FAILED = StateManagement.FAILED; - public static final String DEPENDENCY = StateManagement.DEPENDENCY; - public static final String DEPENDENCY_FAILED = StateManagement.DEPENDENCY_FAILED; - public static final String DISABLE_DEPENDENCY = StateManagement.DISABLE_DEPENDENCY; - public static final String ENABLE_NO_DEPENDENCY = StateManagement.ENABLE_NO_DEPENDENCY; - public static final String NULL_VALUE = StateManagement.NULL_VALUE; - public static final String DO_LOCK = StateManagement.LOCK; - public static final String DO_UNLOCK = StateManagement.UNLOCK; - public static final String DO_PROMOTE = StateManagement.PROMOTE; - public static final String DO_DEMOTE = StateManagement.DEMOTE; - public static final String HOT_STANDBY = StateManagement.HOT_STANDBY; - public static final String COLD_STANDBY = StateManagement.COLD_STANDBY; - public static final String PROVIDING_SERVICE = StateManagement.PROVIDING_SERVICE; - - public static final String ADMIN_STATE = StateManagement.ADMIN_STATE; - public static final String OPERATION_STATE = StateManagement.OPERATION_STATE; - public static final String AVAILABLE_STATUS= StateManagement.AVAILABLE_STATUS; - public static final String STANDBY_STATUS = StateManagement.STANDBY_STATUS; - - public static final Boolean ALLSEEMSWELL_STATE = Boolean.TRUE; - public static final Boolean ALLNOTWELL_STATE = Boolean.FALSE; - - public static final int SEQ_NUM = 0; - /** - * 'FeatureAPI.impl.getList()' returns an ordered list of objects - * implementing the 'FeatureAPI' interface. - */ - public static OrderedServiceImpl<StateManagementFeatureAPI> impl = - new OrderedServiceImpl<>(StateManagementFeatureAPI.class); - - /** - * ALL SEEMS/NOT WELL - * This interface is used to support the concept of All Seems/Not Well. It provides - * a way for client code to indicate to the DroolsPDPIntegrityMonitor that an event - * has occurred which is disabling (or enabling) for the Drools PDP. The call is - * actually implemented in the common modules IntegrityMonitor where it will cause - * the testTransaction to fail if any module has set the value ALLNOTWELL, stopping - * the forward progress counter and eventually causing the operational state to - * become disabled. - * - * ALLSEEMSWELL is passed to the method when the client is healthy - * ALLNOTWELL is passed to the method when the client is disabled - * - * @param key - This should be a unique identifier for the entity making the call (e.g., class name) - * @param asw - This is the indicator of health. See constants: ALLSEEMSWELL or ALLNOTWELL - * @param msg - A message is required. It should indicate why all is not well or a message indicating - * that a component has been restored to health (perhaps indicating the problem that has resolved). - * @throws AllSeemsWellException - */ - public void allSeemsWell(@NotNull String key, @NotNull Boolean asw, @NotNull String msg) - throws AllSeemsWellException; - - /** - * This method is called to add an Observer to receive notifications of state changes - * - * @param stateChangeObserver - */ - public void addObserver(Observer stateChangeObserver); - - /** - * This method returns the X.731 Administrative State for this resource - * - * @return String (locked, unlocked) - */ - public String getAdminState(); - - /** - * This method returns the X.731 Operational State for this resource - * - * @return String (enabled, disabled) - */ - public String getOpState(); - - /** - * This method returns the X.731 Availability Status for this resource - * - * @return String (failed; dependency; dependency,failed) - */ - public String getAvailStatus(); - - /** - * This method returns the X.731 Standby Status for this resource - * - * @return String (providingservice, hotstandby or coldstandby) - */ - public String getStandbyStatus(); - - /** - * This method returns the X.731 Standby Status for the named resource - * @param String (resourceName) - * @return String (providingservice, hotstandby or coldstandby) - */ - public String getStandbyStatus(String resourceName); - - /** - * This method moves the X.731 Operational State for the named resource - * into a value of disabled and the Availability Status to a value of failed. - * As a consequence the Standby Status value will take a value of coldstandby. - * - * @param String (resourceName) - * @throws Exception - */ - public void disableFailed(String resourceName) throws Exception; - - /** - * This method moves the X.731 Operational State for this resource - * into a value of disabled and the Availability Status to a value of failed. - * As a consequence the Standby Status value will take a value of coldstandby. - * - * @param String (resourceName) - * @throws Exception - */ - public void disableFailed() throws Exception; - - /** - * This method moves the X.731 Standby Status for this resource from hotstandby - * to providingservice. If the current value is coldstandby, no change is made. - * If the current value is null, it will move to providingservice assuming the - * Operational State is enabled and Administrative State is unlocked. - * @throws Exception - */ - public void promote() throws Exception; - - /** - * This method moves the X.731 Standby Status for this resource from providingservice - * to hotstandby. If the current value is null, it will move to hotstandby assuming the - * Operational State is enabled and Administrative State is unlocked. Else, it will move - * to coldstandby - * @throws Exception - */ - public void demote() throws Exception; - - /** - * This method returns the resourceName associated with this instance of the StateManagementFeature - * @return String (resourceName) - */ - public String getResourceName(); - - /** - * This Lockable method will lock the StateManagement object Admin state - * @return true if successfull, false otherwise - */ - @Override - public boolean lock(); - - /** - * This Lockable method will unlock the StateManagement object Admin state - * @return true if successfull, false otherwise - */ - @Override - public boolean unlock(); - - /** - * This Lockable method indicates the Admin state StateManagement object - * @return true if locked, false otherwise - */ - @Override - public boolean isLocked(); +public interface StateManagementFeatureAPI extends OrderedService, Lockable { + + public static final String LOCKED = StateManagement.LOCKED; + public static final String UNLOCKED = StateManagement.UNLOCKED; + public static final String ENABLED = StateManagement.ENABLED; + public static final String DISABLED = StateManagement.DISABLED; + public static final String ENABLE_NOT_FAILED = StateManagement.ENABLE_NOT_FAILED; + public static final String DISABLE_FAILED = StateManagement.DISABLE_FAILED; + public static final String FAILED = StateManagement.FAILED; + public static final String DEPENDENCY = StateManagement.DEPENDENCY; + public static final String DEPENDENCY_FAILED = StateManagement.DEPENDENCY_FAILED; + public static final String DISABLE_DEPENDENCY = StateManagement.DISABLE_DEPENDENCY; + public static final String ENABLE_NO_DEPENDENCY = StateManagement.ENABLE_NO_DEPENDENCY; + public static final String NULL_VALUE = StateManagement.NULL_VALUE; + public static final String DO_LOCK = StateManagement.LOCK; + public static final String DO_UNLOCK = StateManagement.UNLOCK; + public static final String DO_PROMOTE = StateManagement.PROMOTE; + public static final String DO_DEMOTE = StateManagement.DEMOTE; + public static final String HOT_STANDBY = StateManagement.HOT_STANDBY; + public static final String COLD_STANDBY = StateManagement.COLD_STANDBY; + public static final String PROVIDING_SERVICE = StateManagement.PROVIDING_SERVICE; + + public static final String ADMIN_STATE = StateManagement.ADMIN_STATE; + public static final String OPERATION_STATE = StateManagement.OPERATION_STATE; + public static final String AVAILABLE_STATUS = StateManagement.AVAILABLE_STATUS; + public static final String STANDBY_STATUS = StateManagement.STANDBY_STATUS; + + public static final Boolean ALLSEEMSWELL_STATE = Boolean.TRUE; + public static final Boolean ALLNOTWELL_STATE = Boolean.FALSE; + + public static final int SEQ_NUM = 0; + /** + * 'FeatureAPI.impl.getList()' returns an ordered list of objects implementing the 'FeatureAPI' + * interface. + */ + public static OrderedServiceImpl<StateManagementFeatureAPI> impl = + new OrderedServiceImpl<>(StateManagementFeatureAPI.class); + + /** + * ALL SEEMS/NOT WELL This interface is used to support the concept of All Seems/Not Well. It + * provides a way for client code to indicate to the DroolsPDPIntegrityMonitor that an event has + * occurred which is disabling (or enabling) for the Drools PDP. The call is actually + * implemented in the common modules IntegrityMonitor where it will cause the testTransaction to + * fail if any module has set the value ALLNOTWELL, stopping the forward progress counter and + * eventually causing the operational state to become disabled. + * + * ALLSEEMSWELL is passed to the method when the client is healthy ALLNOTWELL is passed to the + * method when the client is disabled + * + * @param key - This should be a unique identifier for the entity making the call (e.g., class + * name) + * @param asw - This is the indicator of health. See constants: ALLSEEMSWELL or ALLNOTWELL + * @param msg - A message is required. It should indicate why all is not well or a message + * indicating that a component has been restored to health (perhaps indicating the + * problem that has resolved). + * @throws AllSeemsWellException + */ + public void allSeemsWell(@NotNull String key, @NotNull Boolean asw, @NotNull String msg) + throws AllSeemsWellException; + + /** + * This method is called to add an Observer to receive notifications of state changes + * + * @param stateChangeObserver + */ + public void addObserver(Observer stateChangeObserver); + + /** + * This method returns the X.731 Administrative State for this resource + * + * @return String (locked, unlocked) + */ + public String getAdminState(); + + /** + * This method returns the X.731 Operational State for this resource + * + * @return String (enabled, disabled) + */ + public String getOpState(); + + /** + * This method returns the X.731 Availability Status for this resource + * + * @return String (failed; dependency; dependency,failed) + */ + public String getAvailStatus(); + + /** + * This method returns the X.731 Standby Status for this resource + * + * @return String (providingservice, hotstandby or coldstandby) + */ + public String getStandbyStatus(); + + /** + * This method returns the X.731 Standby Status for the named resource + * + * @param String (resourceName) + * @return String (providingservice, hotstandby or coldstandby) + */ + public String getStandbyStatus(String resourceName); + + /** + * This method moves the X.731 Operational State for the named resource into a value of disabled + * and the Availability Status to a value of failed. As a consequence the Standby Status value + * will take a value of coldstandby. + * + * @param String (resourceName) + * @throws Exception + */ + public void disableFailed(String resourceName) throws Exception; + + /** + * This method moves the X.731 Operational State for this resource into a value of disabled and + * the Availability Status to a value of failed. As a consequence the Standby Status value will + * take a value of coldstandby. + * + * @param String (resourceName) + * @throws Exception + */ + public void disableFailed() throws Exception; + + /** + * This method moves the X.731 Standby Status for this resource from hotstandby to + * providingservice. If the current value is coldstandby, no change is made. If the current + * value is null, it will move to providingservice assuming the Operational State is enabled and + * Administrative State is unlocked. + * + * @throws Exception + */ + public void promote() throws Exception; + + /** + * This method moves the X.731 Standby Status for this resource from providingservice to + * hotstandby. If the current value is null, it will move to hotstandby assuming the Operational + * State is enabled and Administrative State is unlocked. Else, it will move to coldstandby + * + * @throws Exception + */ + public void demote() throws Exception; + + /** + * This method returns the resourceName associated with this instance of the + * StateManagementFeature + * + * @return String (resourceName) + */ + public String getResourceName(); + + /** + * This Lockable method will lock the StateManagement object Admin state + * + * @return true if successfull, false otherwise + */ + @Override + public boolean lock(); + + /** + * This Lockable method will unlock the StateManagement object Admin state + * + * @return true if successfull, false otherwise + */ + @Override + public boolean unlock(); + + /** + * This Lockable method indicates the Admin state StateManagement object + * + * @return true if locked, false otherwise + */ + @Override + public boolean isLocked(); } diff --git a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PMStandbyStateChangeNotifier.java b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PMStandbyStateChangeNotifier.java index 84cc8dbd..8519cdbb 100644 --- a/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PMStandbyStateChangeNotifier.java +++ b/feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/PMStandbyStateChangeNotifier.java @@ -66,7 +66,7 @@ import org.onap.policy.drools.system.PolicyEngine; * the demote), but providingservice (as reset by the election handling logic) and conn.standDownPdp() would not get called! * * To fix this bug, we consolidated StandbyStateChangeNotifier and PMStandbyStateChangeNotifier, with the standDownPdp() always - * being invoked prior to the TopicEndpoint.manager.lock(). In this way, when the election handling logic is invoked + * being invoked prior to the ProxyTopicEndpointManager.getInstance().lock(). In this way, when the election handling logic is invoked * during the controller stoppages, the PDP is in hotstandby and the standdown occurs. * */ diff --git a/feature-healthcheck/pom.xml b/feature-healthcheck/pom.xml index d3625257..50afc0ac 100644 --- a/feature-healthcheck/pom.xml +++ b/feature-healthcheck/pom.xml @@ -104,7 +104,7 @@ <scope>provided</scope> </dependency> <dependency> - <groupId>org.onap.policy.drools-pdp</groupId> + <groupId>org.onap.policy.common</groupId> <artifactId>policy-endpoints</artifactId> <version>${project.version}</version> <scope>provided</scope> diff --git a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java index fb3da657..9c543412 100644 --- a/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java +++ b/feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheck.java @@ -26,10 +26,12 @@ import java.util.Properties; import javax.ws.rs.core.Response; -import org.onap.policy.drools.http.client.HttpClient; -import org.onap.policy.drools.http.server.HttpServletServer; +import org.onap.policy.common.capabilities.Startable; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.impl.IndexedHttpClientFactory; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.http.server.impl.IndexedHttpServletServerFactory; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.Startable; import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,56 +41,56 @@ import org.slf4j.LoggerFactory; */ public interface HealthCheck extends Startable { - /** - * Healthcheck Monitor - */ - public static final HealthCheck monitor = new HealthCheckMonitor(); - - /** - * Healthcheck Report - */ - public static class Report { - /** - * Named Entity in the report - */ - private String name; - - /** - * URL queried - */ - private String url; - - /** - * healthy? - */ - private boolean healthy; - - /** - * return code - */ - private int code; - - /** - * Message from remote entity - */ - private String message; - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Report [name="); - builder.append(getName()); - builder.append(", url="); - builder.append(getUrl()); - builder.append(", healthy="); - builder.append(isHealthy()); - builder.append(", code="); - builder.append(getCode()); - builder.append(", message="); - builder.append(getMessage()); - builder.append("]"); - return builder.toString(); - } + /** + * Healthcheck Monitor + */ + public static final HealthCheck monitor = new HealthCheckMonitor(); + + /** + * Healthcheck Report + */ + public static class Report { + /** + * Named Entity in the report + */ + private String name; + + /** + * URL queried + */ + private String url; + + /** + * healthy? + */ + private boolean healthy; + + /** + * return code + */ + private int code; + + /** + * Message from remote entity + */ + private String message; + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Report [name="); + builder.append(getName()); + builder.append(", url="); + builder.append(getUrl()); + builder.append(", healthy="); + builder.append(isHealthy()); + builder.append(", code="); + builder.append(getCode()); + builder.append(", message="); + builder.append(getMessage()); + builder.append("]"); + return builder.toString(); + } public String getName() { return name; @@ -129,25 +131,25 @@ public interface HealthCheck extends Startable { public void setMessage(String message) { this.message = message; } - } - - /** - * Report aggregation - */ - public static class Reports { - private boolean healthy; - private List<Report> details = new ArrayList<>(); - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("Reports [healthy="); - builder.append(isHealthy()); - builder.append(", details="); - builder.append(getDetails()); - builder.append("]"); - return builder.toString(); - } + } + + /** + * Report aggregation + */ + public static class Reports { + private boolean healthy; + private List<Report> details = new ArrayList<>(); + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Reports [healthy="); + builder.append(isHealthy()); + builder.append(", details="); + builder.append(getDetails()); + builder.append("]"); + return builder.toString(); + } public boolean isHealthy() { return healthy; @@ -164,188 +166,190 @@ public interface HealthCheck extends Startable { public void setDetails(List<Report> details) { this.details = details; } - } - - /** - * perform a healthcheck - * @return a report - */ - public Reports healthCheck(); + } + + /** + * perform a healthcheck + * + * @return a report + */ + public Reports healthCheck(); } + /** * Healthcheck Monitor */ class HealthCheckMonitor implements HealthCheck { - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(HealthCheckMonitor.class); - - /** - * attached http servers - */ - protected volatile List<HttpServletServer> servers = new ArrayList<>(); - - /** - * attached http clients - */ - protected volatile List<HttpClient> clients = new ArrayList<>(); - - /** - * healthcheck configuration - */ - protected volatile Properties healthCheckProperties = null; - - /** - * {@inheritDoc} - */ - @Override - public Reports healthCheck() { - Reports reports = new Reports(); - reports.setHealthy(PolicyEngine.manager.isAlive()); - - HealthCheck.Report engineReport = new Report(); - engineReport.setHealthy(PolicyEngine.manager.isAlive()); - engineReport.setName("PDP-D"); - engineReport.setUrl("self"); - engineReport.setCode(PolicyEngine.manager.isAlive() ? 200 : 500); - engineReport.setMessage(PolicyEngine.manager.isAlive() ? "alive" : "not alive"); - reports.getDetails().add(engineReport); - - for (HttpClient client : clients) { - HealthCheck.Report report = new Report(); - report.setName(client.getName()); - report.setUrl(client.getBaseUrl()); - report.setHealthy(true); - try { - Response response = client.get(); - report.setCode(response.getStatus()); - if (report.getCode() != 200) { - report.setHealthy(false); - reports.setHealthy(false); - } - - report.setMessage(getHttpBody(response, client)); - } catch (Exception e) { - logger.warn("{}: cannot contact http-client {}", this, client, e); - - report.setHealthy(false); - reports.setHealthy(false); - } - reports.getDetails().add(report); - } - return reports; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean start() { - - try { - this.healthCheckProperties = SystemPersistence.manager.getProperties(HealthCheckFeature.CONFIGURATION_PROPERTIES_NAME); - this.servers = HttpServletServer.factory.build(healthCheckProperties); - this.clients = HttpClient.factory.build(healthCheckProperties); - - for (HttpServletServer server : servers) { - startServer(server); - } - } catch (Exception e) { - logger.warn("{}: cannot start {}", this, e); - return false; - } - - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean stop() { - - for (HttpServletServer server : servers) { - try { - server.stop(); - } catch (Exception e) { - logger.warn("{}: cannot stop http-server {}", this, server, e); - } - } - - for (HttpClient client : clients) { - try { - client.stop(); - } catch (Exception e) { - logger.warn("{}: cannot stop http-client {}", this, client, e); - } - } - - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public void shutdown() { - this.stop(); - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized boolean isAlive() { - return this.healthCheckProperties != null; - } - - /** - * @return list of attached Http Servers - */ - public List<HttpServletServer> getServers() { - return this.servers; - } - - /** - * @return list of attached Http Clients - */ - public List<HttpClient> getClients() { - return this.clients; - } - - public String getHttpBody(Response response, HttpClient client) { - - String body = null; + /** + * Logger + */ + private static Logger logger = LoggerFactory.getLogger(HealthCheckMonitor.class); + + /** + * attached http servers + */ + protected volatile List<HttpServletServer> servers = new ArrayList<>(); + + /** + * attached http clients + */ + protected volatile List<HttpClient> clients = new ArrayList<>(); + + /** + * healthcheck configuration + */ + protected volatile Properties healthCheckProperties = null; + + /** + * {@inheritDoc} + */ + @Override + public Reports healthCheck() { + Reports reports = new Reports(); + reports.setHealthy(PolicyEngine.manager.isAlive()); + + HealthCheck.Report engineReport = new Report(); + engineReport.setHealthy(PolicyEngine.manager.isAlive()); + engineReport.setName("PDP-D"); + engineReport.setUrl("self"); + engineReport.setCode(PolicyEngine.manager.isAlive() ? 200 : 500); + engineReport.setMessage(PolicyEngine.manager.isAlive() ? "alive" : "not alive"); + reports.getDetails().add(engineReport); + + for (HttpClient client : clients) { + HealthCheck.Report report = new Report(); + report.setName(client.getName()); + report.setUrl(client.getBaseUrl()); + report.setHealthy(true); + try { + Response response = client.get(); + report.setCode(response.getStatus()); + if (report.getCode() != 200) { + report.setHealthy(false); + reports.setHealthy(false); + } + + report.setMessage(getHttpBody(response, client)); + } catch (Exception e) { + logger.warn("{}: cannot contact http-client {}", this, client, e); + + report.setHealthy(false); + reports.setHealthy(false); + } + reports.getDetails().add(report); + } + return reports; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean start() { + + try { + this.healthCheckProperties = + SystemPersistence.manager.getProperties(HealthCheckFeature.CONFIGURATION_PROPERTIES_NAME); + this.servers = IndexedHttpServletServerFactory.getInstance().build(healthCheckProperties); + this.clients = IndexedHttpClientFactory.getInstance().build(healthCheckProperties); + + for (HttpServletServer server : servers) { + startServer(server); + } + } catch (Exception e) { + logger.warn("{}: cannot start {}", this, e); + return false; + } + + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean stop() { + + for (HttpServletServer server : servers) { + try { + server.stop(); + } catch (Exception e) { + logger.warn("{}: cannot stop http-server {}", this, server, e); + } + } + + for (HttpClient client : clients) { + try { + client.stop(); + } catch (Exception e) { + logger.warn("{}: cannot stop http-client {}", this, client, e); + } + } + + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public void shutdown() { + this.stop(); + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized boolean isAlive() { + return this.healthCheckProperties != null; + } + + /** + * @return list of attached Http Servers + */ + public List<HttpServletServer> getServers() { + return this.servers; + } + + /** + * @return list of attached Http Clients + */ + public List<HttpClient> getClients() { + return this.clients; + } + + public String getHttpBody(Response response, HttpClient client) { + + String body = null; try { body = HttpClient.getBody(response, String.class); } catch (Exception e) { - logger.info("{}: cannot get body from http-client {}", this, - client, e); + logger.info("{}: cannot get body from http-client {}", this, client, e); } - + return body; - } - - public void startServer(HttpServletServer server) { + } + + public void startServer(HttpServletServer server) { try { server.start(); } catch (Exception e) { logger.warn("{}: cannot start http-server {}", this, server, e); } - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("HealthCheckMonitor [servers="); - builder.append(servers); - builder.append(", clients="); - builder.append(clients); - builder.append("]"); - return builder.toString(); - } - + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("HealthCheckMonitor [servers="); + builder.append(servers); + builder.append(", clients="); + builder.append(clients); + builder.append("]"); + return builder.toString(); + } + } diff --git a/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java b/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java index a56483c4..578ce5d5 100644 --- a/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java +++ b/feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java @@ -34,10 +34,10 @@ import java.util.Properties; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.drools.healthcheck.HealthCheck.Report; import org.onap.policy.drools.healthcheck.HealthCheck.Reports; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.PolicyProperties; import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,74 +48,63 @@ public class HealthCheckFeatureTest { * Healthcheck Configuration File */ private static final String HEALTH_CHECK_PROPERTIES_FILE = "feature-healthcheck.properties"; - - private static final Path healthCheckPropsPath = Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), - HEALTH_CHECK_PROPERTIES_FILE); - - private static final Path healthCheckPropsBackupPath = Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), - HEALTH_CHECK_PROPERTIES_FILE + ".bak"); - - + + private static final Path healthCheckPropsPath = + Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), HEALTH_CHECK_PROPERTIES_FILE); + + private static final Path healthCheckPropsBackupPath = Paths + .get(SystemPersistence.manager.getConfigurationPath().toString(), HEALTH_CHECK_PROPERTIES_FILE + ".bak"); + + /** * logger */ private static Logger logger = LoggerFactory.getLogger(HealthCheckFeatureTest.class); private static Properties httpProperties = new Properties(); - - + + @BeforeClass - public static void setup(){ - - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES, "HEALTHCHECK"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_HOST_SUFFIX, - "localhost"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX, - "7777"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, - "username"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, - "password"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, - org.onap.policy.drools.healthcheck.RestMockHealthCheck.class.getName()); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_MANAGED_SUFFIX, - "true"); - - - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES, "HEALTHCHECK"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_HOST_SUFFIX, - "localhost"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX, - "7777"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_URL_SUFFIX, - "healthcheck/test"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_HTTPS_SUFFIX, - "false"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, - "username"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, - "password"); - httpProperties.setProperty - (PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + PolicyProperties.PROPERTY_MANAGED_SUFFIX, - "true"); - + public static void setup() { + + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, "HEALTHCHECK"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7777"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "username"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, "password"); + httpProperties.setProperty( + PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, + org.onap.policy.drools.healthcheck.RestMockHealthCheck.class.getName()); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true"); + + + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES, "HEALTHCHECK"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "7777"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_URL_SUFFIX, "healthcheck/test"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "username"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, "password"); + httpProperties.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "HEALTHCHECK" + + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true"); + configDirSetup(); - + } - + @AfterClass public static void tearDown() { logger.info("-- tearDown() --"); @@ -123,68 +112,68 @@ public class HealthCheckFeatureTest { configDirCleanup(); } - @Test - public void test() { - - HealthCheckFeature feature = new HealthCheckFeature(); - feature.afterStart(PolicyEngine.manager); - - Reports reports = HealthCheck.monitor.healthCheck(); - - for (Report rpt : reports.getDetails()) { - if (rpt.getName() == "HEALTHCHECK") { - assertTrue(rpt.isHealthy()); - assertEquals(200,rpt.getCode()); - assertEquals("All Alive", rpt.getMessage()); - break; - } - } - - feature.afterShutdown(PolicyEngine.manager); - - } - - - /** - * setup up config directory - */ - protected static void configDirSetup() { - - File origPropsFile = new File(healthCheckPropsPath.toString()); - File backupPropsFile = new File(healthCheckPropsBackupPath.toString()); - Path configDir = Paths.get(SystemPersistence.DEFAULT_CONFIGURATION_DIR); - - try { - - if (Files.notExists(configDir)) { - Files.createDirectories(configDir); - } - - Files.deleteIfExists(healthCheckPropsBackupPath); - origPropsFile.renameTo(backupPropsFile); - - FileWriter writer = new FileWriter(origPropsFile); - httpProperties.store(writer,"Machine created healthcheck-feature Properties"); - - } catch (final Exception e) { - logger.info("Problem cleaning {}", healthCheckPropsPath, e); - } - } - - /** - * cleanup up config directory - */ - protected static void configDirCleanup() { - + @Test + public void test() { + + HealthCheckFeature feature = new HealthCheckFeature(); + feature.afterStart(PolicyEngine.manager); + + Reports reports = HealthCheck.monitor.healthCheck(); + + for (Report rpt : reports.getDetails()) { + if (rpt.getName() == "HEALTHCHECK") { + assertTrue(rpt.isHealthy()); + assertEquals(200, rpt.getCode()); + assertEquals("All Alive", rpt.getMessage()); + break; + } + } + + feature.afterShutdown(PolicyEngine.manager); + + } + + + /** + * setup up config directory + */ + protected static void configDirSetup() { + + File origPropsFile = new File(healthCheckPropsPath.toString()); + File backupPropsFile = new File(healthCheckPropsBackupPath.toString()); + Path configDir = Paths.get(SystemPersistence.DEFAULT_CONFIGURATION_DIR); + + try { + + if (Files.notExists(configDir)) { + Files.createDirectories(configDir); + } + + Files.deleteIfExists(healthCheckPropsBackupPath); + origPropsFile.renameTo(backupPropsFile); + + FileWriter writer = new FileWriter(origPropsFile); + httpProperties.store(writer, "Machine created healthcheck-feature Properties"); + + } catch (final Exception e) { + logger.info("Problem cleaning {}", healthCheckPropsPath, e); + } + } + + /** + * cleanup up config directory + */ + protected static void configDirCleanup() { + File origPropsFile = new File(healthCheckPropsBackupPath.toString()); File backupPropsFile = new File(healthCheckPropsPath.toString()); - + try { - Files.deleteIfExists(healthCheckPropsPath); - origPropsFile.renameTo(backupPropsFile); - } catch (final Exception e) { - logger.info("Problem cleaning {}", healthCheckPropsPath, e); - } + Files.deleteIfExists(healthCheckPropsPath); + origPropsFile.renameTo(backupPropsFile); + } catch (final Exception e) { + logger.info("Problem cleaning {}", healthCheckPropsPath, e); } + } } diff --git a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/DmaapManager.java b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/DmaapManager.java index eb41f803..8780eefc 100644 --- a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/DmaapManager.java +++ b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/DmaapManager.java @@ -21,11 +21,13 @@ package org.onap.policy.drools.pooling; import java.util.List; -import org.onap.policy.drools.event.comm.FilterableTopicSource; -import org.onap.policy.drools.event.comm.TopicEndpoint; -import org.onap.policy.drools.event.comm.TopicListener; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.TopicSource; + +import org.onap.policy.common.endpoints.event.comm.FilterableTopicSource; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; +import org.onap.policy.common.endpoints.event.comm.impl.ProxyTopicEndpointManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -97,8 +99,7 @@ public class DmaapManager { } /** - * Used by junit tests to set the factory used to create various objects used by this - * class. + * Used by junit tests to set the factory used to create various objects used by this class. * * @param factory the new factory */ @@ -162,8 +163,8 @@ public class DmaapManager { /** * Stops the publisher. * - * @param waitMs time, in milliseconds, to wait for the sink to transmit any queued - * messages and close + * @param waitMs time, in milliseconds, to wait for the sink to transmit any queued messages and + * close */ public void stopPublisher(long waitMs) { if (!publishing) { @@ -171,8 +172,8 @@ public class DmaapManager { } /* - * Give the sink a chance to transmit messages in the queue. It would be better if - * "waitMs" could be passed to sink.stop(), but that isn't an option at this time. + * Give the sink a chance to transmit messages in the queue. It would be better if "waitMs" + * could be passed to sink.stop(), but that isn't an option at this time. */ try { Thread.sleep(waitMs); @@ -262,14 +263,14 @@ public class DmaapManager { * @return the topic sources */ public List<TopicSource> getTopicSources() { - return TopicEndpoint.manager.getTopicSources(); + return ProxyTopicEndpointManager.getInstance().getTopicSources(); } /** * @return the topic sinks */ public List<TopicSink> getTopicSinks() { - return TopicEndpoint.manager.getTopicSinks(); + return ProxyTopicEndpointManager.getInstance().getTopicSinks(); } } diff --git a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingFeature.java b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingFeature.java index bf35bcf5..815dc548 100644 --- a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingFeature.java +++ b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingFeature.java @@ -25,13 +25,14 @@ import java.util.Properties; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; + +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; +import org.onap.policy.common.endpoints.event.comm.impl.ProxyTopicEndpointManager; import org.onap.policy.common.utils.properties.SpecProperties; import org.onap.policy.common.utils.properties.exception.PropertyException; import org.onap.policy.drools.controller.DroolsController; -import org.onap.policy.drools.event.comm.TopicEndpoint; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.TopicSource; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; import org.onap.policy.drools.features.DroolsControllerFeatureAPI; import org.onap.policy.drools.features.PolicyControllerFeatureAPI; import org.onap.policy.drools.features.PolicyEngineFeatureAPI; @@ -44,11 +45,10 @@ import org.slf4j.LoggerFactory; /** * Controller/session pooling. Multiple hosts may be launched, all servicing the same - * controllers/sessions. When this feature is enabled, the requests are divided across the - * different hosts, instead of all running on a single, active host. - * <p> - * With each controller, there is an associated DMaaP topic that is used for internal - * communication between the different hosts serving the controller. + * controllers/sessions. When this feature is enabled, the requests are divided across the different + * hosts, instead of all running on a single, active host. <p> With each controller, there is an + * associated DMaaP topic that is used for internal communication between the different hosts + * serving the controller. */ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerFeatureAPI, DroolsControllerFeatureAPI { @@ -80,9 +80,9 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF private final CountDownLatch activeLatch = new CountDownLatch(1); /** - * Arguments passed to beforeOffer(), which are saved for when the beforeInsert() is - * called later. As multiple threads can be active within the methods at the same - * time, we must keep this in thread local storage. + * Arguments passed to beforeOffer(), which are saved for when the beforeInsert() is called + * later. As multiple threads can be active within the methods at the same time, we must keep + * this in thread local storage. */ private ThreadLocal<OfferArgs> offerArgs = new ThreadLocal<>(); @@ -128,13 +128,13 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF public boolean beforeStart(PolicyEngine engine) { logger.info("initializing " + PoolingProperties.FEATURE_NAME); featProps = factory.getProperties(PoolingProperties.FEATURE_NAME); - + // remove any generic pooling topic - always use controller-specific property featProps.remove(PoolingProperties.POOLING_TOPIC); - + factory.initTopicSources(featProps); factory.initTopicSinks(featProps); - + return false; } @@ -154,7 +154,7 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF String name = controller.getName(); SpecProperties specProps = new SpecProperties(PoolingProperties.PREFIX, name, featProps); - + if (FeatureEnabledChecker.isFeatureEnabled(specProps, PoolingProperties.FEATURE_ENABLED)) { try { // get & validate the properties @@ -239,8 +239,8 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF @Override public boolean beforeOffer(PolicyController controller, CommInfrastructure protocol, String topic2, String event) { /* - * As this is invoked a lot, we'll directly call the manager's method instead of - * using the functional interface via doManager(). + * As this is invoked a lot, we'll directly call the manager's method instead of using the + * functional interface via doManager(). */ PoolingManagerImpl mgr = ctlr2pool.get(controller.getName()); if (mgr == null) { @@ -270,20 +270,20 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF } catch (IllegalArgumentException | IllegalStateException e) { logger.warn("cannot get controller for {} {}", droolsController.getGroupId(), - droolsController.getArtifactId(), e); + droolsController.getArtifactId(), e); return false; } if (controller == null) { logger.warn("cannot determine controller for {} {}", droolsController.getGroupId(), - droolsController.getArtifactId()); + droolsController.getArtifactId()); return false; } /* - * As this is invoked a lot, we'll directly call the manager's method instead of - * using the functional interface via doManager(). + * As this is invoked a lot, we'll directly call the manager's method instead of using the + * functional interface via doManager(). */ PoolingManagerImpl mgr = ctlr2pool.get(controller.getName()); if (mgr == null) { @@ -295,7 +295,7 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF @Override public boolean afterOffer(PolicyController controller, CommInfrastructure protocol, String topic, String event, - boolean success) { + boolean success) { // clear any stored arguments offerArgs.set(null); @@ -304,8 +304,8 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF } /** - * Executes a function using the manager associated with the controller. Catches any - * exceptions from the function and re-throws it as a runtime exception. + * Executes a function using the manager associated with the controller. Catches any exceptions + * from the function and re-throws it as a runtime exception. * * @param controller * @param func function to be executed @@ -349,8 +349,7 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF /** * * @param mgr - * @return {@code true} if the request was handled by the manager, {@code false} - * otherwise + * @return {@code true} if the request was handled by the manager, {@code false} otherwise * @throws PoolingFeatureException */ public boolean apply(PoolingManagerImpl mgr) throws PoolingFeatureException; @@ -412,7 +411,7 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF * @return a new pooling manager */ public PoolingManagerImpl makeManager(String host, PolicyController controller, PoolingProperties props, - CountDownLatch activeLatch) { + CountDownLatch activeLatch) { return new PoolingManagerImpl(host, controller, props, activeLatch); } @@ -433,7 +432,7 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF * @return the topic sources */ public List<TopicSource> initTopicSources(Properties props) { - return TopicEndpoint.manager.addTopicSources(props); + return ProxyTopicEndpointManager.getInstance().addTopicSources(props); } /** @@ -443,7 +442,7 @@ public class PoolingFeature implements PolicyEngineFeatureAPI, PolicyControllerF * @return the topic sinks */ public List<TopicSink> initTopicSinks(Properties props) { - return TopicEndpoint.manager.addTopicSinks(props); + return ProxyTopicEndpointManager.getInstance().addTopicSinks(props); } } } diff --git a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingManagerImpl.java b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingManagerImpl.java index 68dfee14..02ba4ec9 100644 --- a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingManagerImpl.java +++ b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingManagerImpl.java @@ -31,8 +31,8 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.onap.policy.common.utils.properties.SpecProperties; import org.onap.policy.drools.controller.DroolsController; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; -import org.onap.policy.drools.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicListener; import org.onap.policy.drools.pooling.extractor.ClassExtractors; import org.onap.policy.drools.pooling.message.BucketAssignments; import org.onap.policy.drools.pooling.message.Forward; diff --git a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/message/Forward.java b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/message/Forward.java index 6122d361..fb3d4eb2 100644 --- a/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/message/Forward.java +++ b/feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/message/Forward.java @@ -20,7 +20,7 @@ package org.onap.policy.drools.pooling.message; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.drools.pooling.PoolingFeatureException; import com.fasterxml.jackson.annotation.JsonIgnore; diff --git a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/DmaapManagerTest.java b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/DmaapManagerTest.java index 6509e90e..d48dea5b 100644 --- a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/DmaapManagerTest.java +++ b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/DmaapManagerTest.java @@ -37,10 +37,10 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.onap.policy.drools.event.comm.FilterableTopicSource; -import org.onap.policy.drools.event.comm.TopicListener; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.TopicSource; +import org.onap.policy.common.endpoints.event.comm.FilterableTopicSource; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; import org.onap.policy.drools.pooling.DmaapManager.Factory; public class DmaapManagerTest { diff --git a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/FeatureTest.java b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/FeatureTest.java index 8683103c..3c3466be 100644 --- a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/FeatureTest.java +++ b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/FeatureTest.java @@ -52,12 +52,12 @@ import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.onap.policy.drools.controller.DroolsController; -import org.onap.policy.drools.event.comm.FilterableTopicSource; -import org.onap.policy.drools.event.comm.Topic; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; -import org.onap.policy.drools.event.comm.TopicListener; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.TopicSource; +import org.onap.policy.common.endpoints.event.comm.FilterableTopicSource; +import org.onap.policy.common.endpoints.event.comm.Topic; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; import org.onap.policy.drools.pooling.message.Message; import org.onap.policy.drools.system.PolicyController; import org.onap.policy.drools.system.PolicyEngine; diff --git a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/FeatureTest2.java b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/FeatureTest2.java index 6280ebed..f25f3d3d 100644 --- a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/FeatureTest2.java +++ b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/FeatureTest2.java @@ -27,6 +27,10 @@ import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.onap.policy.drools.pooling.PoolingProperties.PREFIX; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Arrays; import java.util.Deque; @@ -39,6 +43,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; + import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -47,36 +52,26 @@ import org.junit.Ignore; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; +import org.onap.policy.common.endpoints.event.comm.impl.ProxyTopicEndpointManager; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.drools.controller.DroolsController; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; -import org.onap.policy.drools.event.comm.TopicEndpoint; -import org.onap.policy.drools.event.comm.TopicListener; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.TopicSource; -import org.onap.policy.drools.properties.PolicyProperties; import org.onap.policy.drools.system.PolicyController; import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; /** - * End-to-end tests of the pooling feature. Launches one or more "hosts", each one having - * its own feature object. Uses real feature objects, as well as real DMaaP sources and - * sinks. However, the following are not: - * <dl> - * <dt>PolicyEngine, PolicyController, DroolsController</dt> - * <dd>mocked</dd> + * End-to-end tests of the pooling feature. Launches one or more "hosts", each one having its own + * feature object. Uses real feature objects, as well as real DMaaP sources and sinks. However, the + * following are not: <dl> <dt>PolicyEngine, PolicyController, DroolsController</dt> <dd>mocked</dd> * </dl> * - * <p> - * The following fields must be set before executing this: - * <ul> - * <li>UEB_SERVERS</li> - * <li>INTERNAL_TOPIC</li> - * <li>EXTERNAL_TOPIC</li> - * </ul> + * <p> The following fields must be set before executing this: <ul> <li>UEB_SERVERS</li> + * <li>INTERNAL_TOPIC</li> <li>EXTERNAL_TOPIC</li> </ul> */ public class FeatureTest2 { @@ -147,10 +142,10 @@ public class FeatureTest2 { saveManagerFactory = PoolingManagerImpl.getFactory(); saveDmaapFactory = DmaapManager.getFactory(); - externalSink = TopicEndpoint.manager.addTopicSinks(makeSinkProperties(EXTERNAL_TOPIC)).get(0); + externalSink = ProxyTopicEndpointManager.getInstance().addTopicSinks(makeSinkProperties(EXTERNAL_TOPIC)).get(0); externalSink.start(); - internalSink = TopicEndpoint.manager.addTopicSinks(makeSinkProperties(INTERNAL_TOPIC)).get(0); + internalSink = ProxyTopicEndpointManager.getInstance().addTopicSinks(makeSinkProperties(INTERNAL_TOPIC)).get(0); internalSink.start(); } @@ -222,14 +217,15 @@ public class FeatureTest2 { private static Properties makeSinkProperties(String topic) { Properties props = new Properties(); - props.setProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS, topic); + props.setProperty(PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS, topic); - props.setProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic - + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX, UEB_SERVERS); - props.setProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic - + PolicyProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX, "0"); - props.setProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic - + PolicyProperties.PROPERTY_MANAGED_SUFFIX, "false"); + props.setProperty(PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic + + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX, UEB_SERVERS); + props.setProperty(PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic + + PolicyEndPointProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX, "0"); + props.setProperty( + PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, + "false"); return props; } @@ -237,21 +233,20 @@ public class FeatureTest2 { private static Properties makeSourceProperties(String topic) { Properties props = new Properties(); - props.setProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS, topic); + props.setProperty(PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS, topic); - props.setProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX, UEB_SERVERS); - props.setProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX, FETCH_LIMIT); - props.setProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_MANAGED_SUFFIX, "false"); + props.setProperty(PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic + + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX, UEB_SERVERS); + props.setProperty(PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic + + PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX, FETCH_LIMIT); + props.setProperty( + PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, + "false"); if (EXTERNAL_TOPIC.equals(topic)) { // consumer group is a constant - props.setProperty( - PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX, - EXTERNAL_GROUP); + props.setProperty(PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic + + PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX, EXTERNAL_GROUP); // consumer instance is generated by the BusConsumer code } @@ -378,8 +373,8 @@ public class FeatureTest2 { /** * @param droolsController - * @return the controller associated with a drools controller, or {@code null} if - * it has no associated controller + * @return the controller associated with a drools controller, or {@code null} if it has no + * associated controller */ public PolicyController getController(DroolsController droolsController) { return drools2policy.get(droolsController); @@ -472,8 +467,10 @@ public class FeatureTest2 { when(controller.getName()).thenReturn(CONTROLLER1); when(controller.getDrools()).thenReturn(drools); - externalSource = TopicEndpoint.manager.addTopicSources(makeSourceProperties(EXTERNAL_TOPIC)).get(0); - internalSource = TopicEndpoint.manager.addTopicSources(makeSourceProperties(INTERNAL_TOPIC)).get(0); + externalSource = ProxyTopicEndpointManager.getInstance() + .addTopicSources(makeSourceProperties(EXTERNAL_TOPIC)).get(0); + internalSource = ProxyTopicEndpointManager.getInstance() + .addTopicSources(makeSourceProperties(INTERNAL_TOPIC)).get(0); // stop consuming events if the controller stops when(controller.stop()).thenAnswer(args -> { @@ -490,8 +487,8 @@ public class FeatureTest2 { * Waits, for a period of time, for the host to enter the Active state. * * @param timeMs time to wait, in milliseconds - * @return {@code true} if the host entered the Active state within the given - * amount of time, {@code false} otherwise + * @return {@code true} if the host entered the Active state within the given amount of + * time, {@code false} otherwise * @throws InterruptedException */ public boolean awaitActive(long timeMs) throws InterruptedException { @@ -499,8 +496,8 @@ public class FeatureTest2 { } /** - * Starts threads for the host so that it begins consuming from both the external - * "DMaaP" topic and its own internal "DMaaP" topic. + * Starts threads for the host so that it begins consuming from both the external "DMaaP" + * topic and its own internal "DMaaP" topic. */ public void start() { DmaapManager.setFactory(new DmaapManager.Factory() { @@ -592,8 +589,7 @@ public class FeatureTest2 { /** * - * @return {@code true} if a message was seen for this host, {@code false} - * otherwise + * @return {@code true} if a message was seen for this host, {@code false} otherwise */ public boolean messageSeen() { return sawMsg.get(); @@ -664,8 +660,8 @@ public class FeatureTest2 { this.context = context; /* - * Note: do NOT extract anything from "context" at this point, because it - * hasn't been fully initialized yet + * Note: do NOT extract anything from "context" at this point, because it hasn't been + * fully initialized yet */ } @@ -680,15 +676,15 @@ public class FeatureTest2 { props.setProperty(specialize(PoolingProperties.OFFLINE_LIMIT, CONTROLLER1), "10000"); props.setProperty(specialize(PoolingProperties.OFFLINE_AGE_MS, CONTROLLER1), "1000000"); props.setProperty(specialize(PoolingProperties.OFFLINE_PUB_WAIT_MS, CONTROLLER1), - "" + STD_OFFLINE_PUB_WAIT_MS); + "" + STD_OFFLINE_PUB_WAIT_MS); props.setProperty(specialize(PoolingProperties.START_HEARTBEAT_MS, CONTROLLER1), - "" + STD_START_HEARTBEAT_MS); + "" + STD_START_HEARTBEAT_MS); props.setProperty(specialize(PoolingProperties.REACTIVATE_MS, CONTROLLER1), "" + STD_REACTIVATE_WAIT_MS); props.setProperty(specialize(PoolingProperties.IDENTIFICATION_MS, CONTROLLER1), "" + STD_IDENTIFICATION_MS); props.setProperty(specialize(PoolingProperties.ACTIVE_HEARTBEAT_MS, CONTROLLER1), - "" + STD_ACTIVE_HEARTBEAT_MS); + "" + STD_ACTIVE_HEARTBEAT_MS); props.setProperty(specialize(PoolingProperties.INTER_HEARTBEAT_MS, CONTROLLER1), - "" + STD_INTER_HEARTBEAT_MS); + "" + STD_INTER_HEARTBEAT_MS); props.putAll(makeSinkProperties(INTERNAL_TOPIC)); props.putAll(makeSourceProperties(INTERNAL_TOPIC)); @@ -741,8 +737,8 @@ public class FeatureTest2 { public ManagerFactory(Context context) { /* - * Note: do NOT extract anything from "context" at this point, because it - * hasn't been fully initialized yet + * Note: do NOT extract anything from "context" at this point, because it hasn't been + * fully initialized yet */ } diff --git a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingFeatureTest.java b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingFeatureTest.java index 32264e3a..c57a9f6f 100644 --- a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingFeatureTest.java +++ b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingFeatureTest.java @@ -39,7 +39,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.drools.controller.DroolsController; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.drools.pooling.PoolingFeature.Factory; import org.onap.policy.drools.system.PolicyController; import org.onap.policy.drools.system.PolicyEngine; diff --git a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingManagerImplTest.java b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingManagerImplTest.java index d74b87f9..d90bac4b 100644 --- a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingManagerImplTest.java +++ b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingManagerImplTest.java @@ -47,8 +47,8 @@ import org.junit.BeforeClass; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.onap.policy.drools.controller.DroolsController; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; -import org.onap.policy.drools.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicListener; import org.onap.policy.drools.pooling.PoolingManagerImpl.Factory; import org.onap.policy.drools.pooling.extractor.ClassExtractors; import org.onap.policy.drools.pooling.message.BucketAssignments; diff --git a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/message/ForwardTest.java b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/message/ForwardTest.java index bc92fa27..2549fa94 100644 --- a/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/message/ForwardTest.java +++ b/feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/message/ForwardTest.java @@ -25,7 +25,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; public class ForwardTest extends BasicMessageTester<Forward> { // values set by makeValidMessage() diff --git a/feature-simulators/pom.xml b/feature-simulators/pom.xml index eecb8dde..dd0b934b 100644 --- a/feature-simulators/pom.xml +++ b/feature-simulators/pom.xml @@ -45,9 +45,14 @@ <scope>test</scope> </dependency> <dependency> - <groupId>org.onap.policy.drools-pdp</groupId> + <groupId>org.onap.policy.common</groupId> <artifactId>policy-endpoints</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.onap.policy.drools-pdp</groupId> + <artifactId>policy-utils</artifactId> + <version>${project.version}</version> + </dependency> </dependencies> </project> diff --git a/feature-simulators/src/test/java/org/onap/policy/drools/simulators/DMaaPSimulatorTest.java b/feature-simulators/src/test/java/org/onap/policy/drools/simulators/DMaaPSimulatorTest.java index b16804e6..1ba2fc44 100644 --- a/feature-simulators/src/test/java/org/onap/policy/drools/simulators/DMaaPSimulatorTest.java +++ b/feature-simulators/src/test/java/org/onap/policy/drools/simulators/DMaaPSimulatorTest.java @@ -36,43 +36,46 @@ import java.nio.charset.StandardCharsets; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import org.onap.policy.drools.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.http.server.impl.IndexedHttpServletServerFactory; +import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.drools.utils.logging.LoggerUtil; -import org.onap.policy.drools.utils.NetworkUtil; public class DMaaPSimulatorTest { - private static final int DMAAPSIM_SERVER_PORT = 6670; + private static final int DMAAPSIM_SERVER_PORT = 6670; + @BeforeClass public static void setUpSimulator() { LoggerUtil.setLevel("ROOT", "INFO"); LoggerUtil.setLevel("org.eclipse.jetty", "WARN"); try { - final HttpServletServer testServer = HttpServletServer.factory.build("dmaapSim", - "localhost", DMAAPSIM_SERVER_PORT, "/", false, true); - testServer.addServletClass("/*", DMaaPSimulatorJaxRs.class.getName()); - testServer.waitedStart(5000); - if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) - throw new IllegalStateException("cannot connect to port " + testServer.getPort()); + final HttpServletServer testServer = IndexedHttpServletServerFactory.getInstance().build("dmaapSim", + "localhost", DMAAPSIM_SERVER_PORT, "/", false, true); + testServer.addServletClass("/*", DMaaPSimulatorJaxRs.class.getName()); + testServer.waitedStart(5000); + if (!NetworkUtil.isTcpPortOpen("localhost", testServer.getPort(), 5, 10000L)) { + throw new IllegalStateException("cannot connect to port " + testServer.getPort()); + } } catch (final Exception e) { - fail(e.getMessage()); + fail(e.getMessage()); } } @AfterClass public static void tearDownSimulator() { - HttpServletServer.factory.destroy(); + IndexedHttpServletServerFactory.getInstance().destroy(); } - + @Test public void testGetNoData() { int timeout = 1000; - Pair <Integer, String> response = dmaapGet("myTopicNoData", timeout); + Pair<Integer, String> response = dmaapGet("myTopicNoData", timeout); assertNotNull(response); assertNotNull(response.a); assertEquals("No topic", response.b); } - + @Test public void testSinglePost() { String myTopic = "myTopicSinglePost"; @@ -81,13 +84,13 @@ public class DMaaPSimulatorTest { assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = dmaapGet(myTopic, 1000); assertNotNull(response); assertNotNull(response.a); assertEquals(testData, response.b); } - + @Test public void testOneTopicMultiPost() { String[] data = {"data point 1", "data point 2", "something random"}; @@ -96,269 +99,259 @@ public class DMaaPSimulatorTest { assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = dmaapPost(myTopic, data[1]); assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = dmaapPost(myTopic, data[2]); assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = dmaapGet(myTopic, 1000); assertNotNull(response); assertNotNull(response.a); assertEquals(data[0], response.b); - + response = dmaapGet(myTopic, 1000); assertNotNull(response); assertNotNull(response.a); assertEquals(data[1], response.b); - + response = dmaapGet(myTopic, 1000); assertNotNull(response); assertNotNull(response.a); assertEquals(data[2], response.b); } - + @Test public void testMultiTopic() { - String[][] data = {{"Topic one message one", "Topic one message two"}, {"Topic two message one", "Topic two message two"}}; + String[][] data = {{"Topic one message one", "Topic one message two"}, + {"Topic two message one", "Topic two message two"}}; String[] topics = {"topic1", "topic2"}; - + Pair<Integer, String> response = dmaapPost(topics[0], data[0][0]); assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = dmaapGet(topics[0], 1000); assertNotNull(response); assertNotNull(response.a); assertEquals(data[0][0], response.b); - + response = dmaapGet(topics[1], 1000); assertNotNull(response); assertNotNull(response.a); assertEquals("No topic", response.b); - + response = dmaapPost(topics[1], data[1][0]); assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = dmaapPost(topics[1], data[1][1]); assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = dmaapPost(topics[0], data[0][1]); assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = dmaapGet(topics[1], 1000); assertNotNull(response); assertNotNull(response.a); assertEquals(data[1][0], response.b); - + response = dmaapGet(topics[0], 1000); assertNotNull(response); assertNotNull(response.a); assertEquals(data[0][1], response.b); - + response = dmaapGet(topics[1], 1000); assertNotNull(response); assertNotNull(response.a); assertEquals(data[1][1], response.b); - + response = dmaapGet(topics[0], 1000); assertNotNull(response); assertNotNull(response.a); assertEquals("No Data", response.b); } - + @Test public void testResponseCode() { Pair<Integer, String> response = dmaapPost("myTopic", "myTopicData"); assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = setStatus(503); assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = dmaapGet("myTopic", 500); assertNotNull(response); assertEquals(503, response.a.intValue()); assertEquals("You got response code: 503", response.b); - + response = setStatus(202); assertNotNull(response); assertNotNull(response.a); assertNotNull(response.b); - + response = dmaapGet("myTopic", 500); assertNotNull(response); assertEquals(202, response.a.intValue()); assertEquals("myTopicData", response.b); } - - private static Pair<Integer, String> dmaapGet (String topic, int timeout) { + + private static Pair<Integer, String> dmaapGet(String topic, int timeout) { return dmaapGet(topic, "1", "1", timeout); } - - private static Pair<Integer, String> dmaapGet (String topic, String consumerGroup, String consumerId, int timeout) { - String url = "http://localhost:" + DMAAPSIM_SERVER_PORT + "/events/" + topic + "/" + consumerGroup + "/" + consumerId + "?timeout=" + timeout; + + private static Pair<Integer, String> dmaapGet(String topic, String consumerGroup, String consumerId, int timeout) { + String url = "http://localhost:" + DMAAPSIM_SERVER_PORT + "/events/" + topic + "/" + consumerGroup + "/" + + consumerId + "?timeout=" + timeout; try { - URLConnection conn = new URL(url).openConnection(); + URLConnection conn = new URL(url).openConnection(); HttpURLConnection httpConn = null; if (conn instanceof HttpURLConnection) { - httpConn = (HttpURLConnection) conn; - } - else { - fail("connection not set up right"); + httpConn = (HttpURLConnection) conn; + } else { + fail("connection not set up right"); } httpConn.setRequestMethod("GET"); httpConn.connect(); String response = ""; try (BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()))) { - String line; - while((line = connReader.readLine()) != null) { - response += line; - } - httpConn.disconnect(); - return new Pair<Integer, String>(httpConn.getResponseCode(), response); - } - catch (IOException e) { - if (e.getMessage().startsWith("Server returned HTTP response code")) { - System.out.println("hi"); - BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); - String line; - while((line = connReader.readLine()) != null) { - response += line; - } - httpConn.disconnect(); - return new Pair<Integer, String>(httpConn.getResponseCode(), response); - } - else { - fail("we got an exception: " + e); - } + String line; + while ((line = connReader.readLine()) != null) { + response += line; + } + httpConn.disconnect(); + return new Pair<Integer, String>(httpConn.getResponseCode(), response); + } catch (IOException e) { + if (e.getMessage().startsWith("Server returned HTTP response code")) { + System.out.println("hi"); + BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); + String line; + while ((line = connReader.readLine()) != null) { + response += line; + } + httpConn.disconnect(); + return new Pair<Integer, String>(httpConn.getResponseCode(), response); + } else { + fail("we got an exception: " + e); + } } + } catch (Exception e) { + fail("we got an exception" + e); } - catch (Exception e) { - fail("we got an exception" + e); - } - + return null; } - - private static Pair<Integer, String> dmaapPost (String topic, String data) { + + private static Pair<Integer, String> dmaapPost(String topic, String data) { String url = "http://localhost:" + DMAAPSIM_SERVER_PORT + "/events/" + topic; byte[] postData = data.getBytes(StandardCharsets.UTF_8); try { - URLConnection conn = new URL(url).openConnection(); - HttpURLConnection httpConn = null; + URLConnection conn = new URL(url).openConnection(); + HttpURLConnection httpConn = null; if (conn instanceof HttpURLConnection) { - httpConn = (HttpURLConnection) conn; - } - else { - fail("connection not set up right"); + httpConn = (HttpURLConnection) conn; + } else { + fail("connection not set up right"); } httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); - httpConn.setRequestProperty( "Content-Type", "text/plain"); - httpConn.setRequestProperty("Content-Length", ""+postData.length); + httpConn.setRequestProperty("Content-Type", "text/plain"); + httpConn.setRequestProperty("Content-Length", "" + postData.length); httpConn.connect(); String response = ""; try (DataOutputStream connWriter = new DataOutputStream(httpConn.getOutputStream())) { - connWriter.write(postData); - connWriter.flush(); + connWriter.write(postData); + connWriter.flush(); } try (BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()))) { - String line; - while((line = connReader.readLine()) != null) { - response += line; - } - httpConn.disconnect(); - return new Pair<Integer, String>(httpConn.getResponseCode(), response); - } - catch (IOException e) { - if (e.getMessage().startsWith("Server returned HTTP response code")) { - System.out.println("hi"); - BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); - String line; - while((line = connReader.readLine()) != null) { - response += line; - } - httpConn.disconnect(); - return new Pair<Integer, String>(httpConn.getResponseCode(), response); - } - else { - fail("we got an exception: " + e); - } + String line; + while ((line = connReader.readLine()) != null) { + response += line; + } + httpConn.disconnect(); + return new Pair<Integer, String>(httpConn.getResponseCode(), response); + } catch (IOException e) { + if (e.getMessage().startsWith("Server returned HTTP response code")) { + System.out.println("hi"); + BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); + String line; + while ((line = connReader.readLine()) != null) { + response += line; + } + httpConn.disconnect(); + return new Pair<Integer, String>(httpConn.getResponseCode(), response); + } else { + fail("we got an exception: " + e); + } } - } - catch (Exception e) { - fail("we got an exception: " + e); + } catch (Exception e) { + fail("we got an exception: " + e); } return null; } - - private static Pair<Integer, String> setStatus (int status) { + + private static Pair<Integer, String> setStatus(int status) { String url = "http://localhost:" + DMAAPSIM_SERVER_PORT + "/events/setStatus?statusCode=" + status; try { - URLConnection conn = new URL(url).openConnection(); + URLConnection conn = new URL(url).openConnection(); HttpURLConnection httpConn = null; if (conn instanceof HttpURLConnection) { - httpConn = (HttpURLConnection) conn; - } - else { - fail("connection not set up right"); + httpConn = (HttpURLConnection) conn; + } else { + fail("connection not set up right"); } httpConn.setRequestMethod("POST"); httpConn.connect(); String response = ""; try (BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()))) { - String line; - while((line = connReader.readLine()) != null) { - response += line; - } - httpConn.disconnect(); - return new Pair<Integer, String>(httpConn.getResponseCode(), response); - } - catch (IOException e) { - if (e.getMessage().startsWith("Server returned HTTP response code")) { - System.out.println("hi"); - BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); - String line; - while((line = connReader.readLine()) != null) { - response += line; - } - httpConn.disconnect(); - return new Pair<Integer, String>(httpConn.getResponseCode(), response); - } - else { - fail("we got an exception: " + e); - } + String line; + while ((line = connReader.readLine()) != null) { + response += line; + } + httpConn.disconnect(); + return new Pair<Integer, String>(httpConn.getResponseCode(), response); + } catch (IOException e) { + if (e.getMessage().startsWith("Server returned HTTP response code")) { + System.out.println("hi"); + BufferedReader connReader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); + String line; + while ((line = connReader.readLine()) != null) { + response += line; + } + httpConn.disconnect(); + return new Pair<Integer, String>(httpConn.getResponseCode(), response); + } else { + fail("we got an exception: " + e); + } } - } - catch (Exception e) { - fail("we got an exception" + e); + } catch (Exception e) { + fail("we got an exception" + e); } return null; } - + private static class Pair<A, B> { - public final A a; - public final B b; - - public Pair(A a, B b) { - this.a = a; - this.b = b; - } - } + public final A a; + public final B b; + + public Pair(A a, B b) { + this.a = a; + this.b = b; + } + } } diff --git a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DroolsPDPIntegrityMonitor.java b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DroolsPDPIntegrityMonitor.java index 83d4f040..8fdd3a4d 100644 --- a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DroolsPDPIntegrityMonitor.java +++ b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DroolsPDPIntegrityMonitor.java @@ -21,426 +21,413 @@ package org.onap.policy.drools.statemanagement; import java.io.IOException; -import java.util.ArrayList; import java.util.List; import java.util.Properties; + +import org.onap.policy.common.capabilities.Startable; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.http.server.impl.IndexedHttpServletServerFactory; import org.onap.policy.common.im.IntegrityMonitor; import org.onap.policy.common.im.IntegrityMonitorException; -import org.onap.policy.drools.http.server.HttpServletServer; -import org.onap.policy.drools.properties.Startable; import org.onap.policy.drools.utils.PropertyUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * This class extends 'IntegrityMonitor' for use in the 'Drools PDP' - * virtual machine. The included audits are 'Database' and 'Repository'. + * This class extends 'IntegrityMonitor' for use in the 'Drools PDP' virtual machine. The included + * audits are 'Database' and 'Repository'. */ -public class DroolsPDPIntegrityMonitor extends IntegrityMonitor -{ - - private static final String INVALID_PROPERTY_VALUE = "init: property {} does not have the expected value of {}"; - -// get an instance of logger - private static final Logger logger = LoggerFactory.getLogger(DroolsPDPIntegrityMonitor.class); - - // static global instance - private static DroolsPDPIntegrityMonitor im = null; - - // list of audits to run - private static AuditBase[] audits = - new AuditBase[]{DbAudit.getInstance(), RepositoryAudit.getInstance()}; - - private static Properties subsystemTestProperties = null; - - private static final String PROPERTIES_NAME = "feature-state-management.properties"; - - /** - * Constructor - pass arguments to superclass, but remember properties - * @param resourceName unique name of this Integrity Monitor - * @param url the JMX URL of the MBean server - * @param properties properties used locally, as well as by - * 'IntegrityMonitor' - * @throws IntegrityMonitorException (passed from superclass) - */ - private DroolsPDPIntegrityMonitor(String resourceName, - Properties consolidatedProperties - ) throws IntegrityMonitorException { - super(resourceName, consolidatedProperties); - } - - private static void missingProperty(String prop) throws IntegrityMonitorException{ - String msg = "init: missing IntegrityMonitor property: ".concat(prop); - logger.error(msg); - throw new IntegrityMonitorException(msg); - } - - private static void logPropertyValue(String prop, String val){ - if(logger.isInfoEnabled()){ - String msg = "\n\n init: property: " + prop + " = " + val + "\n"; - logger.info(msg); - } - } - - /** - * Static initialization -- create Drools Integrity Monitor, and - * an HTTP server to handle REST 'test' requests - * @throws StateManagementPropertiesException - * @throws IntegrityMonitorException - */ - public static DroolsPDPIntegrityMonitor init(String configDir) throws IntegrityMonitorException - { - - logger.info("init: Entering and invoking PropertyUtil.getProperties() on '{}'", configDir); - - // read in properties - Properties stateManagementProperties = getProperties(configDir); - - // fetch and verify definitions of some properties, adding defaults where - // appropriate - // (the 'IntegrityMonitor' constructor does some additional verification) - - checkPropError(stateManagementProperties, StateManagementProperties.TEST_HOST); - checkPropError(stateManagementProperties, StateManagementProperties.TEST_PORT); - - addDefaultPropError(stateManagementProperties, - StateManagementProperties.TEST_SERVICES, - StateManagementProperties.TEST_SERVICES_DEFAULT); - - addDefaultPropError(stateManagementProperties, - StateManagementProperties.TEST_REST_CLASSES, - StateManagementProperties.TEST_REST_CLASSES_DEFAULT); - - addDefaultPropWarn(stateManagementProperties, - StateManagementProperties.TEST_MANAGED, - StateManagementProperties.TEST_MANAGED_DEFAULT); - - addDefaultPropWarn(stateManagementProperties, - StateManagementProperties.TEST_SWAGGER, - StateManagementProperties.TEST_SWAGGER_DEFAULT); - - checkPropError(stateManagementProperties, StateManagementProperties.RESOURCE_NAME); - checkPropError(stateManagementProperties, StateManagementProperties.FP_MONITOR_INTERVAL); - checkPropError(stateManagementProperties, StateManagementProperties.FAILED_COUNTER_THRESHOLD); - checkPropError(stateManagementProperties, StateManagementProperties.TEST_TRANS_INTERVAL); - checkPropError(stateManagementProperties, StateManagementProperties.WRITE_FPC_INTERVAL); - checkPropError(stateManagementProperties, StateManagementProperties.SITE_NAME); - checkPropError(stateManagementProperties, StateManagementProperties.NODE_TYPE); - checkPropError(stateManagementProperties, StateManagementProperties.DEPENDENCY_GROUPS); - checkPropError(stateManagementProperties, StateManagementProperties.DB_DRIVER); - checkPropError(stateManagementProperties, StateManagementProperties.DB_URL); - checkPropError(stateManagementProperties, StateManagementProperties.DB_USER); - checkPropError(stateManagementProperties, StateManagementProperties.DB_PWD); - - String testHost = stateManagementProperties.getProperty(StateManagementProperties.TEST_HOST); - String testPort = stateManagementProperties.getProperty(StateManagementProperties.TEST_PORT); - String resourceName = stateManagementProperties.getProperty(StateManagementProperties.RESOURCE_NAME); - - subsystemTestProperties = stateManagementProperties; - - // Now that we've validated the properties, create Drools Integrity Monitor - // with these properties. - im = makeMonitor(resourceName, stateManagementProperties); - logger.info("init: New DroolsPDPIntegrityMonitor instantiated, resourceName = ", resourceName); - - // create http server - makeRestServer(testHost, testPort, stateManagementProperties); - logger.info("init: Exiting and returning DroolsPDPIntegrityMonitor"); - - return im; - } - - /** - * Makes an Integrity Monitor. - * @param resourceName unique name of this Integrity Monitor - * @param properties properties used to configure the Integrity Monitor - * @return - * @throws IntegrityMonitorException - */ - private static DroolsPDPIntegrityMonitor makeMonitor(String resourceName, Properties properties) - throws IntegrityMonitorException { - - try { - return new DroolsPDPIntegrityMonitor(resourceName, properties); - - } catch (Exception e) { - throw new IntegrityMonitorException(e); - } - } - - /** - * Makes a rest server for the Integrity Monitor. - * @param testHost host name - * @param testPort port - * @param properties properties used to configure the rest server - * @throws IntegrityMonitorException - */ - private static void makeRestServer(String testHost, String testPort, Properties properties) - throws IntegrityMonitorException { - - try { - logger.info("init: Starting HTTP server, addr= {}", testHost+":"+testPort); - - IntegrityMonitorRestServer server = new IntegrityMonitorRestServer(); - server.init(properties); - - } catch (Exception e) { - logger.error("init: Caught Exception attempting to start server on testPort= {} message:", - testPort, e); - throw new IntegrityMonitorException(e); - } - } - - /** - * Gets the properties from the property file. - * @param configDir directory containing the property file - * @return the properties - * @throws IntegrityMonitorException - */ - private static Properties getProperties(String configDir) throws IntegrityMonitorException { - try { - return PropertyUtil.getProperties(configDir + "/" + PROPERTIES_NAME); - - } catch (IOException e) { - throw new IntegrityMonitorException(e); - } - } - - /** - * Checks that a property is defined. - * @param props set of properties - * @param name name of the property to check - * @throws IntegrityMonitorException - */ - private static void checkPropError(Properties props, String name) throws IntegrityMonitorException { - String val = props.getProperty(name); - if(val == null) { - missingProperty(name); - } - - logPropertyValue(name, val); - } - - /** - * Checks a property's value to verify that it matches the expected value. - * If the property is not defined, then it is added to the property set, - * with the expected value. Logs an error if the property is defined, - * but does not have the expected value. - * @param props set of properties - * @param name name of the property to check - * @param expected expected/default value - */ - private static void addDefaultPropError(Properties props, String name, String expected) { - String val = props.getProperty(name); - if(val == null) { - props.setProperty(name, expected); - - } else if( ! val.equals(expected)) { - logger.error(INVALID_PROPERTY_VALUE, name, expected); - } - - logPropertyValue(name, val); - } - - /** - * Checks a property's value to verify that it matches the expected value. - * If the property is not defined, then it is added to the property set, - * with the expected value. Logs a warning if the property is defined, - * but does not have the expected value. - * @param props set of properties - * @param name name of the property to check - * @param expected expected/default value - */ - private static void addDefaultPropWarn(Properties props, String name, String dflt) { - String val = props.getProperty(name); - if(val == null) { - props.setProperty(name, dflt); - - } else if( ! val.equals(dflt)) { - logger.warn(INVALID_PROPERTY_VALUE, name, dflt); - } - - logPropertyValue(name, val); - } - - /** - * Run tests (audits) unique to Drools PDP VM (Database + Repository) - */ - @Override - public void subsystemTest() throws IntegrityMonitorException - { - logger.info("DroolsPDPIntegrityMonitor.subsystemTest called"); - - // clear all responses (non-null values indicate an error) - for (AuditBase audit : audits) - { - audit.setResponse(null); - } - - // invoke all of the audits - for (AuditBase audit : audits) - { - try - { - // invoke the audit (responses are stored within the audit object) - audit.invoke(subsystemTestProperties); - } - catch (Exception e) - { - logger.error("{} audit error", audit.getName(), e); - if (audit.getResponse() == null) - { - // if there is no current response, use the exception message - audit.setResponse(e.getMessage()); - } - } - } - - // will contain list of subsystems where the audit failed - String responseMsg = ""; - - // Loop through all of the audits, and see which ones have failed. - // NOTE: response information is stored within the audit objects - // themselves -- only one can run at a time. - for (AuditBase audit : audits) - { - String response = audit.getResponse(); - if (response != null) - { - // the audit has failed -- add subsystem and - // and 'responseValue' with the new information - responseMsg = responseMsg.concat("\n" + audit.getName() + ": " + response); - } - } - - if(!responseMsg.isEmpty()){ - throw new IntegrityMonitorException(responseMsg); - } - } - - /* ============================================================ */ - - /** - * This is the base class for audits invoked in 'subsystemTest' - */ - public abstract static class AuditBase - { - // name of the audit - protected String name; - - // non-null indicates the error response - protected String response; - - /** - * Constructor - initialize the name, and clear the initial response - * @param name name of the audit - */ - public AuditBase(String name) - { - this.name = name; - this.response = null; - } - - /** - * @return the name of this audit - */ - public String getName() - { - return name; - } - - /** - * @return the response String (non-null indicates the error message) - */ - public String getResponse() - { - return response; - } - - /** - * Set the response string to the specified value - * @param value the new value of the response string (null = no errors) - */ - public void setResponse(String value) - { - response = value; - } - - /** - * Abstract method to invoke the audit - * @param persistenceProperties Used for DB access - * @throws Exception passed in by the audit - */ - abstract void invoke(Properties persistenceProperties) throws Exception; - } - - public static class IntegrityMonitorRestServer implements Startable { - protected volatile HttpServletServer server = null; - protected volatile Properties integrityMonitorRestServerProperties = null; - - public void init(Properties props) { - this.integrityMonitorRestServerProperties = props; - this.start(); - } - - @Override - public boolean start() { - try { - List<HttpServletServer> servers = HttpServletServer.factory.build(integrityMonitorRestServerProperties); - - if (!servers.isEmpty()) { - server = servers.get(0); - - waitServerStart(); - } - } catch (Exception e) { - logger.error("Exception building servers", e); - return false; - } - - return true; - } - - private void waitServerStart() { - try { - server.waitedStart(5); - } catch (Exception e) { - logger.error("Exception waiting for servers to start: ", e); - } - } - - @Override - public boolean stop() { - try { - server.stop(); - } catch (Exception e) { - logger.error("Exception during stop", e); - } - - return true; - } - - @Override - public void shutdown() { - this.stop(); - } - - @Override - public synchronized boolean isAlive() { - return this.integrityMonitorRestServerProperties != null; - } - } - - public static DroolsPDPIntegrityMonitor getInstance() throws IntegrityMonitorException{ - if(logger.isDebugEnabled()){ - logger.debug("getInstance() called"); - } - if (im == null) { - String msg = "No DroolsPDPIntegrityMonitor instance exists." - + " Please use the method DroolsPDPIntegrityMonitor init(String configDir)"; - throw new IntegrityMonitorException(msg); - }else{ - return im; - } - } +public class DroolsPDPIntegrityMonitor extends IntegrityMonitor { + + private static final String INVALID_PROPERTY_VALUE = "init: property {} does not have the expected value of {}"; + + // get an instance of logger + private static final Logger logger = LoggerFactory.getLogger(DroolsPDPIntegrityMonitor.class); + + // static global instance + private static DroolsPDPIntegrityMonitor im = null; + + // list of audits to run + private static AuditBase[] audits = new AuditBase[] {DbAudit.getInstance(), RepositoryAudit.getInstance()}; + + private static Properties subsystemTestProperties = null; + + private static final String PROPERTIES_NAME = "feature-state-management.properties"; + + /** + * Constructor - pass arguments to superclass, but remember properties + * + * @param resourceName unique name of this Integrity Monitor + * @param url the JMX URL of the MBean server + * @param properties properties used locally, as well as by 'IntegrityMonitor' + * @throws IntegrityMonitorException (passed from superclass) + */ + private DroolsPDPIntegrityMonitor(String resourceName, Properties consolidatedProperties) + throws IntegrityMonitorException { + super(resourceName, consolidatedProperties); + } + + private static void missingProperty(String prop) throws IntegrityMonitorException { + String msg = "init: missing IntegrityMonitor property: ".concat(prop); + logger.error(msg); + throw new IntegrityMonitorException(msg); + } + + private static void logPropertyValue(String prop, String val) { + if (logger.isInfoEnabled()) { + String msg = "\n\n init: property: " + prop + " = " + val + "\n"; + logger.info(msg); + } + } + + /** + * Static initialization -- create Drools Integrity Monitor, and an HTTP server to handle REST + * 'test' requests + * + * @throws StateManagementPropertiesException + * @throws IntegrityMonitorException + */ + public static DroolsPDPIntegrityMonitor init(String configDir) throws IntegrityMonitorException { + + logger.info("init: Entering and invoking PropertyUtil.getProperties() on '{}'", configDir); + + // read in properties + Properties stateManagementProperties = getProperties(configDir); + + // fetch and verify definitions of some properties, adding defaults where + // appropriate + // (the 'IntegrityMonitor' constructor does some additional verification) + + checkPropError(stateManagementProperties, StateManagementProperties.TEST_HOST); + checkPropError(stateManagementProperties, StateManagementProperties.TEST_PORT); + + addDefaultPropError(stateManagementProperties, StateManagementProperties.TEST_SERVICES, + StateManagementProperties.TEST_SERVICES_DEFAULT); + + addDefaultPropError(stateManagementProperties, StateManagementProperties.TEST_REST_CLASSES, + StateManagementProperties.TEST_REST_CLASSES_DEFAULT); + + addDefaultPropWarn(stateManagementProperties, StateManagementProperties.TEST_MANAGED, + StateManagementProperties.TEST_MANAGED_DEFAULT); + + addDefaultPropWarn(stateManagementProperties, StateManagementProperties.TEST_SWAGGER, + StateManagementProperties.TEST_SWAGGER_DEFAULT); + + checkPropError(stateManagementProperties, StateManagementProperties.RESOURCE_NAME); + checkPropError(stateManagementProperties, StateManagementProperties.FP_MONITOR_INTERVAL); + checkPropError(stateManagementProperties, StateManagementProperties.FAILED_COUNTER_THRESHOLD); + checkPropError(stateManagementProperties, StateManagementProperties.TEST_TRANS_INTERVAL); + checkPropError(stateManagementProperties, StateManagementProperties.WRITE_FPC_INTERVAL); + checkPropError(stateManagementProperties, StateManagementProperties.SITE_NAME); + checkPropError(stateManagementProperties, StateManagementProperties.NODE_TYPE); + checkPropError(stateManagementProperties, StateManagementProperties.DEPENDENCY_GROUPS); + checkPropError(stateManagementProperties, StateManagementProperties.DB_DRIVER); + checkPropError(stateManagementProperties, StateManagementProperties.DB_URL); + checkPropError(stateManagementProperties, StateManagementProperties.DB_USER); + checkPropError(stateManagementProperties, StateManagementProperties.DB_PWD); + + String testHost = stateManagementProperties.getProperty(StateManagementProperties.TEST_HOST); + String testPort = stateManagementProperties.getProperty(StateManagementProperties.TEST_PORT); + String resourceName = stateManagementProperties.getProperty(StateManagementProperties.RESOURCE_NAME); + + subsystemTestProperties = stateManagementProperties; + + // Now that we've validated the properties, create Drools Integrity Monitor + // with these properties. + im = makeMonitor(resourceName, stateManagementProperties); + logger.info("init: New DroolsPDPIntegrityMonitor instantiated, resourceName = ", resourceName); + + // create http server + makeRestServer(testHost, testPort, stateManagementProperties); + logger.info("init: Exiting and returning DroolsPDPIntegrityMonitor"); + + return im; + } + + /** + * Makes an Integrity Monitor. + * + * @param resourceName unique name of this Integrity Monitor + * @param properties properties used to configure the Integrity Monitor + * @return + * @throws IntegrityMonitorException + */ + private static DroolsPDPIntegrityMonitor makeMonitor(String resourceName, Properties properties) + throws IntegrityMonitorException { + + try { + return new DroolsPDPIntegrityMonitor(resourceName, properties); + + } catch (Exception e) { + throw new IntegrityMonitorException(e); + } + } + + /** + * Makes a rest server for the Integrity Monitor. + * + * @param testHost host name + * @param testPort port + * @param properties properties used to configure the rest server + * @throws IntegrityMonitorException + */ + private static void makeRestServer(String testHost, String testPort, Properties properties) + throws IntegrityMonitorException { + + try { + logger.info("init: Starting HTTP server, addr= {}", testHost + ":" + testPort); + + IntegrityMonitorRestServer server = new IntegrityMonitorRestServer(); + server.init(properties); + + } catch (Exception e) { + logger.error("init: Caught Exception attempting to start server on testPort= {} message:", testPort, e); + throw new IntegrityMonitorException(e); + } + } + + /** + * Gets the properties from the property file. + * + * @param configDir directory containing the property file + * @return the properties + * @throws IntegrityMonitorException + */ + private static Properties getProperties(String configDir) throws IntegrityMonitorException { + try { + return PropertyUtil.getProperties(configDir + "/" + PROPERTIES_NAME); + + } catch (IOException e) { + throw new IntegrityMonitorException(e); + } + } + + /** + * Checks that a property is defined. + * + * @param props set of properties + * @param name name of the property to check + * @throws IntegrityMonitorException + */ + private static void checkPropError(Properties props, String name) throws IntegrityMonitorException { + String val = props.getProperty(name); + if (val == null) { + missingProperty(name); + } + + logPropertyValue(name, val); + } + + /** + * Checks a property's value to verify that it matches the expected value. If the property is + * not defined, then it is added to the property set, with the expected value. Logs an error if + * the property is defined, but does not have the expected value. + * + * @param props set of properties + * @param name name of the property to check + * @param expected expected/default value + */ + private static void addDefaultPropError(Properties props, String name, String expected) { + String val = props.getProperty(name); + if (val == null) { + props.setProperty(name, expected); + + } else if (!val.equals(expected)) { + logger.error(INVALID_PROPERTY_VALUE, name, expected); + } + + logPropertyValue(name, val); + } + + /** + * Checks a property's value to verify that it matches the expected value. If the property is + * not defined, then it is added to the property set, with the expected value. Logs a warning if + * the property is defined, but does not have the expected value. + * + * @param props set of properties + * @param name name of the property to check + * @param expected expected/default value + */ + private static void addDefaultPropWarn(Properties props, String name, String dflt) { + String val = props.getProperty(name); + if (val == null) { + props.setProperty(name, dflt); + + } else if (!val.equals(dflt)) { + logger.warn(INVALID_PROPERTY_VALUE, name, dflt); + } + + logPropertyValue(name, val); + } + + /** + * Run tests (audits) unique to Drools PDP VM (Database + Repository) + */ + @Override + public void subsystemTest() throws IntegrityMonitorException { + logger.info("DroolsPDPIntegrityMonitor.subsystemTest called"); + + // clear all responses (non-null values indicate an error) + for (AuditBase audit : audits) { + audit.setResponse(null); + } + + // invoke all of the audits + for (AuditBase audit : audits) { + try { + // invoke the audit (responses are stored within the audit object) + audit.invoke(subsystemTestProperties); + } catch (Exception e) { + logger.error("{} audit error", audit.getName(), e); + if (audit.getResponse() == null) { + // if there is no current response, use the exception message + audit.setResponse(e.getMessage()); + } + } + } + + // will contain list of subsystems where the audit failed + String responseMsg = ""; + + // Loop through all of the audits, and see which ones have failed. + // NOTE: response information is stored within the audit objects + // themselves -- only one can run at a time. + for (AuditBase audit : audits) { + String response = audit.getResponse(); + if (response != null) { + // the audit has failed -- add subsystem and + // and 'responseValue' with the new information + responseMsg = responseMsg.concat("\n" + audit.getName() + ": " + response); + } + } + + if (!responseMsg.isEmpty()) { + throw new IntegrityMonitorException(responseMsg); + } + } + + /* ============================================================ */ + + /** + * This is the base class for audits invoked in 'subsystemTest' + */ + public abstract static class AuditBase { + // name of the audit + protected String name; + + // non-null indicates the error response + protected String response; + + /** + * Constructor - initialize the name, and clear the initial response + * + * @param name name of the audit + */ + public AuditBase(String name) { + this.name = name; + this.response = null; + } + + /** + * @return the name of this audit + */ + public String getName() { + return name; + } + + /** + * @return the response String (non-null indicates the error message) + */ + public String getResponse() { + return response; + } + + /** + * Set the response string to the specified value + * + * @param value the new value of the response string (null = no errors) + */ + public void setResponse(String value) { + response = value; + } + + /** + * Abstract method to invoke the audit + * + * @param persistenceProperties Used for DB access + * @throws Exception passed in by the audit + */ + abstract void invoke(Properties persistenceProperties) throws Exception; + } + + public static class IntegrityMonitorRestServer implements Startable { + protected volatile HttpServletServer server = null; + protected volatile Properties integrityMonitorRestServerProperties = null; + + public void init(Properties props) { + this.integrityMonitorRestServerProperties = props; + this.start(); + } + + @Override + public boolean start() { + try { + List<HttpServletServer> servers = + IndexedHttpServletServerFactory.getInstance().build(integrityMonitorRestServerProperties); + + if (!servers.isEmpty()) { + server = servers.get(0); + + waitServerStart(); + } + } catch (Exception e) { + logger.error("Exception building servers", e); + return false; + } + + return true; + } + + private void waitServerStart() { + try { + server.waitedStart(5); + } catch (Exception e) { + logger.error("Exception waiting for servers to start: ", e); + } + } + + @Override + public boolean stop() { + try { + server.stop(); + } catch (Exception e) { + logger.error("Exception during stop", e); + } + + return true; + } + + @Override + public void shutdown() { + this.stop(); + } + + @Override + public synchronized boolean isAlive() { + return this.integrityMonitorRestServerProperties != null; + } + } + + public static DroolsPDPIntegrityMonitor getInstance() throws IntegrityMonitorException { + if (logger.isDebugEnabled()) { + logger.debug("getInstance() called"); + } + if (im == null) { + String msg = "No DroolsPDPIntegrityMonitor instance exists." + + " Please use the method DroolsPDPIntegrityMonitor init(String configDir)"; + throw new IntegrityMonitorException(msg); + } else { + return im; + } + } } diff --git a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementProperties.java b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementProperties.java index 192acc16..38356226 100644 --- a/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementProperties.java +++ b/feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementProperties.java @@ -22,65 +22,71 @@ package org.onap.policy.drools.statemanagement; import java.util.Properties; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class StateManagementProperties { - // get an instance of logger - private static final Logger logger = LoggerFactory.getLogger(StateManagementProperties.class); - - public static final String NODE_NAME = "resource.name"; - public static final String NODE_TYPE = "node_type"; - public static final String SITE_NAME = "site_name"; - - public static final String DB_DRIVER = "javax.persistence.jdbc.driver"; - public static final String DB_URL = "javax.persistence.jdbc.url"; - public static final String DB_USER = "javax.persistence.jdbc.user"; - public static final String DB_PWD = "javax.persistence.jdbc.password"; - - public static final String TEST_SERVICES = PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES; - public static final String TEST_SERVICES_DEFAULT = "TEST"; - public static final String TEST_HOST = TEST_SERVICES + "." + TEST_SERVICES_DEFAULT + PolicyProperties.PROPERTY_HTTP_HOST_SUFFIX; - public static final String TEST_PORT = TEST_SERVICES + "." + TEST_SERVICES_DEFAULT + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX; - public static final String TEST_REST_CLASSES = TEST_SERVICES + "." + TEST_SERVICES_DEFAULT + PolicyProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX; - public static final String TEST_REST_CLASSES_DEFAULT = IntegrityMonitorRestManager.class.getName(); - public static final String TEST_MANAGED = TEST_SERVICES + "." + TEST_SERVICES_DEFAULT + PolicyProperties.PROPERTY_MANAGED_SUFFIX; - public static final String TEST_MANAGED_DEFAULT = "false"; - public static final String TEST_SWAGGER = TEST_SERVICES + "." + TEST_SERVICES_DEFAULT + PolicyProperties.PROPERTY_HTTP_SWAGGER_SUFFIX; - public static final String TEST_SWAGGER_DEFAULT = "true"; - public static final String RESOURCE_NAME = "resource.name"; - public static final String FP_MONITOR_INTERVAL = "fp_monitor_interval"; - public static final String FAILED_COUNTER_THRESHOLD = "failed_counter_threshold"; - public static final String TEST_TRANS_INTERVAL = "test_trans_interval"; - public static final String WRITE_FPC_INTERVAL = "write_fpc_interval"; - public static final String DEPENDENCY_GROUPS = "dependency_groups"; - - private static Properties properties = null; + // get an instance of logger + private static final Logger logger = LoggerFactory.getLogger(StateManagementProperties.class); - private StateManagementProperties(){ - } - /* - * Initialize the parameter values from the feature-state-management.properties file values - * - * This is designed so that the Properties object is obtained from the feature-state-management.properties - * file and then is passed to this method to initialize the value of the parameters. - * This allows the flexibility of JUnit tests using getProperties(filename) to get the - * properties while runtime methods can use getPropertiesFromClassPath(filename). - * - */ - public static void initProperties (Properties prop){ - logger.info("StateManagementProperties.initProperties(Properties): entry"); - logger.info("\n\nStateManagementProperties.initProperties: Properties = \n{}\n\n", prop); - - properties = prop; - } + public static final String NODE_NAME = "resource.name"; + public static final String NODE_TYPE = "node_type"; + public static final String SITE_NAME = "site_name"; - public static String getProperty(String key){ - return properties.getProperty(key); - } - - public static Properties getProperties() { - return properties; - } + public static final String DB_DRIVER = "javax.persistence.jdbc.driver"; + public static final String DB_URL = "javax.persistence.jdbc.url"; + public static final String DB_USER = "javax.persistence.jdbc.user"; + public static final String DB_PWD = "javax.persistence.jdbc.password"; + + public static final String TEST_SERVICES = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES; + public static final String TEST_SERVICES_DEFAULT = "TEST"; + public static final String TEST_HOST = + TEST_SERVICES + "." + TEST_SERVICES_DEFAULT + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX; + public static final String TEST_PORT = + TEST_SERVICES + "." + TEST_SERVICES_DEFAULT + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX; + public static final String TEST_REST_CLASSES = + TEST_SERVICES + "." + TEST_SERVICES_DEFAULT + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX; + public static final String TEST_REST_CLASSES_DEFAULT = IntegrityMonitorRestManager.class.getName(); + public static final String TEST_MANAGED = + TEST_SERVICES + "." + TEST_SERVICES_DEFAULT + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX; + public static final String TEST_MANAGED_DEFAULT = "false"; + public static final String TEST_SWAGGER = + TEST_SERVICES + "." + TEST_SERVICES_DEFAULT + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX; + public static final String TEST_SWAGGER_DEFAULT = "true"; + public static final String RESOURCE_NAME = "resource.name"; + public static final String FP_MONITOR_INTERVAL = "fp_monitor_interval"; + public static final String FAILED_COUNTER_THRESHOLD = "failed_counter_threshold"; + public static final String TEST_TRANS_INTERVAL = "test_trans_interval"; + public static final String WRITE_FPC_INTERVAL = "write_fpc_interval"; + public static final String DEPENDENCY_GROUPS = "dependency_groups"; + + private static Properties properties = null; + + private StateManagementProperties() {} + + /* + * Initialize the parameter values from the feature-state-management.properties file values + * + * This is designed so that the Properties object is obtained from the + * feature-state-management.properties file and then is passed to this method to initialize the + * value of the parameters. This allows the flexibility of JUnit tests using + * getProperties(filename) to get the properties while runtime methods can use + * getPropertiesFromClassPath(filename). + * + */ + public static void initProperties(Properties prop) { + logger.info("StateManagementProperties.initProperties(Properties): entry"); + logger.info("\n\nStateManagementProperties.initProperties: Properties = \n{}\n\n", prop); + + properties = prop; + } + + public static String getProperty(String key) { + return properties.getProperty(key); + } + + public static Properties getProperties() { + return properties; + } } diff --git a/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionTest.java b/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionTest.java index 5dd630e1..fd373a1d 100644 --- a/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionTest.java +++ b/feature-test-transaction/src/test/java/org/onap/policy/drools/testtransaction/TestTransactionTest.java @@ -33,7 +33,7 @@ import java.util.Set; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.drools.properties.DroolsProperties; import org.onap.policy.drools.system.PolicyController; import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; @@ -76,7 +76,7 @@ public class TestTransactionTest { @Test public void registerUnregisterTest() throws InterruptedException { final Properties controllerProperties = new Properties(); - controllerProperties.put(PolicyProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME); + controllerProperties.put(DroolsProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME); final PolicyController controller = PolicyEngine.manager.createPolicyController(TEST_CONTROLLER_NAME, controllerProperties); assertNotNull(PolicyController.factory.get(TEST_CONTROLLER_NAME)); diff --git a/policy-core/pom.xml b/policy-core/pom.xml index cc41b215..e5be8c39 100644 --- a/policy-core/pom.xml +++ b/policy-core/pom.xml @@ -91,6 +91,11 @@ </dependency> <dependency> <groupId>org.onap.policy.common</groupId> + <artifactId>capabilities</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> <artifactId>utils</artifactId> <version>${project.version}</version> </dependency> diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java index 4806df04..1e8a2882 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java @@ -34,831 +34,668 @@ import org.kie.api.builder.ReleaseId; import org.kie.api.builder.Results; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; -import org.onap.policy.drools.properties.Startable; +import org.onap.policy.common.capabilities.Startable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * This class is a wrapper around 'KieContainer', which adds the ability - * to automatically create and track KieSession instances. + * This class is a wrapper around 'KieContainer', which adds the ability to automatically create and + * track KieSession instances. */ -public class PolicyContainer implements Startable -{ - // get an instance of logger - private static Logger logger = LoggerFactory.getLogger(PolicyContainer.class); - // 'KieServices' singleton - private static KieServices kieServices = KieServices.Factory.get(); - - // set of all 'PolicyContainer' instances - private static HashSet<PolicyContainer> containers = - new HashSet<>(); - - // maps feature objects to per-PolicyContainer data - private ConcurrentHashMap<Object, Object> adjuncts = - new ConcurrentHashMap<>(); - - // 'KieContainer' associated with this 'PolicyContainer' - private KieContainer kieContainer; - - // indicates whether the PolicyContainer is 'started' - // (started = sessions created, threads running) - private volatile boolean isStarted = false; - - // maps session name into the associated 'PolicySession' instance - private HashMap<String, PolicySession> sessions = - new HashMap<>(); - - // if not null, this is a 'KieScanner' looking for updates - private KieScanner scanner = null; - - // indicates whether the scanner has been started - // (it can block for a long time) - private boolean scannerStarted = false; - - private static final String ERROR_STRING = "ERROR: Feature API: "; - - /** - * uses 'groupId', 'artifactId' and 'version', and fetches the associated - * artifact and remaining dependencies from the Maven repository to create - * the 'PolicyContainer' and associated 'KieContainer'. - * - * An exception occurs if the creation of the 'KieContainer' fails. - * - * @param groupId the 'groupId' associated with the artifact - * @param artifactId the artifact name - * @param version a comma-separated list of possible versions - */ - public PolicyContainer(String groupId, String artifactId, String version) - { - this(kieServices.newReleaseId(groupId, artifactId, version)); - } - - /** - * uses the 'groupId', 'artifactId' and 'version' information in 'ReleaseId', - * and fetches the associated artifact and remaining dependencies from the - * Maven repository to create the 'PolicyContainer' and associated - * 'KieContainer'. - * - * An exception occurs if the creation of the 'KieContainer' fails. - * - * @param releaseId indicates the artifact that is to be installed in this - * container - */ - public PolicyContainer(ReleaseId releaseId) - { - ReleaseId newReleaseId = releaseId; - if (newReleaseId.getVersion().contains(",")) - { - // this is actually a comma-separated list of release ids - newReleaseId = loadArtifact(newReleaseId.getGroupId(), - newReleaseId.getArtifactId(), - newReleaseId.getVersion()); - } - else - { - kieContainer = kieServices.newKieContainer(newReleaseId); - } - synchronized(containers) - { - if(newReleaseId != null){ - logger.info("Add a new kieContainer in containers: releaseId: " + newReleaseId.toString()); - }else{ - logger.warn("input releaseId is null"); - } - containers.add(this); - } - // 'startScanner(releaseId)' was called at this point, but we have seen - // at least one case where the Drools container was repeatedly updated - // every 60 seconds. It isn't clear what conditions resulted in this - // behavior, so the call was removed. If needed, it can be explicitly - // called from a feature. - } - - /** - * Load an artifact into a new KieContainer. This method handles the - * case where the 'version' is actually a comma-separated list of - * versions. - * - * @param groupId the 'groupId' associated with the artifact - * @param artifactId the artifact name - * @param version a comma-separated list of possible versions - */ - private ReleaseId loadArtifact - (String groupId, String artifactId, String version) - { - String[] versions = version.split(","); - if (versions.length > 1) - { - logger.info("Multiple KieContainer versions are specified: " - + version); - } - - // indicates a 'newKieContainer' call failed - RuntimeException exception = null; - - // set prior to every 'newKieContainer' invocation - // (if we are able to create the container, it will be the last - // one that was successful) - ReleaseId releaseId = null; - for (String ver : versions) - { - try - { - // Create a 'ReleaseId' object describing the artifact, and - // create a 'KieContainer' based upon it. - logger.info("Create new KieContainer start, version = " - + ver + " ..."); - - releaseId = kieServices.newReleaseId(groupId, artifactId, ver); - kieContainer = kieServices.newKieContainer(releaseId); - - // clear any exception, and break out of the loop - exception = null; - break; - } - catch (RuntimeException e) - { - exception = e; - } - } - if (exception != null) - { - // all of the 'newKieContainer' invocations failed -- throw the - // most recent exception - throw exception; - } - return releaseId; - } - - /** - * @return the name of the container, which is the String equivalent of - * the 'ReleaseId'. It has the form: - * - * (groupId + ":" + artifactId + ":" + version) - * - * Note that the name changes after a successful call to 'updateToVersion', - * although typically only the 'version' part changes. - */ - public String getName() - { - return kieContainer.getReleaseId().toString(); - } - - /** - * @return the associated 'KieContainer' instance - */ - public KieContainer getKieContainer() - { - return kieContainer; - } - - /** - * @return the 'ClassLoader' associated with the 'KieContainer' instance - */ - public ClassLoader getClassLoader() - { - return kieContainer.getClassLoader(); - } - - /** - * @return the Maven GroupId of the top-level artifact wrapped - * by the container. - */ - public String getGroupId() - { - return kieContainer.getReleaseId().getGroupId(); - } - - /** - * @return the Maven ArtifactId of the top-level artifact wrapped - * by the container. - */ - public String getArtifactId() - { - return kieContainer.getReleaseId().getArtifactId(); - } - - /** - * @return the version of the top-level artifact wrapped by the - * container (this may change as updates occur) - */ - public String getVersion() - { - return kieContainer.getReleaseId().getVersion(); - } - - /** - * Fetch the named 'PolicySession'. - * - * @param name the name of the KieSession (which is also the name of - * the associated PolicySession) - * @return a PolicySession if found, 'null' if not - */ - public PolicySession getPolicySession(String name) - { - return sessions.get(name); - } - - /** - * Internal method to create a PolicySession, possibly restoring it - * from persistent storage. - * - * @param name of the KieSession and PolicySession - * @param kieBaseName name of the associated 'KieBase' instance - * @return a new or existing PolicySession, or 'null' if not found - */ - private PolicySession activatePolicySession(String name, String kieBaseName) - { - synchronized(sessions) - { - logger.info("activatePolicySession:name :" + name); - PolicySession session = sessions.get(name); - if (session == null) - { - KieSession kieSession = null; - - // loop through all of the features, and give each one - // a chance to create the 'KieSession' - for (PolicySessionFeatureAPI feature : - PolicySessionFeatureAPI.impl.getList()) - { - try - { - if ((kieSession = feature.activatePolicySession - (this, name, kieBaseName)) != null) - break; - } - catch (Exception e) - { - logger.error(ERROR_STRING - + feature.getClass().getName(), e); - } - } - - // if none of the features created the session, create one now - if (kieSession == null) - { - kieSession = kieContainer.newKieSession(name); - } - - if (kieSession != null) - { - // creation of 'KieSession' was successful - build - // a PolicySession - session = new PolicySession(name, this, kieSession); - sessions.put(name, session); - - // notify features - for (PolicySessionFeatureAPI feature : - PolicySessionFeatureAPI.impl.getList()) - { - try - { - feature.newPolicySession(session); - } - catch (Exception e) - { - logger.error(ERROR_STRING - + feature.getClass().getName(), e); - } - } - logger.info("activatePolicySession:new session was added in sessions with name " + name); - } - } - logger.info("activatePolicySession:session - " - + (session == null ? "null" : session.getFullName()) - + " is returned."); - return session; - } - } - - /** - * This creates a 'PolicySession' instance within this 'PolicyContainer', - * and ties it to the specified 'KieSession'. 'name' must not currently - * exist within the 'PolicyContainer', and the 'KieBase' object associated - * with 'KieSession' must belong to the 'KieContainer'. This method provides - * a way for 'KieSession' instances that are created programmatically to fit - * into this framework. - * - * @param name the name for the new 'PolicySession' - * @param kieSession a 'KieSession' instance, that will be included in - * this infrastructure - * @return the new 'PolicySession' - * @throws IllegalArgumentException if 'kieSession' does not reside within - * this container - * @throws IllegalStateException if a 'PolicySession' already exists - * with this name - */ - public PolicySession adoptKieSession(String name, KieSession kieSession) - { - - if(name == null){ - logger.warn("adoptKieSession:input name is null"); - throw new IllegalArgumentException - ("KieSession input name is null " - + getName()); - }else if(kieSession == null){ - logger.warn("adoptKieSession:input kieSession is null"); - throw new IllegalArgumentException - ("KieSession '" + name + "' is null " - + getName()); - }else { - logger.info("adoptKieSession:name: " + name + " kieSession: " + kieSession); - } - // fetch KieBase, and verify it belongs to this KieContainer - boolean match = false; - KieBase kieBase = kieSession.getKieBase(); - logger.info("adoptKieSession:kieBase: " + kieBase); - for (String kieBaseName : kieContainer.getKieBaseNames()) - { - logger.info("adoptKieSession:kieBaseName: " + kieBaseName); - if (kieBase == kieContainer.getKieBase(kieBaseName)) - { - match = true; - break; - } - } - logger.info("adoptKieSession:match " + match); - // if we don't have a match yet, the last chance is to look at the - // default KieBase, if it exists - if (!match && kieBase != kieContainer.getKieBase()) - { - throw new IllegalArgumentException - ("KieSession '" + name + "' does not reside within container " - + getName()); - } - - synchronized (sessions) - { - if (sessions.get(name) != null) - { - throw new IllegalStateException - ("PolicySession '" + name + "' already exists"); - } - - // create the new 'PolicySession', add it to the table, - // and return the object to the caller - logger.info("adoptKieSession:create a new policySession with name " + name); - PolicySession policySession = - new PolicySession(name, this, kieSession); - sessions.put(name, policySession); - - // notify features - for (PolicySessionFeatureAPI feature : - PolicySessionFeatureAPI.impl.getList()) - { - try - { - feature.newPolicySession(policySession); - } - catch (Exception e) - { - logger.error(ERROR_STRING - + feature.getClass().getName(), e); - } - } - return policySession; - } - } - - /** - * This call 'KieContainer.updateToVersion()', and returns the associated - * response as a String. If successful, the name of this 'PolicyContainer' - * changes to match the new version. - * - * @param newVersion this is the version to update to (the 'groupId' - * and 'artifactId' remain the same) - * @return the list of messages associated with the update (not sure if - * this can be 'null', or how to determine success/failure) - */ - public String updateToVersion(String newVersion) - { - ReleaseId releaseId = kieContainer.getReleaseId(); - Results results = this.updateToVersion - (kieServices.newReleaseId(releaseId.getGroupId(), - releaseId.getArtifactId(), - newVersion)); - - List<Message> messages = results == null ? null : results.getMessages(); - return messages == null ? null : messages.toString(); - } - - /** - * This calls 'KieContainer.updateToVersion()', and returns the associated - * response. If successful, the name of this 'PolicyContainer' changes to - * match the new version. - * - * @param releaseId the new artifact (usually new version) to be installed - * @return the 'Results' parameter from 'KieContainer.updateToVersion' - */ - public Results updateToVersion(ReleaseId releaseId) - { - if(releaseId == null){ - logger.warn("updateToVersion:input releaseId is null"); - }else { - logger.info("updateToVersion:releaseId " + releaseId.toString()); +public class PolicyContainer implements Startable { + // get an instance of logger + private static Logger logger = LoggerFactory.getLogger(PolicyContainer.class); + // 'KieServices' singleton + private static KieServices kieServices = KieServices.Factory.get(); + + // set of all 'PolicyContainer' instances + private static HashSet<PolicyContainer> containers = new HashSet<>(); + + // maps feature objects to per-PolicyContainer data + private ConcurrentHashMap<Object, Object> adjuncts = new ConcurrentHashMap<>(); + + // 'KieContainer' associated with this 'PolicyContainer' + private KieContainer kieContainer; + + // indicates whether the PolicyContainer is 'started' + // (started = sessions created, threads running) + private volatile boolean isStarted = false; + + // maps session name into the associated 'PolicySession' instance + private HashMap<String, PolicySession> sessions = new HashMap<>(); + + // if not null, this is a 'KieScanner' looking for updates + private KieScanner scanner = null; + + // indicates whether the scanner has been started + // (it can block for a long time) + private boolean scannerStarted = false; + + private static final String ERROR_STRING = "ERROR: Feature API: "; + + /** + * uses 'groupId', 'artifactId' and 'version', and fetches the associated artifact and remaining + * dependencies from the Maven repository to create the 'PolicyContainer' and associated + * 'KieContainer'. + * + * An exception occurs if the creation of the 'KieContainer' fails. + * + * @param groupId the 'groupId' associated with the artifact + * @param artifactId the artifact name + * @param version a comma-separated list of possible versions + */ + public PolicyContainer(String groupId, String artifactId, String version) { + this(kieServices.newReleaseId(groupId, artifactId, version)); } - // stop all session threads - for (PolicySession session : sessions.values()) - { - session.stopThread(); - } - - // update the version - Results results = kieContainer.updateToVersion(releaseId); - - // restart all session threads, and notify the sessions - for (PolicySession session : sessions.values()) - { - session.startThread(); - session.updated(); - } - - return results; - } - - /** - * @return all existing 'PolicyContainer' instances - */ - public static Collection<PolicyContainer> getPolicyContainers() - { - synchronized(containers) - { - return new HashSet<>(containers); - } - } - - /** - * @return all of the 'PolicySession' instances - */ - public Collection<PolicySession> getPolicySessions() - { - // KLUDGE WARNING: this is a temporary workaround -- if there are - // no features, we don't have persistence, and 'activate' is never - // called. In this case, make sure the container is started. - if (PolicySessionFeatureAPI.impl.getList().isEmpty()) - { - start(); - } - - // return current set of PolicySessions - synchronized(sessions) - { - return new HashSet<>(sessions.values()); - } - } - - /** - * This method will start a 'KieScanner' (if not currently running), - * provided that the ReleaseId version is 'LATEST' or 'RELEASE', - * or refers to a SNAPSHOT version. - * - * @param releaseId the release id used to create the container - */ - public synchronized void startScanner(ReleaseId releaseId) - { - String version = releaseId.getVersion(); - if (!scannerStarted && scanner == null && version != null - && ("LATEST".equals(version) || "RELEASE".equals(version) - || version.endsWith("-SNAPSHOT"))) - { - // create the scanner, and poll at 60 second intervals - try - { - scannerStarted = true; - - // start this in a separate thread -- it can block for a long time - new Thread("Scanner Starter " + getName()) - { - @Override - public void run() - { - scanner = kieServices.newKieScanner(kieContainer); - scanner.start(60000L); - } - }.start(); - } - catch (Exception e) - { - // sometimes the scanner initialization fails for some reason - logger.error("startScanner error", e); - } - } - } - - /** - * Insert a fact into a specific named session - * - * @param name this is the session name - * @param object this is the fact to be inserted into the session - * @return 'true' if the named session was found, 'false' if not - */ - public boolean insert(String name, Object object) - { - // TODO: Should the definition of 'name' be expanded to include an - // alternate entry point as well? For example, 'name.entryPoint' (or - // something other than '.' if that is a problem). - synchronized (sessions) - { - PolicySession session = sessions.get(name); - if (session != null) - { - session.getKieSession().insert(object); - return true; - } - } - return false; - } - - /** - * Insert a fact into all sessions associated with this container - * - * @param object this is the fact to be inserted into the sessions - * @return 'true' if the fact was inserted into at least one session, - * 'false' if not - */ - public boolean insertAll(Object object) - { - boolean rval = false; - synchronized (sessions) - { - for (PolicySession session : sessions.values()) - { - session.getKieSession().insert(object); - rval = true; - } - } - return rval; - } - - /*************************/ - /* 'Startable' interface */ - /*************************/ - - /** - * {@inheritDoc} - */ - @Override - public synchronized boolean start() - { - if (!isStarted) - { - // This will create all 'PolicySession' instances specified in the - // 'kmodule.xml' file that don't exist yet - for (String kieBaseName : kieContainer.getKieBaseNames()) - { - for (String kieSessionName : - kieContainer.getKieSessionNamesInKieBase(kieBaseName)) - { - // if the 'PolicySession' does not currently exist, this method - // call will attempt to create it - PolicySession session = - activatePolicySession(kieSessionName, kieBaseName); - if (session != null) - { - session.startThread(); - } - } - } - isStarted = true; - } - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized boolean stop() - { - if (isStarted) - { - Collection<PolicySession> localSessions; - - synchronized (sessions) - { - // local set containing all of the sessions - localSessions = new HashSet<>(sessions.values()); - - // clear the 'name->session' map in 'PolicyContainer' - sessions.clear(); - } - for (PolicySession session : localSessions) - { - // stop session thread - session.stopThread(); - - // free KieSession resources - session.getKieSession().dispose(); - - // notify features - for (PolicySessionFeatureAPI feature : - PolicySessionFeatureAPI.impl.getList()) - { - try - { - feature.disposeKieSession(session); - } - catch (Exception e) - { - logger.error(ERROR_STRING - + feature.getClass().getName(), e); - } - } - } - isStarted = false; - } - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public synchronized void shutdown() - { - // Note that this method does not call 'destroy' on the 'KieSession' - // instances, which would remove any associated information in persistent - // storage. Should it do this? - - stop(); - synchronized(containers) - { - containers.remove(this); - } - - // How do we free the resources associated with the KieContainer? - // Is garbage collection sufficient? - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isAlive() - { - return isStarted; - } - - /*************************/ - - /** - * This method is similar to 'shutdown', but it also frees any persistence - * resources as well. - */ - public synchronized void destroy() - { - // we need all KieSession instances running in order to free - // resources associated with persistence - start(); - Collection<PolicySession> localSessions; - - synchronized (sessions) - { - // local set containing all of the sessions - localSessions = new HashSet<>(sessions.values()); - - // clear the 'name->session' map in 'PolicyContainer' - sessions.clear(); - } - for (PolicySession session : localSessions) - { - // stop session thread - session.stopThread(); - - // free KieSession resources - session.getKieSession().destroy(); - - // notify features - for (PolicySessionFeatureAPI feature : - PolicySessionFeatureAPI.impl.getList()) - { - try - { - feature.destroyKieSession(session); - } - catch (Exception e) - { - logger.error(ERROR_STRING - + feature.getClass().getName(), e); - } - } - } - isStarted = false; - - synchronized(containers) - { - containers.remove(this); - } - - // How do we free the resources associated with the KieContainer? - // Is garbage collection sufficient? - } - - /** - * This method is called when the host goes from the 'standby->active' state. - */ - public static void activate() - { - // start all of the 'PolicyContainer' instances - for (PolicyContainer container : containers) - { - try - { - container.start(); - } - catch (Exception e) - { - logger.error("PolicyContainer.start() error in activate", e); - } - } - } - - /** - * This method is called when the host goes from the 'active->standby' state. - */ - public static void deactivate() - { - // deactivate all of the 'PolicyContainer' instances - for (PolicyContainer container : containers) - { - try - { - container.stop(); - } - catch (Exception e) - { - logger.error("PolicyContainer.start() error in deactivate", e); - } - } - } - - /** - * This method does the following: - * - * 1) Initializes logging - * 2) Starts the DroolsPDP Integrity Monitor - * 3) Initilaizes persistence - * - * It no longer reads in properties files, o creates 'PolicyContainer' - * instances. - * - * @param args standard 'main' arguments, which are currently ignored - */ - public static void globalInit(String[] args) - { - String configDir = "config"; - logger.info("PolicyContainer.main: configDir=" + configDir); - - // invoke 'globalInit' on all of the features - for (PolicySessionFeatureAPI feature : - PolicySessionFeatureAPI.impl.getList()) - { - try - { - feature.globalInit(args, configDir); - } - catch (Exception e) - { - logger.error(ERROR_STRING - + feature.getClass().getName(), e); - } - } - } - - /** - * Fetch the adjunct object associated with a given feature - * - * @param object this is typically the singleton feature object that is - * used as a key, but it might also be useful to use nested objects - * within the feature as keys. - * @return a feature-specific object associated with the key, or 'null' - * if it is not found. - */ - public Object getAdjunct(Object object) - { - return adjuncts.get(object); - } - - /** - * Store the adjunct object associated with a given feature - * - * @param object this is typically the singleton feature object that is - * used as a key, but it might also be useful to use nested objects - * within the feature as keys. - * @param value a feature-specific object associated with the key, or 'null' - * if the feature-specific object should be removed - */ - public void setAdjunct(Object object, Object value) - { - if (value == null) - { - adjuncts.remove(object); - } - else - { - adjuncts.put(object, value); - } - } + /** + * uses the 'groupId', 'artifactId' and 'version' information in 'ReleaseId', and fetches the + * associated artifact and remaining dependencies from the Maven repository to create the + * 'PolicyContainer' and associated 'KieContainer'. + * + * An exception occurs if the creation of the 'KieContainer' fails. + * + * @param releaseId indicates the artifact that is to be installed in this container + */ + public PolicyContainer(ReleaseId releaseId) { + ReleaseId newReleaseId = releaseId; + if (newReleaseId.getVersion().contains(",")) { + // this is actually a comma-separated list of release ids + newReleaseId = + loadArtifact(newReleaseId.getGroupId(), newReleaseId.getArtifactId(), newReleaseId.getVersion()); + } else { + kieContainer = kieServices.newKieContainer(newReleaseId); + } + synchronized (containers) { + if (newReleaseId != null) { + logger.info("Add a new kieContainer in containers: releaseId: " + newReleaseId.toString()); + } else { + logger.warn("input releaseId is null"); + } + containers.add(this); + } + // 'startScanner(releaseId)' was called at this point, but we have seen + // at least one case where the Drools container was repeatedly updated + // every 60 seconds. It isn't clear what conditions resulted in this + // behavior, so the call was removed. If needed, it can be explicitly + // called from a feature. + } + + /** + * Load an artifact into a new KieContainer. This method handles the case where the 'version' is + * actually a comma-separated list of versions. + * + * @param groupId the 'groupId' associated with the artifact + * @param artifactId the artifact name + * @param version a comma-separated list of possible versions + */ + private ReleaseId loadArtifact(String groupId, String artifactId, String version) { + String[] versions = version.split(","); + if (versions.length > 1) { + logger.info("Multiple KieContainer versions are specified: " + version); + } + + // indicates a 'newKieContainer' call failed + RuntimeException exception = null; + + // set prior to every 'newKieContainer' invocation + // (if we are able to create the container, it will be the last + // one that was successful) + ReleaseId releaseId = null; + for (String ver : versions) { + try { + // Create a 'ReleaseId' object describing the artifact, and + // create a 'KieContainer' based upon it. + logger.info("Create new KieContainer start, version = " + ver + " ..."); + + releaseId = kieServices.newReleaseId(groupId, artifactId, ver); + kieContainer = kieServices.newKieContainer(releaseId); + + // clear any exception, and break out of the loop + exception = null; + break; + } catch (RuntimeException e) { + exception = e; + } + } + if (exception != null) { + // all of the 'newKieContainer' invocations failed -- throw the + // most recent exception + throw exception; + } + return releaseId; + } + + /** + * @return the name of the container, which is the String equivalent of the 'ReleaseId'. It has + * the form: + * + * (groupId + ":" + artifactId + ":" + version) + * + * Note that the name changes after a successful call to 'updateToVersion', although + * typically only the 'version' part changes. + */ + public String getName() { + return kieContainer.getReleaseId().toString(); + } + + /** + * @return the associated 'KieContainer' instance + */ + public KieContainer getKieContainer() { + return kieContainer; + } + + /** + * @return the 'ClassLoader' associated with the 'KieContainer' instance + */ + public ClassLoader getClassLoader() { + return kieContainer.getClassLoader(); + } + + /** + * @return the Maven GroupId of the top-level artifact wrapped by the container. + */ + public String getGroupId() { + return kieContainer.getReleaseId().getGroupId(); + } + + /** + * @return the Maven ArtifactId of the top-level artifact wrapped by the container. + */ + public String getArtifactId() { + return kieContainer.getReleaseId().getArtifactId(); + } + + /** + * @return the version of the top-level artifact wrapped by the container (this may change as + * updates occur) + */ + public String getVersion() { + return kieContainer.getReleaseId().getVersion(); + } + + /** + * Fetch the named 'PolicySession'. + * + * @param name the name of the KieSession (which is also the name of the associated + * PolicySession) + * @return a PolicySession if found, 'null' if not + */ + public PolicySession getPolicySession(String name) { + return sessions.get(name); + } + + /** + * Internal method to create a PolicySession, possibly restoring it from persistent storage. + * + * @param name of the KieSession and PolicySession + * @param kieBaseName name of the associated 'KieBase' instance + * @return a new or existing PolicySession, or 'null' if not found + */ + private PolicySession activatePolicySession(String name, String kieBaseName) { + synchronized (sessions) { + logger.info("activatePolicySession:name :" + name); + PolicySession session = sessions.get(name); + if (session == null) { + KieSession kieSession = null; + + // loop through all of the features, and give each one + // a chance to create the 'KieSession' + for (PolicySessionFeatureAPI feature : PolicySessionFeatureAPI.impl.getList()) { + try { + if ((kieSession = feature.activatePolicySession(this, name, kieBaseName)) != null) { + break; + } + } catch (Exception e) { + logger.error(ERROR_STRING + feature.getClass().getName(), e); + } + } + + // if none of the features created the session, create one now + if (kieSession == null) { + kieSession = kieContainer.newKieSession(name); + } + + if (kieSession != null) { + // creation of 'KieSession' was successful - build + // a PolicySession + session = new PolicySession(name, this, kieSession); + sessions.put(name, session); + + // notify features + for (PolicySessionFeatureAPI feature : PolicySessionFeatureAPI.impl.getList()) { + try { + feature.newPolicySession(session); + } catch (Exception e) { + logger.error(ERROR_STRING + feature.getClass().getName(), e); + } + } + logger.info("activatePolicySession:new session was added in sessions with name " + name); + } + } + logger.info("activatePolicySession:session - " + (session == null ? "null" : session.getFullName()) + + " is returned."); + return session; + } + } + + /** + * This creates a 'PolicySession' instance within this 'PolicyContainer', and ties it to the + * specified 'KieSession'. 'name' must not currently exist within the 'PolicyContainer', and the + * 'KieBase' object associated with 'KieSession' must belong to the 'KieContainer'. This method + * provides a way for 'KieSession' instances that are created programmatically to fit into this + * framework. + * + * @param name the name for the new 'PolicySession' + * @param kieSession a 'KieSession' instance, that will be included in this infrastructure + * @return the new 'PolicySession' + * @throws IllegalArgumentException if 'kieSession' does not reside within this container + * @throws IllegalStateException if a 'PolicySession' already exists with this name + */ + public PolicySession adoptKieSession(String name, KieSession kieSession) { + + if (name == null) { + logger.warn("adoptKieSession:input name is null"); + throw new IllegalArgumentException("KieSession input name is null " + getName()); + } else if (kieSession == null) { + logger.warn("adoptKieSession:input kieSession is null"); + throw new IllegalArgumentException("KieSession '" + name + "' is null " + getName()); + } else { + logger.info("adoptKieSession:name: " + name + " kieSession: " + kieSession); + } + // fetch KieBase, and verify it belongs to this KieContainer + boolean match = false; + KieBase kieBase = kieSession.getKieBase(); + logger.info("adoptKieSession:kieBase: " + kieBase); + for (String kieBaseName : kieContainer.getKieBaseNames()) { + logger.info("adoptKieSession:kieBaseName: " + kieBaseName); + if (kieBase == kieContainer.getKieBase(kieBaseName)) { + match = true; + break; + } + } + logger.info("adoptKieSession:match " + match); + // if we don't have a match yet, the last chance is to look at the + // default KieBase, if it exists + if (!match && kieBase != kieContainer.getKieBase()) { + throw new IllegalArgumentException( + "KieSession '" + name + "' does not reside within container " + getName()); + } + + synchronized (sessions) { + if (sessions.get(name) != null) { + throw new IllegalStateException("PolicySession '" + name + "' already exists"); + } + + // create the new 'PolicySession', add it to the table, + // and return the object to the caller + logger.info("adoptKieSession:create a new policySession with name " + name); + PolicySession policySession = new PolicySession(name, this, kieSession); + sessions.put(name, policySession); + + // notify features + for (PolicySessionFeatureAPI feature : PolicySessionFeatureAPI.impl.getList()) { + try { + feature.newPolicySession(policySession); + } catch (Exception e) { + logger.error(ERROR_STRING + feature.getClass().getName(), e); + } + } + return policySession; + } + } + + /** + * This call 'KieContainer.updateToVersion()', and returns the associated response as a String. + * If successful, the name of this 'PolicyContainer' changes to match the new version. + * + * @param newVersion this is the version to update to (the 'groupId' and 'artifactId' remain the + * same) + * @return the list of messages associated with the update (not sure if this can be 'null', or + * how to determine success/failure) + */ + public String updateToVersion(String newVersion) { + ReleaseId releaseId = kieContainer.getReleaseId(); + Results results = this.updateToVersion( + kieServices.newReleaseId(releaseId.getGroupId(), releaseId.getArtifactId(), newVersion)); + + List<Message> messages = results == null ? null : results.getMessages(); + return messages == null ? null : messages.toString(); + } + + /** + * This calls 'KieContainer.updateToVersion()', and returns the associated response. If + * successful, the name of this 'PolicyContainer' changes to match the new version. + * + * @param releaseId the new artifact (usually new version) to be installed + * @return the 'Results' parameter from 'KieContainer.updateToVersion' + */ + public Results updateToVersion(ReleaseId releaseId) { + if (releaseId == null) { + logger.warn("updateToVersion:input releaseId is null"); + } else { + logger.info("updateToVersion:releaseId " + releaseId.toString()); + } + + // stop all session threads + for (PolicySession session : sessions.values()) { + session.stopThread(); + } + + // update the version + Results results = kieContainer.updateToVersion(releaseId); + + // restart all session threads, and notify the sessions + for (PolicySession session : sessions.values()) { + session.startThread(); + session.updated(); + } + + return results; + } + + /** + * @return all existing 'PolicyContainer' instances + */ + public static Collection<PolicyContainer> getPolicyContainers() { + synchronized (containers) { + return new HashSet<>(containers); + } + } + + /** + * @return all of the 'PolicySession' instances + */ + public Collection<PolicySession> getPolicySessions() { + // KLUDGE WARNING: this is a temporary workaround -- if there are + // no features, we don't have persistence, and 'activate' is never + // called. In this case, make sure the container is started. + if (PolicySessionFeatureAPI.impl.getList().isEmpty()) { + start(); + } + + // return current set of PolicySessions + synchronized (sessions) { + return new HashSet<>(sessions.values()); + } + } + + /** + * This method will start a 'KieScanner' (if not currently running), provided that the ReleaseId + * version is 'LATEST' or 'RELEASE', or refers to a SNAPSHOT version. + * + * @param releaseId the release id used to create the container + */ + public synchronized void startScanner(ReleaseId releaseId) { + String version = releaseId.getVersion(); + if (!scannerStarted && scanner == null && version != null + && ("LATEST".equals(version) || "RELEASE".equals(version) || version.endsWith("-SNAPSHOT"))) { + // create the scanner, and poll at 60 second intervals + try { + scannerStarted = true; + + // start this in a separate thread -- it can block for a long time + new Thread("Scanner Starter " + getName()) { + @Override + public void run() { + scanner = kieServices.newKieScanner(kieContainer); + scanner.start(60000L); + } + }.start(); + } catch (Exception e) { + // sometimes the scanner initialization fails for some reason + logger.error("startScanner error", e); + } + } + } + + /** + * Insert a fact into a specific named session + * + * @param name this is the session name + * @param object this is the fact to be inserted into the session + * @return 'true' if the named session was found, 'false' if not + */ + public boolean insert(String name, Object object) { + // TODO: Should the definition of 'name' be expanded to include an + // alternate entry point as well? For example, 'name.entryPoint' (or + // something other than '.' if that is a problem). + synchronized (sessions) { + PolicySession session = sessions.get(name); + if (session != null) { + session.getKieSession().insert(object); + return true; + } + } + return false; + } + + /** + * Insert a fact into all sessions associated with this container + * + * @param object this is the fact to be inserted into the sessions + * @return 'true' if the fact was inserted into at least one session, 'false' if not + */ + public boolean insertAll(Object object) { + boolean rval = false; + synchronized (sessions) { + for (PolicySession session : sessions.values()) { + session.getKieSession().insert(object); + rval = true; + } + } + return rval; + } + + /*************************/ + /* 'Startable' interface */ + /*************************/ + + /** + * {@inheritDoc} + */ + @Override + public synchronized boolean start() { + if (!isStarted) { + // This will create all 'PolicySession' instances specified in the + // 'kmodule.xml' file that don't exist yet + for (String kieBaseName : kieContainer.getKieBaseNames()) { + for (String kieSessionName : kieContainer.getKieSessionNamesInKieBase(kieBaseName)) { + // if the 'PolicySession' does not currently exist, this method + // call will attempt to create it + PolicySession session = activatePolicySession(kieSessionName, kieBaseName); + if (session != null) { + session.startThread(); + } + } + } + isStarted = true; + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized boolean stop() { + if (isStarted) { + Collection<PolicySession> localSessions; + + synchronized (sessions) { + // local set containing all of the sessions + localSessions = new HashSet<>(sessions.values()); + + // clear the 'name->session' map in 'PolicyContainer' + sessions.clear(); + } + for (PolicySession session : localSessions) { + // stop session thread + session.stopThread(); + + // free KieSession resources + session.getKieSession().dispose(); + + // notify features + for (PolicySessionFeatureAPI feature : PolicySessionFeatureAPI.impl.getList()) { + try { + feature.disposeKieSession(session); + } catch (Exception e) { + logger.error(ERROR_STRING + feature.getClass().getName(), e); + } + } + } + isStarted = false; + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public synchronized void shutdown() { + // Note that this method does not call 'destroy' on the 'KieSession' + // instances, which would remove any associated information in persistent + // storage. Should it do this? + + stop(); + synchronized (containers) { + containers.remove(this); + } + + // How do we free the resources associated with the KieContainer? + // Is garbage collection sufficient? + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isAlive() { + return isStarted; + } + + /*************************/ + + /** + * This method is similar to 'shutdown', but it also frees any persistence resources as well. + */ + public synchronized void destroy() { + // we need all KieSession instances running in order to free + // resources associated with persistence + start(); + Collection<PolicySession> localSessions; + + synchronized (sessions) { + // local set containing all of the sessions + localSessions = new HashSet<>(sessions.values()); + + // clear the 'name->session' map in 'PolicyContainer' + sessions.clear(); + } + for (PolicySession session : localSessions) { + // stop session thread + session.stopThread(); + + // free KieSession resources + session.getKieSession().destroy(); + + // notify features + for (PolicySessionFeatureAPI feature : PolicySessionFeatureAPI.impl.getList()) { + try { + feature.destroyKieSession(session); + } catch (Exception e) { + logger.error(ERROR_STRING + feature.getClass().getName(), e); + } + } + } + isStarted = false; + + synchronized (containers) { + containers.remove(this); + } + + // How do we free the resources associated with the KieContainer? + // Is garbage collection sufficient? + } + + /** + * This method is called when the host goes from the 'standby->active' state. + */ + public static void activate() { + // start all of the 'PolicyContainer' instances + for (PolicyContainer container : containers) { + try { + container.start(); + } catch (Exception e) { + logger.error("PolicyContainer.start() error in activate", e); + } + } + } + + /** + * This method is called when the host goes from the 'active->standby' state. + */ + public static void deactivate() { + // deactivate all of the 'PolicyContainer' instances + for (PolicyContainer container : containers) { + try { + container.stop(); + } catch (Exception e) { + logger.error("PolicyContainer.start() error in deactivate", e); + } + } + } + + /** + * This method does the following: + * + * 1) Initializes logging 2) Starts the DroolsPDP Integrity Monitor 3) Initilaizes persistence + * + * It no longer reads in properties files, o creates 'PolicyContainer' instances. + * + * @param args standard 'main' arguments, which are currently ignored + */ + public static void globalInit(String[] args) { + String configDir = "config"; + logger.info("PolicyContainer.main: configDir=" + configDir); + + // invoke 'globalInit' on all of the features + for (PolicySessionFeatureAPI feature : PolicySessionFeatureAPI.impl.getList()) { + try { + feature.globalInit(args, configDir); + } catch (Exception e) { + logger.error(ERROR_STRING + feature.getClass().getName(), e); + } + } + } + + /** + * Fetch the adjunct object associated with a given feature + * + * @param object this is typically the singleton feature object that is used as a key, but it + * might also be useful to use nested objects within the feature as keys. + * @return a feature-specific object associated with the key, or 'null' if it is not found. + */ + public Object getAdjunct(Object object) { + return adjuncts.get(object); + } + + /** + * Store the adjunct object associated with a given feature + * + * @param object this is typically the singleton feature object that is used as a key, but it + * might also be useful to use nested objects within the feature as keys. + * @param value a feature-specific object associated with the key, or 'null' if the + * feature-specific object should be removed + */ + public void setAdjunct(Object object, Object value) { + if (value == null) { + adjuncts.remove(object); + } else { + adjuncts.put(object, value); + } + } } diff --git a/policy-core/src/main/java/org/onap/policy/drools/properties/Lockable.java b/policy-core/src/main/java/org/onap/policy/drools/properties/DroolsProperties.java index ee1e7400..dad9d946 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/properties/Lockable.java +++ b/policy-core/src/main/java/org/onap/policy/drools/properties/DroolsProperties.java @@ -20,26 +20,23 @@ package org.onap.policy.drools.properties; -/** - * Marks a entity as able to lock and unlock. - */ -public interface Lockable { - - /** - * locks this entity - * @return true is the lock operation was successful, false otherwise - */ - public boolean lock(); - - /** - * unlocks this entity - * @return true is the unlock operation was successful, false otherwise - */ - public boolean unlock(); - - /** - * is this entity locked? - * @return true if the entity is in a locked state, false otherwise - */ - public boolean isLocked(); +public interface DroolsProperties { + + /* Controller Properties */ + + public static final String PROPERTY_CONTROLLER_NAME = "controller.name"; + + /* Drools Properties */ + + public static final String RULES_GROUPID = "rules.groupId"; + public static final String RULES_ARTIFACTID = "rules.artifactId"; + public static final String RULES_VERSION = "rules.version"; + + /* Management Server Properties */ + + public static final String ENV_MANAGEMENT_SERVER_PORT = "ENGINE_MANAGEMENT_PORT"; + public static final String ENV_MANAGEMENT_SERVER_HOST = "ENGINE_MANAGEMENT_HOST"; + public static final String ENV_MANAGEMENT_AUTH_USER = "ENGINE_MANAGEMENT_USER"; + public static final String ENV_MANAGEMENT_AUTH_PASSWD = "ENGINE_MANAGEMENT_PASSWORD"; + } diff --git a/policy-core/src/main/java/org/onap/policy/drools/properties/PolicyProperties.java b/policy-core/src/main/java/org/onap/policy/drools/properties/PolicyProperties.java deleted file mode 100644 index 4cb5ef43..00000000 --- a/policy-core/src/main/java/org/onap/policy/drools/properties/PolicyProperties.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-core - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.properties; - -public interface PolicyProperties { - - /* Controller Properties */ - - public static final String PROPERTY_CONTROLLER_NAME = "controller.name"; - - /* Generic property suffixes */ - - public static final String PROPERTY_TOPIC_SERVERS_SUFFIX = ".servers"; - public static final String PROPERTY_TOPIC_API_KEY_SUFFIX = ".apiKey"; - public static final String PROPERTY_TOPIC_API_SECRET_SUFFIX = ".apiSecret"; - public static final String PROPERTY_TOPIC_AAF_MECHID_SUFFIX = ".aafMechId"; - public static final String PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX = ".aafPassword"; - public static final String PROPERTY_TOPIC_EVENTS_SUFFIX =".events"; - public static final String PROPERTY_TOPIC_EVENTS_FILTER_SUFFIX =".filter"; - public static final String PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_GSON_SUFFIX =".events.custom.gson"; - public static final String PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_JACKSON_SUFFIX =".events.custom.jackson"; - - public static final String PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX = ".consumerGroup"; - public static final String PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX = ".consumerInstance"; - public static final String PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX = ".fetchTimeout"; - public static final String PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX = ".fetchLimit"; - public static final String PROPERTY_MANAGED_SUFFIX =".managed"; - - public static final String PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX =".partitionKey"; - - public static final String PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX = ".selfSignedCertificates"; - - /* UEB Properties */ - - public static final String PROPERTY_UEB_SOURCE_TOPICS = "ueb.source.topics"; - public static final String PROPERTY_UEB_SINK_TOPICS = "ueb.sink.topics"; - - /* DMAAP Properties */ - - public static final String PROPERTY_DMAAP_SOURCE_TOPICS = "dmaap.source.topics"; - public static final String PROPERTY_DMAAP_SINK_TOPICS = "dmaap.sink.topics"; - - public static final String PROPERTY_DMAAP_DME2_PARTNER_SUFFIX = ".dme2.partner"; - public static final String PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX = ".dme2.routeOffer"; - public static final String PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX = ".dme2.environment"; - public static final String PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX = ".dme2.aft.environment"; - public static final String PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX = ".dme2.latitude"; - public static final String PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX = ".dme2.longitude"; - - public static final String PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX = ".dme2.epReadTimeoutMs"; - public static final String PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX = ".dme2.epConnTimeout"; - public static final String PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX = ".dme2.roundtripTimeoutMs"; - public static final String PROPERTY_DMAAP_DME2_VERSION_SUFFIX = ".dme2.version"; - public static final String PROPERTY_DMAAP_DME2_SERVICE_NAME_SUFFIX = ".dme2.serviceName"; - public static final String PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX = ".dme2.subContextPath"; - public static final String PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX = ".dme2.sessionStickinessRequired"; - - public static final String PROPERTY_NOOP_SINK_TOPICS = "noop.sink.topics"; - - /* HTTP Server Properties */ - - public static final String PROPERTY_HTTP_SERVER_SERVICES = "http.server.services"; - - public static final String PROPERTY_HTTP_HOST_SUFFIX = ".host"; - public static final String PROPERTY_HTTP_PORT_SUFFIX = ".port"; - public static final String PROPERTY_HTTP_CONTEXT_URIPATH_SUFFIX = ".contextUriPath"; - - public static final String PROPERTY_HTTP_AUTH_USERNAME_SUFFIX = ".userName"; - public static final String PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX = ".password"; - public static final String PROPERTY_HTTP_AUTH_URIPATH_SUFFIX = ".authUriPath"; - - public static final String PROPERTY_HTTP_REST_CLASSES_SUFFIX = ".restClasses"; - public static final String PROPERTY_HTTP_REST_PACKAGES_SUFFIX = ".restPackages"; - public static final String PROPERTY_HTTP_REST_URIPATH_SUFFIX = ".restUriPath"; - - public static final String PROPERTY_HTTP_HTTPS_SUFFIX = ".https"; - public static final String PROPERTY_HTTP_SWAGGER_SUFFIX = ".swagger"; - - /* HTTP Client Properties */ - - public static final String PROPERTY_HTTP_CLIENT_SERVICES = "http.client.services"; - - public static final String PROPERTY_HTTP_URL_SUFFIX = PROPERTY_HTTP_CONTEXT_URIPATH_SUFFIX; - - /* Drools Properties */ - - public static final String RULES_GROUPID = "rules.groupId"; - public static final String RULES_ARTIFACTID = "rules.artifactId"; - public static final String RULES_VERSION = "rules.version"; - - /* Management Server Properties */ - - public static final String ENV_MANAGEMENT_SERVER_PORT = "ENGINE_MANAGEMENT_PORT"; - public static final String ENV_MANAGEMENT_SERVER_HOST = "ENGINE_MANAGEMENT_HOST"; - public static final String ENV_MANAGEMENT_AUTH_USER = "ENGINE_MANAGEMENT_USER"; - public static final String ENV_MANAGEMENT_AUTH_PASSWD = "ENGINE_MANAGEMENT_PASSWORD"; - -} diff --git a/policy-core/src/main/java/org/onap/policy/drools/properties/Startable.java b/policy-core/src/main/java/org/onap/policy/drools/properties/Startable.java deleted file mode 100644 index 6fa2e58b..00000000 --- a/policy-core/src/main/java/org/onap/policy/drools/properties/Startable.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-core - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.properties; - -/** - * Declares the Startable property of any class class implementing - * this interface. This implies that the implementing class supports - * start-like operations. - */ -public interface Startable { - - /** - * Start operation. This operation starts the entity. - * - * @return boolean. true if the start operation was successful, - * otherwise false. - * @throws IllegalStateException. if the element is in a state that - * conflicts with the start operation. - */ - public boolean start(); - - /** - * Stop operation. The entity can be restarted again by invoking - * the start operation. - * - * @return boolean. true if the stop operation was successful, - * otherwise false. - * @throws IllegalStateException. if the element is in a state that - * conflicts with the stop operation. - */ - public boolean stop(); - - /** - * shutdown operation. The terminate operation yields the entity - * unusuable. It cannot be (re)started. - * - * @throws IllegalStateException. if the element is in a state that - * conflicts with the stop operation. - */ - public void shutdown(); - - /** - * is it alive? - * @return boolean. true if alive, otherwise false - */ - public boolean isAlive(); -} diff --git a/policy-endpoints/pom.xml b/policy-endpoints/pom.xml deleted file mode 100644 index 04c284dc..00000000 --- a/policy-endpoints/pom.xml +++ /dev/null @@ -1,175 +0,0 @@ -<!-- - ============LICENSE_START======================================================= - ONAP Policy Engine - Drools PDP - ================================================================================ - Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ============LICENSE_END========================================================= - --> - -<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.drools-pdp</groupId> - <artifactId>drools-pdp</artifactId> - <version>1.3.0-SNAPSHOT</version> - </parent> - - <artifactId>policy-endpoints</artifactId> - - <name>policy-endpoints</name> - <description>Endpoints</description> - - <properties> - </properties> - - <dependencies> - - <dependency> - <groupId>com.att.nsa</groupId> - <artifactId>cambriaClient</artifactId> - <version>${cambria.version}</version> - <exclusions> - <exclusion> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - </exclusion> - </exclusions> - </dependency> - - <dependency> - <groupId>org.onap.dmaap.messagerouter.dmaapclient</groupId> - <artifactId>dmaapClient</artifactId> - <version>${dmaap.version}</version> - <exclusions> - <exclusion> - <groupId>org.slf4j</groupId> - <artifactId>slf4j-log4j12</artifactId> - </exclusion> - <exclusion> - <groupId>log4j</groupId> - <artifactId>log4j</artifactId> - </exclusion> - </exclusions> - </dependency> - - <dependency> - <groupId>org.eclipse.jetty</groupId> - <artifactId>jetty-server</artifactId> - <version>${jetty.version}</version> - </dependency> - - <dependency> - <groupId>org.eclipse.jetty</groupId> - <artifactId>jetty-servlet</artifactId> - <version>${jetty.version}</version> - </dependency> - - <dependency> - <groupId>org.glassfish.jersey.core</groupId> - <artifactId>jersey-server</artifactId> - <version>${jersey.version}</version> - </dependency> - - <dependency> - <groupId>org.glassfish.jersey.containers</groupId> - <artifactId>jersey-container-servlet-core</artifactId> - </dependency> - - <dependency> - <groupId>org.glassfish.jersey.media</groupId> - <artifactId>jersey-media-json-jackson</artifactId> - <version>${jersey.version}</version> - </dependency> - - <dependency> - <groupId>org.glassfish.jersey.containers</groupId> - <artifactId>jersey-container-jetty-http</artifactId> - <version>${jersey.version}</version> - <exclusions> - <exclusion> - <groupId>org.eclipse.jetty</groupId> - <artifactId>jetty-util</artifactId> - </exclusion> - </exclusions> - </dependency> - - <dependency> - <groupId>org.glassfish.jersey.core</groupId> - <artifactId>jersey-client</artifactId> - <version>${jersey.version}</version> - </dependency> - - <dependency> - <groupId>com.fasterxml.jackson.core</groupId> - <artifactId>jackson-databind</artifactId> - <version>${jackson.version}</version> - </dependency> - - <dependency> - <groupId>com.fasterxml.jackson.datatype</groupId> - <artifactId>jackson-datatype-jsr310</artifactId> - <version>${jackson.version}</version> - </dependency> - - <dependency> - <groupId>com.fasterxml.jackson.core</groupId> - <artifactId>jackson-annotations</artifactId> - <version>${jackson.version}</version> - </dependency> - - <dependency> - <groupId>io.swagger</groupId> - <artifactId>swagger-jersey2-jaxrs</artifactId> - </dependency> - - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpcore</artifactId> - </dependency> - - <dependency> - <groupId>org.apache.httpcomponents</groupId> - <artifactId>httpclient</artifactId> - </dependency> - - <dependency> - <groupId>org.apache.commons</groupId> - <artifactId>commons-collections4</artifactId> - <version>4.1</version> - </dependency> - - <dependency> - <groupId>ch.qos.logback</groupId> - <artifactId>logback-classic</artifactId> - </dependency> - - <dependency> - <groupId>org.onap.policy.drools-pdp</groupId> - <artifactId>policy-core</artifactId> - <version>${project.version}</version> - </dependency> - - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> - </dependency> - - </dependencies> - -</project> diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/FilterableTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/FilterableTopicSource.java deleted file mode 100644 index b1e0e1c2..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/FilterableTopicSource.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm; - -/** - * TopicSource that supports server-side filtering. - */ -public interface FilterableTopicSource extends TopicSource { - - /** - * Sets the server-side filter. - * - * @param filter new filter value, or {@code null} - * @throws UnsupportedOperationException if the consumer does not support - * server-side filtering - * @throws IllegalArgumentException if the consumer cannot be built with the - * new filter - */ - public void setFilter(String filter); - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/Topic.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/Topic.java deleted file mode 100644 index 30174f1f..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/Topic.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm; - -import java.util.List; - -import org.onap.policy.drools.properties.Lockable; -import org.onap.policy.drools.properties.Startable; - -/** - * Essential Topic Data - */ -public interface Topic extends TopicRegisterable, Startable, Lockable { - - /** - * network logger - */ - public static final String NETWORK_LOGGER = "network"; - - /** - * Underlying Communication infrastructure Types - */ - public enum CommInfrastructure { - /** - * UEB Communication Infrastructure - */ - UEB, - /** - * DMAAP Communication Infrastructure - */ - DMAAP, - /** - * NOOP for internal use only - */ - NOOP, - /** - * REST Communication Infrastructure - */ - REST - } - - /** - * gets the topic name - * - * @return topic name - */ - public String getTopic(); - - /** - * gets the communication infrastructure type - * @return - */ - public CommInfrastructure getTopicCommInfrastructure(); - - /** - * return list of servers - * @return bus servers - */ - public List<String> getServers(); - - /** - * get the more recent events in this topic entity - * - * @return list of most recent events - */ - public String[] getRecentEvents(); - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicEndpoint.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicEndpoint.java deleted file mode 100644 index 5c04bb8f..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicEndpoint.java +++ /dev/null @@ -1,658 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm; - -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.onap.policy.drools.event.comm.bus.DmaapTopicSink; -import org.onap.policy.drools.event.comm.bus.DmaapTopicSource; -import org.onap.policy.drools.event.comm.bus.NoopTopicSink; -import org.onap.policy.drools.event.comm.bus.UebTopicSink; -import org.onap.policy.drools.event.comm.bus.UebTopicSource; -import org.onap.policy.drools.properties.Lockable; -import org.onap.policy.drools.properties.Startable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -/** - * Abstraction to managed the system's Networked Topic Endpoints, sources of all events input into - * the System. - */ -public interface TopicEndpoint extends Startable, Lockable { - - /** - * singleton for global access - */ - public static final TopicEndpoint manager = new ProxyTopicEndpointManager(); - - /** - * Add Topic Sources to the communication infrastructure initialized per properties - * - * @param properties properties for Topic Source construction - * @return a generic Topic Source - * @throws IllegalArgumentException when invalid arguments are provided - */ - public List<TopicSource> addTopicSources(Properties properties); - - /** - * Add Topic Sinks to the communication infrastructure initialized per properties - * - * @param properties properties for Topic Sink construction - * @return a generic Topic Sink - * @throws IllegalArgumentException when invalid arguments are provided - */ - public List<TopicSink> addTopicSinks(Properties properties); - - /** - * gets all Topic Sources - * - * @return the Topic Source List - */ - List<TopicSource> getTopicSources(); - - /** - * get the Topic Sources for the given topic name - * - * @param topicName the topic name - * - * @return the Topic Source List - * @throws IllegalStateException if the entity is in an invalid state - * @throws IllegalArgumentException if invalid parameters are present - */ - public List<TopicSource> getTopicSources(List<String> topicNames); - - /** - * gets the Topic Source for the given topic name and underlying communication infrastructure type - * - * @param commType communication infrastructure type - * @param topicName the topic name - * - * @return the Topic Source - * @throws IllegalStateException if the entity is in an invalid state, for example multiple - * TopicReaders for a topic name and communication infrastructure - * @throws IllegalArgumentException if invalid parameters are present - * @throws UnsupportedOperationException if the operation is not supported. - */ - public TopicSource getTopicSource(Topic.CommInfrastructure commType, String topicName); - - /** - * get the UEB Topic Source for the given topic name - * - * @param topicName the topic name - * - * @return the UEB Topic Source - * @throws IllegalStateException if the entity is in an invalid state, for example multiple - * TopicReaders for a topic name and communication infrastructure - * @throws IllegalArgumentException if invalid parameters are present - */ - public UebTopicSource getUebTopicSource(String topicName); - - /** - * get the DMAAP Topic Source for the given topic name - * - * @param topicName the topic name - * - * @return the DMAAP Topic Source - * @throws IllegalStateException if the entity is in an invalid state, for example multiple - * TopicReaders for a topic name and communication infrastructure - * @throws IllegalArgumentException if invalid parameters are present - */ - public DmaapTopicSource getDmaapTopicSource(String topicName); - - /** - * get the Topic Sinks for the given topic name - * - * @param topicNames the topic names - * @return the Topic Sink List - * @throws IllegalStateException - * @throws IllegalArgumentException - */ - public List<TopicSink> getTopicSinks(List<String> topicNames); - - /** - * get the Topic Sinks for the given topic name and underlying communication infrastructure type - * - * @param topicName the topic name - * @param commType communication infrastructure type - * - * @return the Topic Sink List - * @throws IllegalStateException if the entity is in an invalid state, for example multiple - * TopicWriters for a topic name and communication infrastructure - * @throws IllegalArgumentException if invalid parameters are present - */ - public TopicSink getTopicSink(Topic.CommInfrastructure commType, String topicName); - - /** - * get the Topic Sinks for the given topic name and all the underlying communication - * infrastructure type - * - * @param topicName the topic name - * @param commType communication infrastructure type - * - * @return the Topic Sink List - * @throws IllegalStateException if the entity is in an invalid state, for example multiple - * TopicWriters for a topic name and communication infrastructure - * @throws IllegalArgumentException if invalid parameters are present - */ - public List<TopicSink> getTopicSinks(String topicName); - - /** - * get the UEB Topic Source for the given topic name - * - * @param topicName the topic name - * - * @return the Topic Source - * @throws IllegalStateException if the entity is in an invalid state, for example multiple - * TopicReaders for a topic name and communication infrastructure - * @throws IllegalArgumentException if invalid parameters are present - */ - public UebTopicSink getUebTopicSink(String topicName); - - /** - * get the no-op Topic Sink for the given topic name - * - * @param topicName the topic name - * - * @return the Topic Source - * @throws IllegalStateException if the entity is in an invalid state, for example multiple - * TopicReaders for a topic name and communication infrastructure - * @throws IllegalArgumentException if invalid parameters are present - */ - public NoopTopicSink getNoopTopicSink(String topicName); - - /** - * get the DMAAP Topic Source for the given topic name - * - * @param topicName the topic name - * - * @return the Topic Source - * @throws IllegalStateException if the entity is in an invalid state, for example multiple - * TopicReaders for a topic name and communication infrastructure - * @throws IllegalArgumentException if invalid parameters are present - */ - public DmaapTopicSink getDmaapTopicSink(String topicName); - - /** - * gets only the UEB Topic Sources - * - * @return the UEB Topic Source List - */ - public List<UebTopicSource> getUebTopicSources(); - - /** - * gets only the DMAAP Topic Sources - * - * @return the DMAAP Topic Source List - */ - public List<DmaapTopicSource> getDmaapTopicSources(); - - /** - * gets all Topic Sinks - * - * @return the Topic Sink List - */ - public List<TopicSink> getTopicSinks(); - - /** - * gets only the UEB Topic Sinks - * - * @return the UEB Topic Sink List - */ - public List<UebTopicSink> getUebTopicSinks(); - - /** - * gets only the DMAAP Topic Sinks - * - * @return the DMAAP Topic Sink List - */ - public List<DmaapTopicSink> getDmaapTopicSinks(); - - /** - * gets only the NOOP Topic Sinks - * - * @return the NOOP Topic Sinks List - */ - public List<NoopTopicSink> getNoopTopicSinks(); -} - - -/* - * ----------------- implementation ------------------- - */ - -/** - * This implementation of the Topic Endpoint Manager, proxies operations to appropriate - * implementations according to the communication infrastructure that are supported - */ -class ProxyTopicEndpointManager implements TopicEndpoint { - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(ProxyTopicEndpointManager.class); - /** - * Is this element locked? - */ - protected volatile boolean locked = false; - - /** - * Is this element alive? - */ - protected volatile boolean alive = false; - - @Override - public List<TopicSource> addTopicSources(Properties properties) { - - // 1. Create UEB Sources - // 2. Create DMAAP Sources - - final List<TopicSource> sources = new ArrayList<>(); - - sources.addAll(UebTopicSource.factory.build(properties)); - sources.addAll(DmaapTopicSource.factory.build(properties)); - - if (this.isLocked()) { - for (final TopicSource source : sources) { - source.lock(); - } - } - - return sources; - } - - @Override - public List<TopicSink> addTopicSinks(Properties properties) { - // 1. Create UEB Sinks - // 2. Create DMAAP Sinks - - final List<TopicSink> sinks = new ArrayList<>(); - - sinks.addAll(UebTopicSink.factory.build(properties)); - sinks.addAll(DmaapTopicSink.factory.build(properties)); - sinks.addAll(NoopTopicSink.factory.build(properties)); - - if (this.isLocked()) { - for (final TopicSink sink : sinks) { - sink.lock(); - } - } - - return sinks; - } - - @Override - public List<TopicSource> getTopicSources() { - - final List<TopicSource> sources = new ArrayList<>(); - - sources.addAll(UebTopicSource.factory.inventory()); - sources.addAll(DmaapTopicSource.factory.inventory()); - - return sources; - } - - @Override - public List<TopicSink> getTopicSinks() { - - final List<TopicSink> sinks = new ArrayList<>(); - - sinks.addAll(UebTopicSink.factory.inventory()); - sinks.addAll(DmaapTopicSink.factory.inventory()); - sinks.addAll(NoopTopicSink.factory.inventory()); - - return sinks; - } - - @JsonIgnore - @Override - public List<UebTopicSource> getUebTopicSources() { - return UebTopicSource.factory.inventory(); - } - - @JsonIgnore - @Override - public List<DmaapTopicSource> getDmaapTopicSources() { - return DmaapTopicSource.factory.inventory(); - } - - @JsonIgnore - @Override - public List<UebTopicSink> getUebTopicSinks() { - return UebTopicSink.factory.inventory(); - } - - @JsonIgnore - @Override - public List<DmaapTopicSink> getDmaapTopicSinks() { - return DmaapTopicSink.factory.inventory(); - } - - @JsonIgnore - @Override - public List<NoopTopicSink> getNoopTopicSinks() { - return NoopTopicSink.factory.inventory(); - } - - @Override - public boolean start() { - - synchronized (this) { - if (this.locked) { - throw new IllegalStateException(this + " is locked"); - } - - if (this.alive) { - return true; - } - - this.alive = true; - } - - final List<Startable> endpoints = this.getEndpoints(); - - boolean success = true; - for (final Startable endpoint : endpoints) { - try { - success = endpoint.start() && success; - } catch (final Exception e) { - success = false; - logger.error("Problem starting endpoint: {}", endpoint, e); - } - } - - return success; - } - - - @Override - public boolean stop() { - - /* - * stop regardless if it is locked, in other words, stop operation has precedence over locks. - */ - synchronized (this) { - this.alive = false; - } - - final List<Startable> endpoints = this.getEndpoints(); - - boolean success = true; - for (final Startable endpoint : endpoints) { - try { - success = endpoint.stop() && success; - } catch (final Exception e) { - success = false; - logger.error("Problem stopping endpoint: {}", endpoint, e); - } - } - - return success; - } - - /** - * - * @return list of managed endpoints - */ - @JsonIgnore - protected List<Startable> getEndpoints() { - final List<Startable> endpoints = new ArrayList<>(); - - endpoints.addAll(this.getTopicSources()); - endpoints.addAll(this.getTopicSinks()); - - return endpoints; - } - - @Override - public void shutdown() { - UebTopicSource.factory.destroy(); - UebTopicSink.factory.destroy(); - NoopTopicSink.factory.destroy(); - - DmaapTopicSource.factory.destroy(); - DmaapTopicSink.factory.destroy(); - } - - @Override - public boolean isAlive() { - return this.alive; - } - - @Override - public boolean lock() { - - synchronized (this) { - if (this.locked) - return true; - - this.locked = true; - } - - for (final TopicSource source : this.getTopicSources()) { - source.lock(); - } - - for (final TopicSink sink : this.getTopicSinks()) { - sink.lock(); - } - - return true; - } - - @Override - public boolean unlock() { - synchronized (this) { - if (!this.locked) - return true; - - this.locked = false; - } - - for (final TopicSource source : this.getTopicSources()) { - source.unlock(); - } - - for (final TopicSink sink : this.getTopicSinks()) { - sink.unlock(); - } - - return true; - } - - @Override - public boolean isLocked() { - return this.locked; - } - - @Override - public List<TopicSource> getTopicSources(List<String> topicNames) { - - if (topicNames == null) { - throw new IllegalArgumentException("must provide a list of topics"); - } - - final List<TopicSource> sources = new ArrayList<>(); - for (final String topic : topicNames) { - try { - final TopicSource uebSource = this.getUebTopicSource(topic); - if (uebSource != null) - sources.add(uebSource); - } catch (final Exception e) { - logger.debug("No UEB source for topic: {}", topic, e); - } - - try { - final TopicSource dmaapSource = this.getDmaapTopicSource(topic); - if (dmaapSource != null) - sources.add(dmaapSource); - } catch (final Exception e) { - logger.debug("No DMAAP source for topic: {}", topic, e); - } - } - return sources; - } - - @Override - public List<TopicSink> getTopicSinks(List<String> topicNames) { - - if (topicNames == null) { - throw new IllegalArgumentException("must provide a list of topics"); - } - - final List<TopicSink> sinks = new ArrayList<>(); - for (final String topic : topicNames) { - try { - final TopicSink uebSink = this.getUebTopicSink(topic); - if (uebSink != null) - sinks.add(uebSink); - } catch (final Exception e) { - logger.debug("No UEB sink for topic: {}", topic, e); - } - - try { - final TopicSink dmaapSink = this.getDmaapTopicSink(topic); - if (dmaapSink != null) - sinks.add(dmaapSink); - } catch (final Exception e) { - logger.debug("No DMAAP sink for topic: {}", topic, e); - } - - try { - final TopicSink noopSink = this.getNoopTopicSink(topic); - if (noopSink != null) - sinks.add(noopSink); - } catch (final Exception e) { - logger.debug("No NOOP sink for topic: {}", topic, e); - } - } - return sinks; - } - - @Override - public TopicSource getTopicSource(Topic.CommInfrastructure commType, String topicName) { - - if (commType == null) { - throw parmException(topicName); - } - - if (topicName == null) { - throw parmException(topicName); - } - - switch (commType) { - case UEB: - return this.getUebTopicSource(topicName); - case DMAAP: - return this.getDmaapTopicSource(topicName); - default: - throw new UnsupportedOperationException("Unsupported " + commType.name()); - } - } - - private IllegalArgumentException parmException(String topicName) { - return new IllegalArgumentException( - "Invalid parameter: a communication infrastructure required to fetch " + topicName); - } - - @Override - public TopicSink getTopicSink(Topic.CommInfrastructure commType, String topicName) { - if (commType == null) { - throw parmException(topicName); - } - - if (topicName == null) { - throw parmException(topicName); - } - - switch (commType) { - case UEB: - return this.getUebTopicSink(topicName); - case DMAAP: - return this.getDmaapTopicSink(topicName); - case NOOP: - return this.getNoopTopicSink(topicName); - default: - throw new UnsupportedOperationException("Unsupported " + commType.name()); - } - } - - @Override - public List<TopicSink> getTopicSinks(String topicName) { - if (topicName == null) { - throw parmException(topicName); - } - - final List<TopicSink> sinks = new ArrayList<>(); - - try { - sinks.add(this.getUebTopicSink(topicName)); - } catch (final Exception e) { - logNoSink(topicName, e); - } - - try { - sinks.add(this.getDmaapTopicSink(topicName)); - } catch (final Exception e) { - logNoSink(topicName, e); - } - - try { - sinks.add(this.getNoopTopicSink(topicName)); - } catch (final Exception e) { - logNoSink(topicName, e); - } - - return sinks; - } - -private void logNoSink(String topicName, Exception ex) { - logger.debug("No sink for topic: {}", topicName, ex); -} - - @Override - public UebTopicSource getUebTopicSource(String topicName) { - return UebTopicSource.factory.get(topicName); - } - - @Override - public UebTopicSink getUebTopicSink(String topicName) { - return UebTopicSink.factory.get(topicName); - } - - @Override - public DmaapTopicSource getDmaapTopicSource(String topicName) { - return DmaapTopicSource.factory.get(topicName); - } - - @Override - public DmaapTopicSink getDmaapTopicSink(String topicName) { - return DmaapTopicSink.factory.get(topicName); - } - - @Override - public NoopTopicSink getNoopTopicSink(String topicName) { - return NoopTopicSink.factory.get(topicName); - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicListener.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicListener.java deleted file mode 100644 index 4c8552b6..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicListener.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm; - -/** - * Listener for event messages entering the Policy Engine - */ -@FunctionalInterface -public interface TopicListener { - - /** - * Notification of a new Event over a given Topic - * - * @param commType communication infrastructure type - * @param topic topic name - * @param event event message as a string - */ - public void onTopicEvent(Topic.CommInfrastructure commType, String topic, String event); - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicRegisterable.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicRegisterable.java deleted file mode 100644 index 540025e5..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicRegisterable.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm; - -/** - * Marks a Topic entity as registerable - */ -public interface TopicRegisterable { - - /** - * Register for notification of events with this Topic Entity - * - * @param topicListener the listener of events - */ - public void register(TopicListener topicListener); - - /** - * Unregisters for notification of events with this Topic Entity - * - * @param topicListener the listener of events - */ - public void unregister(TopicListener topicListener); - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicSink.java deleted file mode 100644 index 5ea849ee..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicSink.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm; - -/** - * Marks a given Topic Endpoint as able to send messages over a topic - */ -public interface TopicSink extends Topic { - - /** - * Sends a string message over this Topic Endpoint - * - * @param message message to send - * - * @return true if the send operation succeeded, false otherwise - * @throws IllegalArgumentException an invalid message has been provided - * @throws IllegalStateException the entity is in an state that prevents - * it from sending messages, for example, locked or stopped. - */ - public boolean send(String message); - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicSource.java deleted file mode 100644 index 17cde607..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/TopicSource.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm; - -/** - * Marker for a Topic Entity, indicating that the entity is able to read - * over a topic - */ -public interface TopicSource extends Topic { - - /** - * pushes an event into the source programatically - * - * @param event the event in json format - * @return true if it can be processed correctly, false otherwise - */ - public boolean offer(String event); - -}
\ No newline at end of file diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/ApiKeyEnabled.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/ApiKeyEnabled.java deleted file mode 100644 index 9ddf4fff..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/ApiKeyEnabled.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -/** - * API - */ -public interface ApiKeyEnabled { - /** - * @return api key - */ - public String getApiKey(); - - /** - * @return api secret - */ - public String getApiSecret(); -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/BusTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/BusTopicSink.java deleted file mode 100644 index 99a600b0..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/BusTopicSink.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -import org.onap.policy.drools.event.comm.TopicSink; - -/** - * Topic Sink over Bus Infrastructure (DMAAP/UEB) - */ -public interface BusTopicSink extends ApiKeyEnabled, TopicSink { - /** - * Log Failures after X number of retries - */ - public static final int DEFAULT_LOG_SEND_FAILURES_AFTER = 1; - - /** - * Sets the UEB partition key for published messages - * - * @param partitionKey the partition key - */ - public void setPartitionKey(String partitionKey); - - /** - * return the partition key in used by the system to publish messages - * - * @return the partition key - */ - public String getPartitionKey(); -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/BusTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/BusTopicSource.java deleted file mode 100644 index 83d4e72c..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/BusTopicSource.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -import org.onap.policy.drools.event.comm.TopicSource; - -/** - * Generic Topic Source for UEB/DMAAP Communication Infrastructure - * - */ -public interface BusTopicSource extends ApiKeyEnabled, TopicSource { - - /** - * Default Timeout fetching in milliseconds - */ - public static int DEFAULT_TIMEOUT_MS_FETCH = 15000; - - /** - * Default maximum number of messages fetch at the time - */ - public static int DEFAULT_LIMIT_FETCH = 100; - - /** - * Definition of No Timeout fetching - */ - public static int NO_TIMEOUT_MS_FETCH = -1; - - /** - * Definition of No limit fetching - */ - public static int NO_LIMIT_FETCH = -1; - - /** - * gets the consumer group - * - * @return consumer group - */ - public String getConsumerGroup(); - - /** - * gets the consumer instance - * - * @return consumer instance - */ - public String getConsumerInstance(); - - /** - * gets the fetch timeout - * - * @return fetch timeout - */ - public int getFetchTimeout(); - - /** - * gets the fetch limit - * - * @return fetch limit - */ - public int getFetchLimit(); -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSink.java deleted file mode 100644 index 982fcafa..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSink.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -public interface DmaapTopicSink extends BusTopicSink { - - /** - * Factory of UebTopicWriter for instantiation and management purposes - */ - - public static final DmaapTopicSinkFactory factory = new IndexedDmaapTopicSinkFactory(); -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSinkFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSinkFactory.java deleted file mode 100644 index 5ff5084e..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSinkFactory.java +++ /dev/null @@ -1,465 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; -import org.onap.policy.drools.event.comm.bus.internal.InlineDmaapTopicSink; -import org.onap.policy.drools.properties.PolicyProperties; - -/** - * DMAAP Topic Sink Factory - */ -public interface DmaapTopicSinkFactory { - public final String DME2_READ_TIMEOUT_PROPERTY = "AFT_DME2_EP_READ_TIMEOUT_MS"; - public final String DME2_EP_CONN_TIMEOUT_PROPERTY = "AFT_DME2_EP_CONN_TIMEOUT"; - public final String DME2_ROUNDTRIP_TIMEOUT_PROPERTY = "AFT_DME2_ROUNDTRIP_TIMEOUT_MS"; - public final String DME2_VERSION_PROPERTY = "Version"; - public final String DME2_ROUTE_OFFER_PROPERTY = "routeOffer"; - public final String DME2_SERVICE_NAME_PROPERTY = "ServiceName"; - public final String DME2_SUBCONTEXT_PATH_PROPERTY = "SubContextPath"; - public final String DME2_SESSION_STICKINESS_REQUIRED_PROPERTY = "sessionstickinessrequired"; - - /** - * Instantiates a new DMAAP Topic Sink - * - * @param servers list of servers - * @param topic topic name - * @param apiKey API Key - * @param apiSecret API Secret - * @param userName AAF user name - * @param password AAF password - * @param partitionKey Consumer Group - * @param environment DME2 environment - * @param aftEnvironment DME2 AFT environment - * @param partner DME2 Partner - * @param latitude DME2 latitude - * @param longitude DME2 longitude - * @param additionalProps additional properties to pass to DME2 - * @param managed is this sink endpoint managed? - * - * @return an DMAAP Topic Sink - * @throws IllegalArgumentException if invalid parameters are present - */ - public DmaapTopicSink build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String userName, - String password, - String partitionKey, - String environment, - String aftEnvironment, - String partner, - String latitude, - String longitude, - Map<String,String> additionalProps, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts) ; - - /** - * Instantiates a new DMAAP Topic Sink - * - * @param servers list of servers - * @param topic topic name - * @param apiKey API Key - * @param apiSecret API Secret - * @param userName AAF user name - * @param password AAF password - * @param partitionKey Consumer Group - * @param managed is this sink endpoint managed? - * - * @return an DMAAP Topic Sink - * @throws IllegalArgumentException if invalid parameters are present - */ - public DmaapTopicSink build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String userName, - String password, - String partitionKey, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts); - - /** - * Creates an DMAAP Topic Sink based on properties files - * - * @param properties Properties containing initialization values - * - * @return an DMAAP Topic Sink - * @throws IllegalArgumentException if invalid parameters are present - */ - public List<DmaapTopicSink> build(Properties properties); - - /** - * Instantiates a new DMAAP Topic Sink - * - * @param servers list of servers - * @param topic topic name - * - * @return an DMAAP Topic Sink - * @throws IllegalArgumentException if invalid parameters are present - */ - public DmaapTopicSink build(List<String> servers, String topic); - - /** - * Destroys an DMAAP Topic Sink based on a topic - * - * @param topic topic name - * @throws IllegalArgumentException if invalid parameters are present - */ - public void destroy(String topic); - - /** - * gets an DMAAP Topic Sink based on topic name - * @param topic the topic name - * - * @return an DMAAP Topic Sink with topic name - * @throws IllegalArgumentException if an invalid topic is provided - * @throws IllegalStateException if the DMAAP Topic Reader is - * an incorrect state - */ - public DmaapTopicSink get(String topic); - - /** - * Provides a snapshot of the DMAAP Topic Sinks - * @return a list of the DMAAP Topic Sinks - */ - public List<DmaapTopicSink> inventory(); - - /** - * Destroys all DMAAP Topic Sinks - */ - public void destroy(); -} - -/* ------------- implementation ----------------- */ - -/** - * Factory of DMAAP Reader Topics indexed by topic name - */ -class IndexedDmaapTopicSinkFactory implements DmaapTopicSinkFactory { - private static final String MISSING_TOPIC = "A topic must be provided"; - - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(IndexedDmaapTopicSinkFactory.class); - - /** - * DMAAP Topic Name Index - */ - protected HashMap<String, DmaapTopicSink> dmaapTopicWriters = new HashMap<>(); - - @Override - public DmaapTopicSink build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String userName, - String password, - String partitionKey, - String environment, - String aftEnvironment, - String partner, - String latitude, - String longitude, - Map<String,String> additionalProps, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized (this) { - if (dmaapTopicWriters.containsKey(topic)) { - return dmaapTopicWriters.get(topic); - } - - DmaapTopicSink dmaapTopicSink = - new InlineDmaapTopicSink(servers, topic, - apiKey, apiSecret, - userName, password, - partitionKey, - environment, aftEnvironment, - partner, latitude, longitude, additionalProps, useHttps, allowSelfSignedCerts); - - if (managed) - dmaapTopicWriters.put(topic, dmaapTopicSink); - return dmaapTopicSink; - } - } - - @Override - public DmaapTopicSink build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String userName, - String password, - String partitionKey, - boolean managed, - boolean useHttps, boolean allowSelfSignedCerts) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized (this) { - if (dmaapTopicWriters.containsKey(topic)) { - return dmaapTopicWriters.get(topic); - } - - DmaapTopicSink dmaapTopicSink = - new InlineDmaapTopicSink(servers, topic, - apiKey, apiSecret, - userName, password, - partitionKey, useHttps, allowSelfSignedCerts); - - if (managed) - dmaapTopicWriters.put(topic, dmaapTopicSink); - return dmaapTopicSink; - } - } - - @Override - public DmaapTopicSink build(List<String> servers, String topic) { - return this.build(servers, topic, null, null, null, null, null, true, false, false); - } - - @Override - public List<DmaapTopicSink> build(Properties properties) { - - String writeTopics = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS); - if (writeTopics == null || writeTopics.isEmpty()) { - logger.info("{}: no topic for DMaaP Sink", this); - return new ArrayList<>(); - } - - List<String> writeTopicList = new ArrayList<>(Arrays.asList(writeTopics.split("\\s*,\\s*"))); - List<DmaapTopicSink> newDmaapTopicSinks = new ArrayList<>(); - synchronized(this) { - for (String topic: writeTopicList) { - if (this.dmaapTopicWriters.containsKey(topic)) { - newDmaapTopicSinks.add(this.dmaapTopicWriters.get(topic)); - continue; - } - String servers = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + - topic + - PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX); - - List<String> serverList; - if (servers != null && !servers.isEmpty()) - serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*"))); - else serverList = new ArrayList<>(); - - String apiKey = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_API_KEY_SUFFIX); - String apiSecret = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_API_SECRET_SUFFIX); - - String aafMechId = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX); - String aafPassword = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX); - - String partitionKey = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX); - - String managedString = properties.getProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic + - PolicyProperties.PROPERTY_MANAGED_SUFFIX); - - /* DME2 Properties */ - - String dme2Environment = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX); - - String dme2AftEnvironment = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX); - - String dme2Partner = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX); - - String dme2RouteOffer = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX); - - String dme2Latitude = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX); - - String dme2Longitude = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX); - - String dme2EpReadTimeoutMs = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX); - - String dme2EpConnTimeout = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX); - - String dme2RoundtripTimeoutMs = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS - + "." + topic + PolicyProperties.PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX); - - String dme2Version = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_VERSION_SUFFIX); - - String dme2SubContextPath = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX); - - String dme2SessionStickinessRequired = properties - .getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX); - - Map<String,String> dme2AdditionalProps = new HashMap<>(); - - if (dme2EpReadTimeoutMs != null && !dme2EpReadTimeoutMs.isEmpty()) - dme2AdditionalProps.put(DME2_READ_TIMEOUT_PROPERTY, dme2EpReadTimeoutMs); - if (dme2EpConnTimeout != null && !dme2EpConnTimeout.isEmpty()) - dme2AdditionalProps.put(DME2_EP_CONN_TIMEOUT_PROPERTY, dme2EpConnTimeout); - if (dme2RoundtripTimeoutMs != null && !dme2RoundtripTimeoutMs.isEmpty()) - dme2AdditionalProps.put(DME2_ROUNDTRIP_TIMEOUT_PROPERTY, dme2RoundtripTimeoutMs); - if (dme2Version != null && !dme2Version.isEmpty()) - dme2AdditionalProps.put(DME2_VERSION_PROPERTY, dme2Version); - if (dme2RouteOffer != null && !dme2RouteOffer.isEmpty()) - dme2AdditionalProps.put(DME2_ROUTE_OFFER_PROPERTY, dme2RouteOffer); - if (dme2SubContextPath != null && !dme2SubContextPath.isEmpty()) - dme2AdditionalProps.put(DME2_SUBCONTEXT_PATH_PROPERTY, dme2SubContextPath); - if (dme2SessionStickinessRequired != null && !dme2SessionStickinessRequired.isEmpty()) - dme2AdditionalProps.put(DME2_SESSION_STICKINESS_REQUIRED_PROPERTY, dme2SessionStickinessRequired); - - if (servers == null || servers.isEmpty()) { - logger.error("{}: no DMaaP servers or DME2 ServiceName provided", this); - continue; - } - - boolean managed = true; - if (managedString != null && !managedString.isEmpty()) { - managed = Boolean.parseBoolean(managedString); - } - - String useHttpsString = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic + - PolicyProperties.PROPERTY_HTTP_HTTPS_SUFFIX); - - //default is to use HTTP if no https property exists - boolean useHttps = false; - if (useHttpsString != null && !useHttpsString.isEmpty()){ - useHttps = Boolean.parseBoolean(useHttpsString); - } - - - String allowSelfSignedCertsString = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic + - PolicyProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX); - - //default is to disallow self-signed certs - boolean allowSelfSignedCerts = false; - if (allowSelfSignedCertsString != null && !allowSelfSignedCertsString.isEmpty()){ - allowSelfSignedCerts = Boolean.parseBoolean(allowSelfSignedCertsString); - } - - DmaapTopicSink dmaapTopicSink = this.build(serverList, topic, - apiKey, apiSecret, - aafMechId, aafPassword, - partitionKey, - dme2Environment, dme2AftEnvironment, - dme2Partner, dme2Latitude, dme2Longitude, - dme2AdditionalProps, managed, useHttps, allowSelfSignedCerts); - - newDmaapTopicSinks.add(dmaapTopicSink); - } - return newDmaapTopicSinks; - } - } - - @Override - public void destroy(String topic) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - DmaapTopicSink dmaapTopicWriter; - synchronized(this) { - if (!dmaapTopicWriters.containsKey(topic)) { - return; - } - - dmaapTopicWriter = dmaapTopicWriters.remove(topic); - } - - dmaapTopicWriter.shutdown(); - } - - @Override - public void destroy() { - List<DmaapTopicSink> writers = this.inventory(); - for (DmaapTopicSink writer: writers) { - writer.shutdown(); - } - - synchronized(this) { - this.dmaapTopicWriters.clear(); - } - } - - @Override - public DmaapTopicSink get(String topic) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized(this) { - if (dmaapTopicWriters.containsKey(topic)) { - return dmaapTopicWriters.get(topic); - } else { - throw new IllegalStateException("DmaapTopicSink for " + topic + " not found"); - } - } - } - - @Override - public synchronized List<DmaapTopicSink> inventory() { - return new ArrayList<>(this.dmaapTopicWriters.values()); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("IndexedDmaapTopicSinkFactory []"); - return builder.toString(); - } - -}
\ No newline at end of file diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSource.java deleted file mode 100644 index 8d9329fa..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSource.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -public interface DmaapTopicSource extends BusTopicSource { - - /** - * factory for managing and tracking DMAAP sources - */ - public static DmaapTopicSourceFactory factory = new IndexedDmaapTopicSourceFactory(); -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSourceFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSourceFactory.java deleted file mode 100644 index 5a8e2a72..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/DmaapTopicSourceFactory.java +++ /dev/null @@ -1,587 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.onap.policy.drools.event.comm.bus.internal.SingleThreadedDmaapTopicSource; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; -import org.onap.policy.drools.properties.PolicyProperties; - -/** - * DMAAP Topic Source Factory - */ -public interface DmaapTopicSourceFactory { - public final String DME2_READ_TIMEOUT_PROPERTY = "AFT_DME2_EP_READ_TIMEOUT_MS"; - public final String DME2_EP_CONN_TIMEOUT_PROPERTY = "AFT_DME2_EP_CONN_TIMEOUT"; - public final String DME2_ROUNDTRIP_TIMEOUT_PROPERTY = "AFT_DME2_ROUNDTRIP_TIMEOUT_MS"; - public final String DME2_VERSION_PROPERTY = "Version"; - public final String DME2_ROUTE_OFFER_PROPERTY = "routeOffer"; - public final String DME2_SERVICE_NAME_PROPERTY = "ServiceName"; - public final String DME2_SUBCONTEXT_PATH_PROPERTY = "SubContextPath"; - public final String DME2_SESSION_STICKINESS_REQUIRED_PROPERTY = "sessionstickinessrequired"; - - /** - * Creates an DMAAP Topic Source based on properties files - * - * @param properties Properties containing initialization values - * - * @return an DMAAP Topic Source - * @throws IllegalArgumentException if invalid parameters are present - */ - public List<DmaapTopicSource> build(Properties properties); - - /** - * Instantiates a new DMAAP Topic Source - * - * @param servers list of servers - * @param topic topic name - * @param apiKey API Key - * @param apiSecret API Secret - * @param userName user name - * @param password password - * @param consumerGroup Consumer Group - * @param consumerInstance Consumer Instance - * @param fetchTimeout Read Fetch Timeout - * @param fetchLimit Fetch Limit - * @param managed is this endpoind managed? - * @param useHttps does the connection use HTTPS? - * @param allowSelfSignedCerts does connection allow self-signed certificates? - * - * @return an DMAAP Topic Source - * @throws IllegalArgumentException if invalid parameters are present - */ - public DmaapTopicSource build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String userName, - String password, - String consumerGroup, - String consumerInstance, - int fetchTimeout, - int fetchLimit, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts); - - /** - * Instantiates a new DMAAP Topic Source - * - * @param servers list of servers - * @param topic topic name - * @param apiKey API Key - * @param apiSecret API Secret - * @param userName user name - * @param password password - * @param consumerGroup Consumer Group - * @param consumerInstance Consumer Instance - * @param fetchTimeout Read Fetch Timeout - * @param fetchLimit Fetch Limit - * @param environment DME2 environment - * @param aftEnvironment DME2 AFT environment - * @param partner DME2 Partner - * @param latitude DME2 latitude - * @param longitude DME2 longitude - * @param additionalProps additional properties to pass to DME2 - * @param managed is this endpoind managed? - * @param useHttps does the connection use HTTPS? - * @param allowSelfSignedCerts does connection allow self-signed certificates? - * - * @return an DMAAP Topic Source - * @throws IllegalArgumentException if invalid parameters are present - */ - public DmaapTopicSource build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String userName, - String password, - String consumerGroup, - String consumerInstance, - int fetchTimeout, - int fetchLimit, - String environment, - String aftEnvironment, - String partner, - String latitude, - String longitude, - Map<String,String> additionalProps, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts); - - /** - * Instantiates a new DMAAP Topic Source - * - * @param servers list of servers - * @param topic topic name - * @param apiKey API Key - * @param apiSecret API Secret - * - * @return an DMAAP Topic Source - * @throws IllegalArgumentException if invalid parameters are present - */ - public DmaapTopicSource build(List<String> servers, - String topic, - String apiKey, - String apiSecret); - - /** - * Instantiates a new DMAAP Topic Source - * - * @param servers list of servers - * @param topic topic name - * - * @return an DMAAP Topic Source - * @throws IllegalArgumentException if invalid parameters are present - */ - public DmaapTopicSource build(List<String> servers, - String topic); - - /** - * Destroys an DMAAP Topic Source based on a topic - * - * @param topic topic name - * @throws IllegalArgumentException if invalid parameters are present - */ - public void destroy(String topic); - - /** - * Destroys all DMAAP Topic Sources - */ - public void destroy(); - - /** - * gets an DMAAP Topic Source based on topic name - * @param topic the topic name - * @return an DMAAP Topic Source with topic name - * @throws IllegalArgumentException if an invalid topic is provided - * @throws IllegalStateException if the DMAAP Topic Source is - * an incorrect state - */ - public DmaapTopicSource get(String topic); - - /** - * Provides a snapshot of the DMAAP Topic Sources - * @return a list of the DMAAP Topic Sources - */ - public List<DmaapTopicSource> inventory(); -} - - -/* ------------- implementation ----------------- */ - -/** - * Factory of DMAAP Source Topics indexed by topic name - */ - -class IndexedDmaapTopicSourceFactory implements DmaapTopicSourceFactory { - private static final String MISSING_TOPIC = "A topic must be provided"; - - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(IndexedDmaapTopicSourceFactory.class); - - /** - * DMaaP Topic Name Index - */ - protected HashMap<String, DmaapTopicSource> dmaapTopicSources = - new HashMap<>(); - - /** - * {@inheritDoc} - */ - @Override - public DmaapTopicSource build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String userName, - String password, - String consumerGroup, - String consumerInstance, - int fetchTimeout, - int fetchLimit, - String environment, - String aftEnvironment, - String partner, - String latitude, - String longitude, - Map<String,String> additionalProps, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized(this) { - if (dmaapTopicSources.containsKey(topic)) { - return dmaapTopicSources.get(topic); - } - - DmaapTopicSource dmaapTopicSource = - new SingleThreadedDmaapTopicSource(servers, topic, - apiKey, apiSecret, userName, password, - consumerGroup, consumerInstance, - fetchTimeout, fetchLimit, - environment, aftEnvironment, partner, - latitude, longitude, additionalProps, useHttps, allowSelfSignedCerts); - - if (managed) - dmaapTopicSources.put(topic, dmaapTopicSource); - - return dmaapTopicSource; - } - } - /** - * {@inheritDoc} - */ - @Override - public DmaapTopicSource build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String userName, - String password, - String consumerGroup, - String consumerInstance, - int fetchTimeout, - int fetchLimit, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts) { - - if (servers == null || servers.isEmpty()) { - throw new IllegalArgumentException("DMaaP Server(s) must be provided"); - } - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized(this) { - if (dmaapTopicSources.containsKey(topic)) { - return dmaapTopicSources.get(topic); - } - - DmaapTopicSource dmaapTopicSource = - new SingleThreadedDmaapTopicSource(servers, topic, - apiKey, apiSecret, userName, password, - consumerGroup, consumerInstance, - fetchTimeout, fetchLimit, useHttps,allowSelfSignedCerts); - - if (managed) - dmaapTopicSources.put(topic, dmaapTopicSource); - - return dmaapTopicSource; - } - } - - /** - * {@inheritDoc} - */ - @Override - public List<DmaapTopicSource> build(Properties properties) { - - String readTopics = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS); - if (readTopics == null || readTopics.isEmpty()) { - logger.info("{}: no topic for DMaaP Source", this); - return new ArrayList<>(); - } - List<String> readTopicList = new ArrayList<>(Arrays.asList(readTopics.split("\\s*,\\s*"))); - - List<DmaapTopicSource> dmaapTopicSourceLst = new ArrayList<>(); - synchronized(this) { - for (String topic: readTopicList) { - if (this.dmaapTopicSources.containsKey(topic)) { - dmaapTopicSourceLst.add(this.dmaapTopicSources.get(topic)); - continue; - } - - String servers = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + - topic + - PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX); - - List<String> serverList; - if (servers != null && !servers.isEmpty()) - serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*"))); - else serverList = new ArrayList<>(); - - String apiKey = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_API_KEY_SUFFIX); - - String apiSecret = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_API_SECRET_SUFFIX); - - String aafMechId = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX); - - String aafPassword = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX); - - String consumerGroup = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX); - - String consumerInstance = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX); - - String fetchTimeoutString = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX); - - /* DME2 Properties */ - - String dme2Environment = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX); - - String dme2AftEnvironment = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX); - - String dme2Partner = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX); - - String dme2RouteOffer = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX); - - String dme2Latitude = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX); - - String dme2Longitude = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX); - - String dme2EpReadTimeoutMs = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_EP_READ_TIMEOUT_MS_SUFFIX); - - String dme2EpConnTimeout = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_EP_CONN_TIMEOUT_SUFFIX); - - String dme2RoundtripTimeoutMs = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS - + "." + topic + PolicyProperties.PROPERTY_DMAAP_DME2_ROUNDTRIP_TIMEOUT_MS_SUFFIX); - - String dme2Version = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_VERSION_SUFFIX); - - String dme2SubContextPath = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." - + topic + PolicyProperties.PROPERTY_DMAAP_DME2_SUB_CONTEXT_PATH_SUFFIX); - - String dme2SessionStickinessRequired = properties - .getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_SESSION_STICKINESS_REQUIRED_SUFFIX); - - Map<String,String> dme2AdditionalProps = new HashMap<>(); - - if (dme2EpReadTimeoutMs != null && !dme2EpReadTimeoutMs.isEmpty()) - dme2AdditionalProps.put(DME2_READ_TIMEOUT_PROPERTY, dme2EpReadTimeoutMs); - if (dme2EpConnTimeout != null && !dme2EpConnTimeout.isEmpty()) - dme2AdditionalProps.put(DME2_EP_CONN_TIMEOUT_PROPERTY, dme2EpConnTimeout); - if (dme2RoundtripTimeoutMs != null && !dme2RoundtripTimeoutMs.isEmpty()) - dme2AdditionalProps.put(DME2_ROUNDTRIP_TIMEOUT_PROPERTY, dme2RoundtripTimeoutMs); - if (dme2Version != null && !dme2Version.isEmpty()) - dme2AdditionalProps.put(DME2_VERSION_PROPERTY, dme2Version); - if (dme2RouteOffer != null && !dme2RouteOffer.isEmpty()) - dme2AdditionalProps.put(DME2_ROUTE_OFFER_PROPERTY, dme2RouteOffer); - if (dme2SubContextPath != null && !dme2SubContextPath.isEmpty()) - dme2AdditionalProps.put(DME2_SUBCONTEXT_PATH_PROPERTY, dme2SubContextPath); - if (dme2SessionStickinessRequired != null && !dme2SessionStickinessRequired.isEmpty()) - dme2AdditionalProps.put(DME2_SESSION_STICKINESS_REQUIRED_PROPERTY, dme2SessionStickinessRequired); - - - if (servers == null || servers.isEmpty()) { - - logger.error("{}: no DMaaP servers or DME2 ServiceName provided", this); - continue; - } - - int fetchTimeout = DmaapTopicSource.DEFAULT_TIMEOUT_MS_FETCH; - if (fetchTimeoutString != null && !fetchTimeoutString.isEmpty()) { - try { - fetchTimeout = Integer.parseInt(fetchTimeoutString); - } catch (NumberFormatException nfe) { - logger.warn("{}: fetch timeout {} is in invalid format for topic {} ", - this, fetchTimeoutString, topic); - } - } - - String fetchLimitString = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX); - int fetchLimit = DmaapTopicSource.DEFAULT_LIMIT_FETCH; - if (fetchLimitString != null && !fetchLimitString.isEmpty()) { - try { - fetchLimit = Integer.parseInt(fetchLimitString); - } catch (NumberFormatException nfe) { - logger.warn("{}: fetch limit {} is in invalid format for topic {} ", - this, fetchLimitString, topic); - } - } - - String managedString = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_MANAGED_SUFFIX); - boolean managed = true; - if (managedString != null && !managedString.isEmpty()) { - managed = Boolean.parseBoolean(managedString); - } - - String useHttpsString = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic + - PolicyProperties.PROPERTY_HTTP_HTTPS_SUFFIX); - - //default is to use HTTP if no https property exists - boolean useHttps = false; - if (useHttpsString != null && !useHttpsString.isEmpty()){ - useHttps = Boolean.parseBoolean(useHttpsString); - } - - String allowSelfSignedCertsString = properties.getProperty(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic + - PolicyProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX); - - //default is to disallow self-signed certs - boolean allowSelfSignedCerts = false; - if (allowSelfSignedCertsString != null && !allowSelfSignedCertsString.isEmpty()){ - allowSelfSignedCerts = Boolean.parseBoolean(allowSelfSignedCertsString); - } - - - DmaapTopicSource uebTopicSource = this.build(serverList, topic, - apiKey, apiSecret, aafMechId, aafPassword, - consumerGroup, consumerInstance, - fetchTimeout, fetchLimit, - dme2Environment, dme2AftEnvironment, dme2Partner, - dme2Latitude, dme2Longitude, dme2AdditionalProps, - managed, useHttps, allowSelfSignedCerts); - - dmaapTopicSourceLst.add(uebTopicSource); - } - } - return dmaapTopicSourceLst; - } - - /** - * {@inheritDoc} - * @throws IllegalArgumentException - */ - @Override - public DmaapTopicSource build(List<String> servers, - String topic, - String apiKey, - String apiSecret) { - return this.build(servers, topic, - apiKey, apiSecret, null, null, - null, null, - DmaapTopicSource.DEFAULT_TIMEOUT_MS_FETCH, - DmaapTopicSource.DEFAULT_LIMIT_FETCH, - true, - false, - false); - } - - /** - * {@inheritDoc} - * @throws IllegalArgumentException - */ - @Override - public DmaapTopicSource build(List<String> servers, String topic) { - return this.build(servers, topic, null, null); - } - - /** - * {@inheritDoc} - */ - @Override - public void destroy(String topic) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - DmaapTopicSource uebTopicSource; - - synchronized(this) { - if (!dmaapTopicSources.containsKey(topic)) { - return; - } - - uebTopicSource = dmaapTopicSources.remove(topic); - } - - uebTopicSource.shutdown(); - } - - /** - * {@inheritDoc} - */ - @Override - public DmaapTopicSource get(String topic) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized(this) { - if (dmaapTopicSources.containsKey(topic)) { - return dmaapTopicSources.get(topic); - } else { - throw new IllegalArgumentException("DmaapTopiceSource for " + topic + " not found"); - } - } - } - - @Override - public synchronized List<DmaapTopicSource> inventory() { - return new ArrayList<>(this.dmaapTopicSources.values()); - } - - @Override - public void destroy() { - List<DmaapTopicSource> readers = this.inventory(); - for (DmaapTopicSource reader: readers) { - reader.shutdown(); - } - - synchronized(this) { - this.dmaapTopicSources.clear(); - } - } - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("IndexedDmaapTopicSourceFactory []"); - return builder.toString(); - } - -} - diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/NoopTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/NoopTopicSink.java deleted file mode 100644 index afc11229..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/NoopTopicSink.java +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.event.comm.bus; - -import java.util.List; - -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.bus.internal.TopicBase; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * NOOP topic sink - */ -public class NoopTopicSink extends TopicBase implements TopicSink { - - /** - * factory - */ - public static final NoopTopicSinkFactory factory = new IndexedNoopTopicSinkFactory(); - - /** - * logger - */ - private static Logger logger = LoggerFactory.getLogger(NoopTopicSink.class); - - /** - * net logger - */ - private static final Logger netLogger = LoggerFactory.getLogger(NETWORK_LOGGER); - - /** - * constructor - * @param servers servers - * @param topic topic - * @throws IllegalArgumentException if an invalid argument has been passed in - */ - public NoopTopicSink(List<String> servers, String topic) { - super(servers, topic); - } - - @Override - public boolean send(String message) { - - if (message == null || message.isEmpty()) - throw new IllegalArgumentException("Message to send is empty"); - - if (!this.alive) - throw new IllegalStateException(this + " is stopped"); - - try { - synchronized (this) { - this.recentEvents.add(message); - } - - netLogger.info("[OUT|{}|{}]{}{}", this.getTopicCommInfrastructure(), - this.topic, System.lineSeparator(), message); - - broadcast(message); - } catch (Exception e) { - logger.warn("{}: cannot send because of {}", this, e.getMessage(), e); - return false; - } - - return true; - } - - @Override - public CommInfrastructure getTopicCommInfrastructure() { - return CommInfrastructure.NOOP; - } - - @Override - public boolean start() { - logger.info("{}: starting", this); - - synchronized(this) { - - if (this.alive) - return true; - - if (locked) - throw new IllegalStateException(this + " is locked."); - - this.alive = true; - } - - return true; - } - - @Override - public boolean stop() { - synchronized(this) { - this.alive = false; - } - return true; - } - - @Override - public void shutdown() { - this.stop(); - } - - @Override - public String toString() { - return "NoopTopicSink [toString()=" + super.toString() + "]"; - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/NoopTopicSinkFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/NoopTopicSinkFactory.java deleted file mode 100644 index 8633d093..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/NoopTopicSinkFactory.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.event.comm.bus; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; - -import org.onap.policy.drools.properties.PolicyProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Noop Topic Sink Factory - */ -public interface NoopTopicSinkFactory { - - /** - * Creates noop topic sinks based on properties files - * - * @param properties Properties containing initialization values - * - * @return a noop topic sink - * @throws IllegalArgumentException if invalid parameters are present - */ - public List<NoopTopicSink> build(Properties properties); - - /** - * builds a noop sink - * - * @param servers list of servers - * @param topic topic name - * @param managed is this sink endpoint managed? - * @return a noop topic sink - * @throws IllegalArgumentException if invalid parameters are present - */ - public NoopTopicSink build(List<String> servers, String topic, boolean managed); - - /** - * Destroys a sink based on the topic - * - * @param topic topic name - * @throws IllegalArgumentException if invalid parameters are present - */ - public void destroy(String topic); - - /** - * gets a sink based on topic name - * - * @param topic the topic name - * - * @return a sink with topic name - * @throws IllegalArgumentException if an invalid topic is provided - * @throws IllegalStateException if the sink is in an incorrect state - */ - public NoopTopicSink get(String topic); - - /** - * Provides a snapshot of the UEB Topic Writers - * - * @return a list of the UEB Topic Writers - */ - public List<NoopTopicSink> inventory(); - - /** - * Destroys all sinks - */ - public void destroy(); -} - - -/* ------------- implementation ----------------- */ - -/** - * Factory of noop sinks - */ -class IndexedNoopTopicSinkFactory implements NoopTopicSinkFactory { - private static final String MISSING_TOPIC = "A topic must be provided"; - -/** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(IndexedUebTopicSinkFactory.class); - - /** - * noop topic sinks map - */ - protected HashMap<String, NoopTopicSink> noopTopicSinks = new HashMap<>(); - - @Override - public List<NoopTopicSink> build(Properties properties) { - - final String sinkTopics = properties.getProperty(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS); - if (sinkTopics == null || sinkTopics.isEmpty()) { - logger.info("{}: no topic for noop sink", this); - return new ArrayList<>(); - } - - final List<String> sinkTopicList = - new ArrayList<>(Arrays.asList(sinkTopics.split("\\s*,\\s*"))); - final List<NoopTopicSink> newSinks = new ArrayList<>(); - synchronized (this) { - for (final String topic : sinkTopicList) { - if (this.noopTopicSinks.containsKey(topic)) { - newSinks.add(this.noopTopicSinks.get(topic)); - continue; - } - - String servers = properties.getProperty(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS + "." - + topic + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX); - - if (servers == null || servers.isEmpty()) - servers = "noop"; - - final List<String> serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*"))); - - final String managedString = - properties.getProperty(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS + "." + topic - + PolicyProperties.PROPERTY_MANAGED_SUFFIX); - boolean managed = true; - if (managedString != null && !managedString.isEmpty()) { - managed = Boolean.parseBoolean(managedString); - } - - final NoopTopicSink noopSink = this.build(serverList, topic, managed); - newSinks.add(noopSink); - } - return newSinks; - } - } - - @Override - public NoopTopicSink build(List<String> servers, String topic, boolean managed) { - - List<String> noopSinkServers = servers; - if (noopSinkServers == null) { - noopSinkServers = new ArrayList<>(); - } - - if (noopSinkServers.isEmpty()) { - noopSinkServers.add("noop"); - } - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized (this) { - if (this.noopTopicSinks.containsKey(topic)) { - return this.noopTopicSinks.get(topic); - } - - final NoopTopicSink sink = new NoopTopicSink(noopSinkServers, topic); - - if (managed) - this.noopTopicSinks.put(topic, sink); - - return sink; - } - } - - @Override - public void destroy(String topic) { - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - NoopTopicSink noopSink; - synchronized (this) { - if (!this.noopTopicSinks.containsKey(topic)) { - return; - } - - noopSink = this.noopTopicSinks.remove(topic); - } - - noopSink.shutdown(); - } - - @Override - public void destroy() { - final List<NoopTopicSink> sinks = this.inventory(); - for (final NoopTopicSink sink : sinks) { - sink.shutdown(); - } - - synchronized (this) { - this.noopTopicSinks.clear(); - } - } - - @Override - public NoopTopicSink get(String topic) { - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized (this) { - if (this.noopTopicSinks.containsKey(topic)) { - return this.noopTopicSinks.get(topic); - } else { - throw new IllegalStateException("DmaapTopicSink for " + topic + " not found"); - } - } - } - - @Override - public List<NoopTopicSink> inventory() { - return new ArrayList<>(this.noopTopicSinks.values()); - } -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSink.java deleted file mode 100644 index 57dd1f1a..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSink.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -/** - * Topic Writer over UEB Infrastructure - */ -public interface UebTopicSink extends BusTopicSink { - - /** - * Factory of UEB Topic Sinks for instantiation and management purposes - */ - public static final UebTopicSinkFactory factory = new IndexedUebTopicSinkFactory(); -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSinkFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSinkFactory.java deleted file mode 100644 index 10468bef..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSinkFactory.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; - -import org.onap.policy.drools.event.comm.bus.internal.InlineUebTopicSink; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; -import org.onap.policy.drools.properties.PolicyProperties; - -/** - * UEB Topic Sink Factory - */ -public interface UebTopicSinkFactory { - - /** - * Instantiates a new UEB Topic Writer - * - * @param servers list of servers - * @param topic topic name - * @param apiKey API Key - * @param apiSecret API Secret - * @param partitionKey Consumer Group - * @param managed is this sink endpoint managed? - * - * @return an UEB Topic Sink - * @throws IllegalArgumentException if invalid parameters are present - */ - public UebTopicSink build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String partitionKey, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts); - - /** - * Creates an UEB Topic Writer based on properties files - * - * @param properties Properties containing initialization values - * - * @return an UEB Topic Writer - * @throws IllegalArgumentException if invalid parameters are present - */ - public List<UebTopicSink> build(Properties properties); - - /** - * Instantiates a new UEB Topic Writer - * - * @param servers list of servers - * @param topic topic name - * - * @return an UEB Topic Writer - * @throws IllegalArgumentException if invalid parameters are present - */ - public UebTopicSink build(List<String> servers, String topic); - - /** - * Destroys an UEB Topic Writer based on a topic - * - * @param topic topic name - * @throws IllegalArgumentException if invalid parameters are present - */ - public void destroy(String topic); - - /** - * gets an UEB Topic Writer based on topic name - * @param topic the topic name - * - * @return an UEB Topic Writer with topic name - * @throws IllegalArgumentException if an invalid topic is provided - * @throws IllegalStateException if the UEB Topic Reader is - * an incorrect state - */ - public UebTopicSink get(String topic); - - /** - * Provides a snapshot of the UEB Topic Writers - * @return a list of the UEB Topic Writers - */ - public List<UebTopicSink> inventory(); - - /** - * Destroys all UEB Topic Writers - */ - public void destroy(); -} - -/* ------------- implementation ----------------- */ - -/** - * Factory of UEB Reader Topics indexed by topic name - */ -class IndexedUebTopicSinkFactory implements UebTopicSinkFactory { - private static final String MISSING_TOPIC = "A topic must be provided"; - - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(IndexedUebTopicSinkFactory.class); - - /** - * UEB Topic Name Index - */ - protected HashMap<String, UebTopicSink> uebTopicSinks = - new HashMap<>(); - - @Override - public UebTopicSink build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String partitionKey, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts) { - - if (servers == null || servers.isEmpty()) { - throw new IllegalArgumentException("UEB Server(s) must be provided"); - } - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized (this) { - if (uebTopicSinks.containsKey(topic)) { - return uebTopicSinks.get(topic); - } - - UebTopicSink uebTopicWriter = - new InlineUebTopicSink(servers, topic, - apiKey, apiSecret,partitionKey, useHttps, allowSelfSignedCerts); - - if (managed) - uebTopicSinks.put(topic, uebTopicWriter); - - return uebTopicWriter; - } - } - - - @Override - public UebTopicSink build(List<String> servers, String topic) { - return this.build(servers, topic, null, null, null, true, false, false); - } - - - @Override - public List<UebTopicSink> build(Properties properties) { - - String writeTopics = properties.getProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS); - if (writeTopics == null || writeTopics.isEmpty()) { - logger.info("{}: no topic for UEB Sink", this); - return new ArrayList<>(); - } - - List<String> writeTopicList = new ArrayList<>(Arrays.asList(writeTopics.split("\\s*,\\s*"))); - List<UebTopicSink> newUebTopicSinks = new ArrayList<>(); - synchronized(this) { - for (String topic: writeTopicList) { - if (this.uebTopicSinks.containsKey(topic)) { - newUebTopicSinks.add(this.uebTopicSinks.get(topic)); - continue; - } - - String servers = properties.getProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + "." + - topic + - PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX); - if (servers == null || servers.isEmpty()) { - logger.error("{}: no UEB servers configured for sink {}", this, topic); - continue; - } - - List<String> serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*"))); - - String apiKey = properties.getProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_API_KEY_SUFFIX); - String apiSecret = properties.getProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_API_SECRET_SUFFIX); - String partitionKey = properties.getProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_SINK_PARTITION_KEY_SUFFIX); - - String managedString = properties.getProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic + - PolicyProperties.PROPERTY_MANAGED_SUFFIX); - boolean managed = true; - if (managedString != null && !managedString.isEmpty()) { - managed = Boolean.parseBoolean(managedString); - } - - String useHttpsString = properties.getProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic + - PolicyProperties.PROPERTY_HTTP_HTTPS_SUFFIX); - - //default is to use HTTP if no https property exists - boolean useHttps = false; - if (useHttpsString != null && !useHttpsString.isEmpty()){ - useHttps = Boolean.parseBoolean(useHttpsString); - } - - - String allowSelfSignedCertsString = properties.getProperty(PolicyProperties.PROPERTY_UEB_SINK_TOPICS + "." + topic + - PolicyProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX); - - //default is to disallow self-signed certs - boolean allowSelfSignedCerts = false; - if (allowSelfSignedCertsString != null && !allowSelfSignedCertsString.isEmpty()){ - allowSelfSignedCerts = Boolean.parseBoolean(allowSelfSignedCertsString); - } - - UebTopicSink uebTopicWriter = this.build(serverList, topic, - apiKey, apiSecret, - partitionKey, managed, useHttps, allowSelfSignedCerts); - newUebTopicSinks.add(uebTopicWriter); - } - return newUebTopicSinks; - } - } - - @Override - public void destroy(String topic) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - UebTopicSink uebTopicWriter; - synchronized(this) { - if (!uebTopicSinks.containsKey(topic)) { - return; - } - - uebTopicWriter = uebTopicSinks.remove(topic); - } - - uebTopicWriter.shutdown(); - } - - @Override - public void destroy() { - List<UebTopicSink> writers = this.inventory(); - for (UebTopicSink writer: writers) { - writer.shutdown(); - } - - synchronized(this) { - this.uebTopicSinks.clear(); - } - } - - @Override - public UebTopicSink get(String topic) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized(this) { - if (uebTopicSinks.containsKey(topic)) { - return uebTopicSinks.get(topic); - } else { - throw new IllegalStateException("UebTopicSink for " + topic + " not found"); - } - } - } - - @Override - public synchronized List<UebTopicSink> inventory() { - return new ArrayList<>(this.uebTopicSinks.values()); - } - - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("IndexedUebTopicSinkFactory []"); - return builder.toString(); - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSource.java deleted file mode 100644 index 7d35a993..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSource.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -/** - * Topic Source for UEB Communication Infrastructure - * - */ -public interface UebTopicSource extends BusTopicSource { - - /** - * factory for managing and tracking UEB readers - */ - public static UebTopicSourceFactory factory = - new IndexedUebTopicSourceFactory(); -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSourceFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSourceFactory.java deleted file mode 100644 index d48be278..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/UebTopicSourceFactory.java +++ /dev/null @@ -1,394 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; - -import org.onap.policy.drools.event.comm.bus.internal.SingleThreadedUebTopicSource; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; -import org.onap.policy.drools.properties.PolicyProperties; - -/** - * UEB Topic Source Factory - */ -public interface UebTopicSourceFactory { - - /** - * Creates an UEB Topic Source based on properties files - * - * @param properties Properties containing initialization values - * - * @return an UEB Topic Source - * @throws IllegalArgumentException if invalid parameters are present - */ - public List<UebTopicSource> build(Properties properties); - - /** - * Instantiates a new UEB Topic Source - * - * @param servers list of servers - * @param topic topic name - * @param apiKey API Key - * @param apiSecret API Secret - * @param consumerGroup Consumer Group - * @param consumerInstance Consumer Instance - * @param fetchTimeout Read Fetch Timeout - * @param fetchLimit Fetch Limit - * @param managed is this source endpoint managed? - * - * @return an UEB Topic Source - * @throws IllegalArgumentException if invalid parameters are present - */ - public UebTopicSource build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String consumerGroup, - String consumerInstance, - int fetchTimeout, - int fetchLimit, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts); - - /** - * Instantiates a new UEB Topic Source - * - * @param servers list of servers - * @param topic topic name - * @param apiKey API Key - * @param apiSecret API Secret - * - * @return an UEB Topic Source - * @throws IllegalArgumentException if invalid parameters are present - */ - public UebTopicSource build(List<String> servers, - String topic, - String apiKey, - String apiSecret); - - /** - * Instantiates a new UEB Topic Source - * - * @param servers list of servers - * @param topic topic name - * - * @return an UEB Topic Source - * @throws IllegalArgumentException if invalid parameters are present - */ - public UebTopicSource build(List<String> servers, - String topic); - - /** - * Destroys an UEB Topic Source based on a topic - * - * @param topic topic name - * @throws IllegalArgumentException if invalid parameters are present - */ - public void destroy(String topic); - - /** - * Destroys all UEB Topic Sources - */ - public void destroy(); - - /** - * gets an UEB Topic Source based on topic name - * @param topic the topic name - * @return an UEB Topic Source with topic name - * @throws IllegalArgumentException if an invalid topic is provided - * @throws IllegalStateException if the UEB Topic Source is - * an incorrect state - */ - public UebTopicSource get(String topic); - - /** - * Provides a snapshot of the UEB Topic Sources - * @return a list of the UEB Topic Sources - */ - public List<UebTopicSource> inventory(); -} - -/* ------------- implementation ----------------- */ - -/** - * Factory of UEB Source Topics indexed by topic name - */ -class IndexedUebTopicSourceFactory implements UebTopicSourceFactory { - private static final String MISSING_TOPIC = "A topic must be provided"; - - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(IndexedUebTopicSourceFactory.class); - - /** - * UEB Topic Name Index - */ - protected HashMap<String, UebTopicSource> uebTopicSources = - new HashMap<>(); - - /** - * {@inheritDoc} - */ - @Override - public UebTopicSource build(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String consumerGroup, - String consumerInstance, - int fetchTimeout, - int fetchLimit, - boolean managed, - boolean useHttps, - boolean allowSelfSignedCerts) { - if (servers == null || servers.isEmpty()) { - throw new IllegalArgumentException("UEB Server(s) must be provided"); - } - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized(this) { - if (uebTopicSources.containsKey(topic)) { - return uebTopicSources.get(topic); - } - - UebTopicSource uebTopicSource = - new SingleThreadedUebTopicSource(servers, topic, - apiKey, apiSecret, - consumerGroup, consumerInstance, - fetchTimeout, fetchLimit, useHttps, allowSelfSignedCerts); - - if (managed) - uebTopicSources.put(topic, uebTopicSource); - - return uebTopicSource; - } - } - - /** - * {@inheritDoc} - */ - @Override - public List<UebTopicSource> build(Properties properties) { - - String readTopics = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS); - if (readTopics == null || readTopics.isEmpty()) { - logger.info("{}: no topic for UEB Source", this); - return new ArrayList<>(); - } - List<String> readTopicList = new ArrayList<>(Arrays.asList(readTopics.split("\\s*,\\s*"))); - - List<UebTopicSource> newUebTopicSources = new ArrayList<>(); - synchronized(this) { - for (String topic: readTopicList) { - if (this.uebTopicSources.containsKey(topic)) { - newUebTopicSources.add(this.uebTopicSources.get(topic)); - continue; - } - - String servers = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + - topic + - PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX); - - if (servers == null || servers.isEmpty()) { - logger.error("{}: no UEB servers configured for sink {}", this, topic); - continue; - } - - List<String> serverList = new ArrayList<>(Arrays.asList(servers.split("\\s*,\\s*"))); - - String apiKey = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_API_KEY_SUFFIX); - - String apiSecret = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_API_SECRET_SUFFIX); - - String consumerGroup = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_GROUP_SUFFIX); - - String consumerInstance = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_SOURCE_CONSUMER_INSTANCE_SUFFIX); - - String fetchTimeoutString = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX); - int fetchTimeout = UebTopicSource.DEFAULT_TIMEOUT_MS_FETCH; - if (fetchTimeoutString != null && !fetchTimeoutString.isEmpty()) { - try { - fetchTimeout = Integer.parseInt(fetchTimeoutString); - } catch (NumberFormatException nfe) { - logger.warn("{}: fetch timeout {} is in invalid format for topic {} ", - this, fetchTimeoutString, topic); - } - } - - String fetchLimitString = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + - "." + topic + - PolicyProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX); - int fetchLimit = UebTopicSource.DEFAULT_LIMIT_FETCH; - if (fetchLimitString != null && !fetchLimitString.isEmpty()) { - try { - fetchLimit = Integer.parseInt(fetchLimitString); - } catch (NumberFormatException nfe) { - logger.warn("{}: fetch limit {} is in invalid format for topic {} ", - this, fetchLimitString, topic); - } - } - - String managedString = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + - topic + PolicyProperties.PROPERTY_MANAGED_SUFFIX); - boolean managed = true; - if (managedString != null && !managedString.isEmpty()) { - managed = Boolean.parseBoolean(managedString); - } - - String useHttpsString = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic + - PolicyProperties.PROPERTY_HTTP_HTTPS_SUFFIX); - - //default is to use HTTP if no https property exists - boolean useHttps = false; - if (useHttpsString != null && !useHttpsString.isEmpty()){ - useHttps = Boolean.parseBoolean(useHttpsString); - } - - String allowSelfSignedCertsString = properties.getProperty(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + topic + - PolicyProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX); - - //default is to disallow self-signed certs - boolean allowSelfSignedCerts = false; - if (allowSelfSignedCertsString != null && !allowSelfSignedCertsString.isEmpty()){ - allowSelfSignedCerts = Boolean.parseBoolean(allowSelfSignedCertsString); - } - - UebTopicSource uebTopicSource = this.build(serverList, topic, - apiKey, apiSecret, - consumerGroup, consumerInstance, - fetchTimeout, fetchLimit, managed, useHttps, allowSelfSignedCerts); - newUebTopicSources.add(uebTopicSource); - } - } - return newUebTopicSources; - } - - /** - * {@inheritDoc} - */ - @Override - public UebTopicSource build(List<String> servers, - String topic, - String apiKey, - String apiSecret) { - - return this.build(servers, topic, - apiKey, apiSecret, - null, null, - UebTopicSource.DEFAULT_TIMEOUT_MS_FETCH, - UebTopicSource.DEFAULT_LIMIT_FETCH, true, false, true); - } - - /** - * {@inheritDoc} - */ - @Override - public UebTopicSource build(List<String> servers, String topic) { - return this.build(servers, topic, null, null); - } - - /** - * {@inheritDoc} - */ - @Override - public void destroy(String topic) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - UebTopicSource uebTopicSource; - - synchronized(this) { - if (!uebTopicSources.containsKey(topic)) { - return; - } - - uebTopicSource = uebTopicSources.remove(topic); - } - - uebTopicSource.shutdown(); - } - - /** - * {@inheritDoc} - */ - @Override - public UebTopicSource get(String topic) { - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException(MISSING_TOPIC); - } - - synchronized(this) { - if (uebTopicSources.containsKey(topic)) { - return uebTopicSources.get(topic); - } else { - throw new IllegalStateException("UebTopiceSource for " + topic + " not found"); - } - } - } - - @Override - public synchronized List<UebTopicSource> inventory() { - return new ArrayList<>(this.uebTopicSources.values()); - } - - @Override - public void destroy() { - List<UebTopicSource> readers = this.inventory(); - for (UebTopicSource reader: readers) { - reader.shutdown(); - } - - synchronized(this) { - this.uebTopicSources.clear(); - } - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("IndexedUebTopicSourceFactory []"); - return builder.toString(); - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusConsumer.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusConsumer.java deleted file mode 100644 index 828bb920..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusConsumer.java +++ /dev/null @@ -1,546 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus.internal; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import org.onap.policy.drools.event.comm.bus.DmaapTopicSinkFactory; -import org.onap.policy.drools.properties.PolicyProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.cambria.client.CambriaClientBuilders; -import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; -import com.att.nsa.cambria.client.CambriaConsumer; -import com.att.nsa.mr.client.MRClientFactory; -import com.att.nsa.mr.client.impl.MRConsumerImpl; -import com.att.nsa.mr.client.response.MRConsumerResponse; -import com.att.nsa.mr.test.clients.ProtocolTypeConstants; - -/** - * Wrapper around libraries to consume from message bus - * - */ -public interface BusConsumer { - - /** - * fetch messages - * - * @return list of messages - * @throws Exception when error encountered by underlying libraries - */ - public Iterable<String> fetch() throws InterruptedException, IOException; - - /** - * close underlying library consumer - */ - public void close(); - - /** - * BusConsumer that supports server-side filtering. - */ - public interface FilterableBusConsumer extends BusConsumer { - - /** - * Sets the server-side filter. - * - * @param filter new filter value, or {@code null} - * @throws IllegalArgumentException if the consumer cannot be built with - * the new filter - */ - public void setFilter(String filter); - } - - /** - * Cambria based consumer - */ - public static class CambriaConsumerWrapper implements FilterableBusConsumer { - - /** - * logger - */ - private static Logger logger = LoggerFactory.getLogger(CambriaConsumerWrapper.class); - - /** - * Used to build the consumer. - */ - private final ConsumerBuilder builder; - - /** - * Locked while updating {@link #consumer} and {@link #newConsumer}. - */ - private final Object consLocker = new Object(); - - /** - * Cambria client - */ - private CambriaConsumer consumer; - - /** - * Cambria client to use for next fetch - */ - private CambriaConsumer newConsumer = null; - - /** - * fetch timeout - */ - protected int fetchTimeout; - - /** - * close condition - */ - protected Object closeCondition = new Object(); - - /** - * Cambria Consumer Wrapper - * - * @param servers messaging bus hosts - * @param topic topic - * @param apiKey API Key - * @param apiSecret API Secret - * @param consumerGroup Consumer Group - * @param consumerInstance Consumer Instance - * @param fetchTimeout Fetch Timeout - * @param fetchLimit Fetch Limit - * @throws GeneralSecurityException - * @throws MalformedURLException - */ - public CambriaConsumerWrapper(List<String> servers, String topic, String apiKey, - String apiSecret, String consumerGroup, String consumerInstance, int fetchTimeout, - int fetchLimit, boolean useHttps, boolean useSelfSignedCerts) { - this(servers, topic, apiKey, apiSecret, null, null, - consumerGroup, consumerInstance, fetchTimeout, fetchLimit, - useHttps, useSelfSignedCerts); - } - - public CambriaConsumerWrapper(List<String> servers, String topic, String apiKey, - String apiSecret, String username, String password, - String consumerGroup, String consumerInstance, int fetchTimeout, - int fetchLimit, boolean useHttps, boolean useSelfSignedCerts) { - - this.fetchTimeout = fetchTimeout; - - this.builder = new CambriaClientBuilders.ConsumerBuilder(); - - builder.knownAs(consumerGroup, consumerInstance).usingHosts(servers).onTopic(topic) - .waitAtServer(fetchTimeout).receivingAtMost(fetchLimit); - - // Set read timeout to fetch timeout + 30 seconds (TBD: this should be configurable) - builder.withSocketTimeout(fetchTimeout + 30000); - - if (useHttps) { - builder.usingHttps(); - - if (useSelfSignedCerts) { - builder.allowSelfSignedCertificates(); - } - } - - if (apiKey != null && !apiKey.isEmpty() && apiSecret != null && !apiSecret.isEmpty()) { - builder.authenticatedBy(apiKey, apiSecret); - } - - if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) { - builder.authenticatedByHttp(username, password); - } - - try { - this.consumer = builder.build(); - } catch (MalformedURLException | GeneralSecurityException e) { - throw new IllegalArgumentException(e); - } - } - - @Override - public Iterable<String> fetch() throws IOException, InterruptedException { - try { - return getCurrentConsumer().fetch(); - } catch (final IOException e) { - logger.error("{}: cannot fetch because of {} - backoff for {} ms.", this, e.getMessage(), - this.fetchTimeout); - synchronized (this.closeCondition) { - this.closeCondition.wait(this.fetchTimeout); - } - - throw e; - } - } - - @Override - public void close() { - synchronized (closeCondition) { - closeCondition.notifyAll(); - } - - getCurrentConsumer().close(); - } - - private CambriaConsumer getCurrentConsumer() { - CambriaConsumer old = null; - CambriaConsumer ret; - - synchronized(consLocker) { - if(this.newConsumer != null) { - // replace old consumer with new consumer - old = this.consumer; - this.consumer = this.newConsumer; - this.newConsumer = null; - } - - ret = this.consumer; - } - - if(old != null) { - old.close(); - } - - return ret; - } - - @Override - public void setFilter(String filter) { - logger.info("{}: setting DMAAP server-side filter: {}", this, filter); - builder.withServerSideFilter(filter); - - try { - CambriaConsumer previous; - synchronized(consLocker) { - previous = this.newConsumer; - this.newConsumer = builder.build(); - } - - if(previous != null) { - // there was already a new consumer - close it - previous.close(); - } - - } catch (MalformedURLException | GeneralSecurityException e) { - /* - * Since an exception occurred, "consumer" still has its old value, - * thus it should not be closed at this point. - */ - throw new IllegalArgumentException(e); - } - } - - @Override - public String toString() { - return "CambriaConsumerWrapper [fetchTimeout=" + fetchTimeout + "]"; - } - } - - /** - * MR based consumer - */ - public abstract class DmaapConsumerWrapper implements BusConsumer { - - /** - * logger - */ - private static Logger logger = LoggerFactory.getLogger(DmaapConsumerWrapper.class); - - /** - * Name of the "protocol" property. - */ - protected static final String PROTOCOL_PROP = "Protocol"; - - /** - * fetch timeout - */ - protected int fetchTimeout; - - /** - * close condition - */ - protected Object closeCondition = new Object(); - - /** - * MR Consumer - */ - protected MRConsumerImpl consumer; - - /** - * MR Consumer Wrapper - * - * @param servers messaging bus hosts - * @param topic topic - * @param apiKey API Key - * @param apiSecret API Secret - * @param username AAF Login - * @param password AAF Password - * @param consumerGroup Consumer Group - * @param consumerInstance Consumer Instance - * @param fetchTimeout Fetch Timeout - * @param fetchLimit Fetch Limit - * @throws MalformedURLException - */ - public DmaapConsumerWrapper(List<String> servers, String topic, String apiKey, String apiSecret, - String username, String password, String consumerGroup, String consumerInstance, - int fetchTimeout, int fetchLimit) throws MalformedURLException { - - this.fetchTimeout = fetchTimeout; - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException("No topic for DMaaP"); - } - - this.consumer = new MRConsumerImpl(servers, topic, consumerGroup, consumerInstance, - fetchTimeout, fetchLimit, null, apiKey, apiSecret); - - this.consumer.setUsername(username); - this.consumer.setPassword(password); - } - - @Override - public Iterable<String> fetch() throws InterruptedException, IOException { - final MRConsumerResponse response = this.consumer.fetchWithReturnConsumerResponse(); - if (response == null) { - logger.warn("{}: DMaaP NULL response received", this); - - synchronized (closeCondition) { - closeCondition.wait(fetchTimeout); - } - return new ArrayList<>(); - } else { - logger.debug("DMaaP consumer received {} : {}" + response.getResponseCode(), - response.getResponseMessage()); - - if (response.getResponseCode() == null || !"200".equals(response.getResponseCode())) { - - logger.error("DMaaP consumer received: {} : {}", response.getResponseCode(), - response.getResponseMessage()); - - synchronized (closeCondition) { - closeCondition.wait(fetchTimeout); - } - - /* fall through */ - } - } - - if (response.getActualMessages() == null) - return new ArrayList<>(); - else - return response.getActualMessages(); - } - - @Override - public void close() { - synchronized (closeCondition) { - closeCondition.notifyAll(); - } - - this.consumer.close(); - } - - @Override - public String toString() { - return "DmaapConsumerWrapper [" + "consumer.getAuthDate()=" + consumer.getAuthDate() - + ", consumer.getAuthKey()=" + consumer.getAuthKey() + ", consumer.getHost()=" - + consumer.getHost() + ", consumer.getProtocolFlag()=" + consumer.getProtocolFlag() - + ", consumer.getUsername()=" + consumer.getUsername() + "]"; - } - } - - /** - * MR based consumer - */ - public static class DmaapAafConsumerWrapper extends DmaapConsumerWrapper { - - private static Logger logger = LoggerFactory.getLogger(DmaapAafConsumerWrapper.class); - - private final Properties props; - - /** - * MR Consumer Wrapper - * - * @param servers messaging bus hosts - * @param topic topic - * @param apiKey API Key - * @param apiSecret API Secret - * @param aafLogin AAF Login - * @param aafPassword AAF Password - * @param consumerGroup Consumer Group - * @param consumerInstance Consumer Instance - * @param fetchTimeout Fetch Timeout - * @param fetchLimit Fetch Limit - * @throws MalformedURLException - */ - public DmaapAafConsumerWrapper(List<String> servers, String topic, String apiKey, - String apiSecret, String aafLogin, String aafPassword, String consumerGroup, - String consumerInstance, int fetchTimeout, int fetchLimit, boolean useHttps) - throws MalformedURLException { - - super(servers, topic, apiKey, apiSecret, aafLogin, aafPassword, consumerGroup, - consumerInstance, fetchTimeout, fetchLimit); - - // super constructor sets servers = {""} if empty to avoid errors when using DME2 - if ((servers.size() == 1 && ("".equals(servers.get(0)))) || (servers == null) - || (servers.isEmpty())) { - throw new IllegalArgumentException("Must provide at least one host for HTTP AAF"); - } - - this.consumer.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - - props = new Properties(); - - if (useHttps) { - props.setProperty(PROTOCOL_PROP, "https"); - this.consumer.setHost(servers.get(0) + ":3905"); - - } else { - props.setProperty(PROTOCOL_PROP, "http"); - this.consumer.setHost(servers.get(0) + ":3904"); - } - - this.consumer.setProps(props); - logger.info("{}: CREATION", this); - } - - @Override - public String toString() { - final MRConsumerImpl consumer = this.consumer; - - return "DmaapConsumerWrapper [" + "consumer.getAuthDate()=" + consumer.getAuthDate() - + ", consumer.getAuthKey()=" + consumer.getAuthKey() + ", consumer.getHost()=" - + consumer.getHost() + ", consumer.getProtocolFlag()=" + consumer.getProtocolFlag() - + ", consumer.getUsername()=" + consumer.getUsername() + "]"; - } - } - - public static class DmaapDmeConsumerWrapper extends DmaapConsumerWrapper { - - private static Logger logger = LoggerFactory.getLogger(DmaapDmeConsumerWrapper.class); - - private final Properties props; - - public DmaapDmeConsumerWrapper(List<String> servers, String topic, String apiKey, - String apiSecret, String dme2Login, String dme2Password, String consumerGroup, - String consumerInstance, int fetchTimeout, int fetchLimit, String environment, - String aftEnvironment, String dme2Partner, String latitude, String longitude, - Map<String, String> additionalProps, boolean useHttps) throws MalformedURLException { - - - - super(servers, topic, apiKey, apiSecret, dme2Login, dme2Password, consumerGroup, - consumerInstance, fetchTimeout, fetchLimit); - - - final String dme2RouteOffer = - additionalProps.get(DmaapTopicSinkFactory.DME2_ROUTE_OFFER_PROPERTY); - - if (environment == null || environment.isEmpty()) { - throw parmException(topic, PolicyProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX); - } - if (aftEnvironment == null || aftEnvironment.isEmpty()) { - throw parmException(topic, PolicyProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX); - } - if (latitude == null || latitude.isEmpty()) { - throw parmException(topic, PolicyProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX); - } - if (longitude == null || longitude.isEmpty()) { - throw parmException(topic, PolicyProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX); - } - - if ((dme2Partner == null || dme2Partner.isEmpty()) - && (dme2RouteOffer == null || dme2RouteOffer.isEmpty())) { - throw new IllegalArgumentException( - "Must provide at least " + PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX + " or " - + PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic - + PolicyProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX + " for DME2"); - } - - final String serviceName = servers.get(0); - - this.consumer.setProtocolFlag(ProtocolTypeConstants.DME2.getValue()); - - this.consumer.setUsername(dme2Login); - this.consumer.setPassword(dme2Password); - - props = new Properties(); - - props.setProperty(DmaapTopicSinkFactory.DME2_SERVICE_NAME_PROPERTY, serviceName); - - props.setProperty("username", dme2Login); - props.setProperty("password", dme2Password); - - /* These are required, no defaults */ - props.setProperty("topic", topic); - - props.setProperty("Environment", environment); - props.setProperty("AFT_ENVIRONMENT", aftEnvironment); - - if (dme2Partner != null) - props.setProperty("Partner", dme2Partner); - if (dme2RouteOffer != null) - props.setProperty(DmaapTopicSinkFactory.DME2_ROUTE_OFFER_PROPERTY, dme2RouteOffer); - - props.setProperty("Latitude", latitude); - props.setProperty("Longitude", longitude); - - /* These are optional, will default to these values if not set in additionalProps */ - props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", "50000"); - props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", "240000"); - props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", "15000"); - props.setProperty("Version", "1.0"); - props.setProperty("SubContextPath", "/"); - props.setProperty("sessionstickinessrequired", "no"); - - /* These should not change */ - props.setProperty("TransportType", "DME2"); - props.setProperty("MethodType", "GET"); - - if (useHttps) { - props.setProperty(PROTOCOL_PROP, "https"); - - } else { - props.setProperty(PROTOCOL_PROP, "http"); - } - - props.setProperty("contenttype", "application/json"); - - if (additionalProps != null) { - for (Map.Entry<String, String> entry : additionalProps.entrySet()) - props.put(entry.getKey(), entry.getValue()); - } - - MRClientFactory.prop = props; - this.consumer.setProps(props); - - logger.info("{}: CREATION", this); - } - - private IllegalArgumentException parmException(String topic, String propnm) { - return new IllegalArgumentException( - "Missing " + PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + topic - + propnm + " property for DME2 in DMaaP"); - - } - } -} - - diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusPublisher.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusPublisher.java deleted file mode 100644 index 1efaa063..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusPublisher.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus.internal; - -import java.net.MalformedURLException; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import org.onap.policy.drools.event.comm.bus.DmaapTopicSinkFactory; -import org.onap.policy.drools.properties.PolicyProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import com.att.nsa.cambria.client.CambriaClientBuilders; -import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; -import com.att.nsa.mr.client.impl.MRSimplerBatchPublisher; -import com.att.nsa.mr.client.response.MRPublisherResponse; -import com.att.nsa.mr.test.clients.ProtocolTypeConstants; -import com.fasterxml.jackson.annotation.JsonIgnore; - -public interface BusPublisher { - - /** - * sends a message - * - * @param partition id - * @param message the message - * @return true if success, false otherwise - * @throws IllegalArgumentException if no message provided - */ - public boolean send(String partitionId, String message); - - /** - * closes the publisher - */ - public void close(); - - /** - * Cambria based library publisher - */ - public static class CambriaPublisherWrapper implements BusPublisher { - - private static Logger logger = LoggerFactory.getLogger(CambriaPublisherWrapper.class); - - /** - * The actual Cambria publisher - */ - @JsonIgnore - protected volatile CambriaBatchingPublisher publisher; - - public CambriaPublisherWrapper(List<String> servers, String topic, - String apiKey, - String apiSecret, boolean useHttps) { - this(servers, topic, apiKey, apiSecret, null, null, useHttps); - } - - public CambriaPublisherWrapper(List<String> servers, String topic, - String apiKey, String apiSecret, - String username, String password, - boolean useHttps) { - - PublisherBuilder builder = new CambriaClientBuilders.PublisherBuilder(); - - builder.usingHosts(servers).onTopic(topic); - - // Set read timeout to 30 seconds (TBD: this should be configurable) - builder.withSocketTimeout(30000); - - if (useHttps){ - builder.usingHttps(); - } - - - if (apiKey != null && !apiKey.isEmpty() && - apiSecret != null && !apiSecret.isEmpty()) { - builder.authenticatedBy(apiKey, apiSecret); - } - - if (username != null && !username.isEmpty() && - password != null && !password.isEmpty()) { - builder.authenticatedByHttp(username, password); - } - - try { - this.publisher = builder.build(); - } catch (MalformedURLException | GeneralSecurityException e) { - throw new IllegalArgumentException(e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean send(String partitionId, String message) { - if (message == null) - throw new IllegalArgumentException("No message provided"); - - try { - this.publisher.send(partitionId, message); - } catch (Exception e) { - logger.warn("{}: SEND of {} cannot be performed because of {}", - this, message, e.getMessage(), e); - return false; - } - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public void close() { - logger.info("{}: CLOSE", this); - - try { - this.publisher.close(); - } catch (Exception e) { - logger.warn("{}: CLOSE FAILED because of {}", - this, e.getMessage(),e); - } - } - - - @Override - public String toString() { - return "CambriaPublisherWrapper []"; - } - - } - - /** - * DmaapClient library wrapper - */ - public abstract class DmaapPublisherWrapper implements BusPublisher { - - private static Logger logger = LoggerFactory.getLogger(DmaapPublisherWrapper.class); - - /** - * MR based Publisher - */ - protected MRSimplerBatchPublisher publisher; - protected Properties props; - - /** - * MR Publisher Wrapper - * - * @param servers messaging bus hosts - * @param topic topic - * @param username AAF or DME2 Login - * @param password AAF or DME2 Password - */ - public DmaapPublisherWrapper(ProtocolTypeConstants protocol, - List<String> servers, String topic, - String username, - String password, boolean useHttps) { - - - if (topic == null || topic.isEmpty()) - throw new IllegalArgumentException("No topic for DMaaP"); - - - if (protocol == ProtocolTypeConstants.AAF_AUTH) { - if (servers == null || servers.isEmpty()) - throw new IllegalArgumentException("No DMaaP servers or DME2 partner provided"); - - ArrayList<String> dmaapServers = new ArrayList<>(); - if(useHttps){ - for (String server: servers) { - dmaapServers.add(server + ":3905"); - } - - } - else{ - for (String server: servers) { - dmaapServers.add(server + ":3904"); - } - } - - - this.publisher = - new MRSimplerBatchPublisher.Builder(). - againstUrls(dmaapServers). - onTopic(topic). - build(); - - this.publisher.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - } else if (protocol == ProtocolTypeConstants.DME2) { - ArrayList<String> dmaapServers = new ArrayList<>(); - dmaapServers.add("0.0.0.0:3904"); - - this.publisher = - new MRSimplerBatchPublisher.Builder(). - againstUrls(dmaapServers). - onTopic(topic). - build(); - - this.publisher.setProtocolFlag(ProtocolTypeConstants.DME2.getValue()); - } - - this.publisher.logTo(LoggerFactory.getLogger(MRSimplerBatchPublisher.class.getName())); - - this.publisher.setUsername(username); - this.publisher.setPassword(password); - - props = new Properties(); - - if (useHttps) { - props.setProperty("Protocol", "https"); - } else { - props.setProperty("Protocol", "http"); - } - - props.setProperty("contenttype", "application/json"); - props.setProperty("username", username); - props.setProperty("password", password); - - props.setProperty("topic", topic); - - this.publisher.setProps(props); - - if (protocol == ProtocolTypeConstants.AAF_AUTH) - this.publisher.setHost(servers.get(0)); - - logger.info("{}: CREATION: using protocol {}", this, protocol.getValue()); - } - - /** - * {@inheritDoc} - */ - @Override - public void close() { - logger.info("{}: CLOSE", this); - - try { - this.publisher.close(1, TimeUnit.SECONDS); - } catch (Exception e) { - logger.warn("{}: CLOSE FAILED because of {}", - this, e.getMessage(), e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean send(String partitionId, String message) { - if (message == null) - throw new IllegalArgumentException("No message provided"); - - this.publisher.setPubResponse(new MRPublisherResponse()); - this.publisher.send(partitionId, message); - MRPublisherResponse response = this.publisher.sendBatchWithResponse(); - if (response != null) { - logger.debug("DMaaP publisher received {} : {}", - response.getResponseCode(), - response.getResponseMessage()); - } - - return true; - } - - @Override - public String toString() { - return "DmaapPublisherWrapper [" + "publisher.getAuthDate()=" + publisher.getAuthDate() - + ", publisher.getAuthKey()=" + publisher.getAuthKey() + ", publisher.getHost()=" - + publisher.getHost() + ", publisher.getProtocolFlag()=" + publisher.getProtocolFlag() - + ", publisher.getUsername()=" + publisher.getUsername() + "]"; - } - } - - /** - * DmaapClient library wrapper - */ - public static class DmaapAafPublisherWrapper extends DmaapPublisherWrapper { - /** - * MR based Publisher - */ - public DmaapAafPublisherWrapper(List<String> servers, String topic, - String aafLogin, - String aafPassword, boolean useHttps) { - - super(ProtocolTypeConstants.AAF_AUTH, servers, topic, aafLogin, aafPassword, useHttps); - } - } - - public static class DmaapDmePublisherWrapper extends DmaapPublisherWrapper { - public DmaapDmePublisherWrapper(List<String> servers, String topic, - String username, String password, - String environment, String aftEnvironment, String dme2Partner, - String latitude, String longitude, Map<String,String> additionalProps, boolean useHttps) { - - super(ProtocolTypeConstants.DME2, servers, topic, username, password, useHttps); - - - - - - - String dme2RouteOffer = additionalProps.get(DmaapTopicSinkFactory.DME2_ROUTE_OFFER_PROPERTY); - - if (environment == null || environment.isEmpty()) { - throw parmException(topic, PolicyProperties.PROPERTY_DMAAP_DME2_ENVIRONMENT_SUFFIX); - } - if (aftEnvironment == null || aftEnvironment.isEmpty()) { - throw parmException(topic, PolicyProperties.PROPERTY_DMAAP_DME2_AFT_ENVIRONMENT_SUFFIX); - } - if (latitude == null || latitude.isEmpty()) { - throw parmException(topic, PolicyProperties.PROPERTY_DMAAP_DME2_LATITUDE_SUFFIX); - } - if (longitude == null || longitude.isEmpty()) { - throw parmException(topic, PolicyProperties.PROPERTY_DMAAP_DME2_LONGITUDE_SUFFIX); - } - - if ((dme2Partner == null || dme2Partner.isEmpty()) && (dme2RouteOffer == null || dme2RouteOffer.isEmpty())) { - throw new IllegalArgumentException("Must provide at least " + PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + - "." + topic + PolicyProperties.PROPERTY_DMAAP_DME2_PARTNER_SUFFIX + " or " + - PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + topic + PolicyProperties.PROPERTY_DMAAP_DME2_ROUTE_OFFER_SUFFIX + " for DME2"); - } - - String serviceName = servers.get(0); - - /* These are required, no defaults */ - props.setProperty("Environment", environment); - props.setProperty("AFT_ENVIRONMENT", aftEnvironment); - - props.setProperty(DmaapTopicSinkFactory.DME2_SERVICE_NAME_PROPERTY, serviceName); - - if (dme2Partner != null) - props.setProperty("Partner", dme2Partner); - if (dme2RouteOffer != null) - props.setProperty(DmaapTopicSinkFactory.DME2_ROUTE_OFFER_PROPERTY, dme2RouteOffer); - - props.setProperty("Latitude", latitude); - props.setProperty("Longitude", longitude); - - // ServiceName also a default, found in additionalProps - - /* These are optional, will default to these values if not set in optionalProps */ - props.setProperty("AFT_DME2_EP_READ_TIMEOUT_MS", "50000"); - props.setProperty("AFT_DME2_ROUNDTRIP_TIMEOUT_MS", "240000"); - props.setProperty("AFT_DME2_EP_CONN_TIMEOUT", "15000"); - props.setProperty("Version", "1.0"); - props.setProperty("SubContextPath", "/"); - props.setProperty("sessionstickinessrequired", "no"); - - /* These should not change */ - props.setProperty("TransportType", "DME2"); - props.setProperty("MethodType", "POST"); - - for (Map.Entry<String,String> entry : additionalProps.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - - if (value != null) - props.setProperty(key, value); - } - - this.publisher.setProps(props); - } - - private IllegalArgumentException parmException(String topic, String propnm) { - return new IllegalArgumentException("Missing " + PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + - "." + topic + propnm + " property for DME2 in DMaaP"); - - } - } -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusTopicBase.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusTopicBase.java deleted file mode 100644 index 0bf3d445..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/BusTopicBase.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus.internal; - -import java.util.List; - -import org.onap.policy.drools.event.comm.bus.ApiKeyEnabled; - -/** - * Bus Topic Base - */ -public abstract class BusTopicBase extends TopicBase implements ApiKeyEnabled { - - /** - * API Key - */ - protected String apiKey; - - /** - * API Secret - */ - protected String apiSecret; - - /** - * Use https - */ - protected boolean useHttps; - - /** - * allow self signed certificates - */ - protected boolean allowSelfSignedCerts; - - /** - * Instantiates a new Bus Topic Base - * - * @param servers list of servers - * @param topic topic name - * @param apiKey API Key - * @param apiSecret API Secret - * @param useHttps does connection use HTTPS? - * @param allowSelfSignedCerts are self-signed certificates allow - * - * @return a Bus Topic Base - * @throws IllegalArgumentException if invalid parameters are present - */ - public BusTopicBase(List<String> servers, - String topic, - String apiKey, - String apiSecret, - boolean useHttps, - boolean allowSelfSignedCerts) { - - super(servers, topic); - - this.apiKey = apiKey; - this.apiSecret = apiSecret; - this.useHttps = useHttps; - this.allowSelfSignedCerts = allowSelfSignedCerts; - } - - @Override - public String getApiKey() { - return apiKey; - } - - @Override - public String getApiSecret() { - return apiSecret; - } - - /** - * @return if using https - */ - public boolean isUseHttps(){ - return useHttps; - } - - /** - * @return if self signed certificates are allowed - */ - public boolean isAllowSelfSignedCerts(){ - return allowSelfSignedCerts; - } - - protected boolean anyNullOrEmpty(String... args) { - for (String arg : args) { - if (arg == null || arg.isEmpty()) { - return true; - } - } - - return false; - } - - protected boolean allNullOrEmpty(String... args) { - for (String arg : args) { - if (!(arg == null || arg.isEmpty())) { - return false; - } - } - - return true; - } - - - @Override - public String toString() { - return "BusTopicBase [apiKey=" + apiKey + ", apiSecret=" + apiSecret + ", useHttps=" + useHttps - + ", allowSelfSignedCerts=" + allowSelfSignedCerts + ", toString()=" + super.toString() + "]"; - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/InlineBusTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/InlineBusTopicSink.java deleted file mode 100644 index a50d7b10..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/InlineBusTopicSink.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus.internal; - -import java.util.List; -import java.util.UUID; - -import org.onap.policy.drools.event.comm.bus.BusTopicSink; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -/** - * Transport Agnostic Bus Topic Sink to carry out the core functionality - * to interact with a sink regardless if it is UEB or DMaaP. - * - */ -public abstract class InlineBusTopicSink extends BusTopicBase implements BusTopicSink { - - /** - * loggers - */ - private static Logger logger = LoggerFactory.getLogger(InlineBusTopicSink.class); - private static final Logger netLogger = LoggerFactory.getLogger(NETWORK_LOGGER); - - /** - * The partition key to publish to - */ - protected String partitionId; - - /** - * message bus publisher - */ - protected BusPublisher publisher; - - /** - * constructor for abstract sink - * - * @param servers servers - * @param topic topic - * @param apiKey api secret - * @param apiSecret api secret - * @param partitionId partition id - * @param useHttps does connection use HTTPS? - * @param allowSelfSignedCerts are self-signed certificates allow - * @throws IllegalArgumentException in invalid parameters are passed in - */ - public InlineBusTopicSink(List<String> servers, String topic, - String apiKey, String apiSecret, String partitionId, boolean useHttps, boolean allowSelfSignedCerts) { - - super(servers, topic, apiKey, apiSecret, useHttps, allowSelfSignedCerts); - - if (partitionId == null || partitionId.isEmpty()) { - this.partitionId = UUID.randomUUID ().toString(); - } - } - - /** - * Initialize the Bus publisher - */ - public abstract void init(); - - /** - * {@inheritDoc} - */ - @Override - public boolean start() { - logger.info("{}: starting", this); - - synchronized(this) { - - if (this.alive) - return true; - - if (locked) - throw new IllegalStateException(this + " is locked."); - - this.alive = true; - } - - this.init(); - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean stop() { - - BusPublisher publisherCopy; - synchronized(this) { - this.alive = false; - publisherCopy = this.publisher; - this.publisher = null; - } - - if (publisherCopy != null) { - try { - publisherCopy.close(); - } catch (Exception e) { - logger.warn("{}: cannot stop publisher because of {}", - this, e.getMessage(), e); - } - } else { - logger.warn("{}: there is no publisher", this); - return false; - } - - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean send(String message) { - - if (message == null || message.isEmpty()) { - throw new IllegalArgumentException("Message to send is empty"); - } - - if (!this.alive) { - throw new IllegalStateException(this + " is stopped"); - } - - try { - synchronized (this) { - this.recentEvents.add(message); - } - - netLogger.info("[OUT|{}|{}]{}{}", this.getTopicCommInfrastructure(), - this.topic, System.lineSeparator(), message); - - publisher.send(this.partitionId, message); - broadcast(message); - } catch (Exception e) { - logger.warn("{}: cannot send because of {}", this, e.getMessage(), e); - return false; - } - - return true; - } - - - /** - * {@inheritDoc} - */ - @Override - public void setPartitionKey(String partitionKey) { - this.partitionId = partitionKey; - } - - /** - * {@inheritDoc} - */ - @Override - public String getPartitionKey() { - return this.partitionId; - } - - /** - * {@inheritDoc} - */ - @Override - public void shutdown() { - this.stop(); - } - - protected boolean anyNullOrEmpty(String... args) { - for (String arg : args) { - if (arg == null || arg.isEmpty()) { - return true; - } - } - - return false; - } - - protected boolean allNullOrEmpty(String... args) { - for (String arg : args) { - if (!(arg == null || arg.isEmpty())) { - return false; - } - } - - return true; - } - - - @Override - public String toString() { - return "InlineBusTopicSink [partitionId=" + partitionId + ", alive=" + alive + ", publisher=" + publisher + "]"; - } -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/InlineDmaapTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/InlineDmaapTopicSink.java deleted file mode 100644 index 48116e34..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/InlineDmaapTopicSink.java +++ /dev/null @@ -1,144 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus.internal; - -import java.util.List; -import java.util.Map; - -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; -import org.onap.policy.drools.event.comm.Topic; -import org.onap.policy.drools.event.comm.bus.DmaapTopicSink; - -/** - * This implementation publishes events for the associated DMAAP topic, - * inline with the calling thread. - */ -public class InlineDmaapTopicSink extends InlineBusTopicSink implements DmaapTopicSink { - - protected static Logger logger = - LoggerFactory.getLogger(InlineDmaapTopicSink.class); - - protected final String userName; - protected final String password; - - protected String environment = null; - protected String aftEnvironment = null; - protected String partner = null; - protected String latitude = null; - protected String longitude = null; - - protected Map<String,String> additionalProps = null; - - /** - * - * @param servers DMaaP servers - * @param topic DMaaP Topic to be monitored - * @param apiKey DMaaP API Key (optional) - * @param apiSecret DMaaP API Secret (optional) - * @param consumerGroup DMaaP Reader Consumer Group - * @param consumerInstance DMaaP Reader Instance - * @param fetchTimeout DMaaP fetch timeout - * @param fetchLimit DMaaP fetch limit - * @param environment DME2 Environment - * @param aftEnvironment DME2 AFT Environment - * @param partner DME2 Partner - * @param latitude DME2 Latitude - * @param longitude DME2 Longitude - * @param additionalProps Additional properties to pass to DME2 - * @param useHttps does connection use HTTPS? - * @param allowSelfSignedCerts are self-signed certificates allow - * - * @throws IllegalArgumentException An invalid parameter passed in - */ - public InlineDmaapTopicSink(List<String> servers, String topic, - String apiKey, String apiSecret, - String userName, String password, - String partitionKey, - String environment, String aftEnvironment, String partner, - String latitude, String longitude, Map<String,String> additionalProps, - boolean useHttps, boolean allowSelfSignedCerts) { - - super(servers, topic, apiKey, apiSecret, partitionKey, useHttps, allowSelfSignedCerts); - - this.userName = userName; - this.password = password; - - this.environment = environment; - this.aftEnvironment = aftEnvironment; - this.partner = partner; - - this.latitude = latitude; - this.longitude = longitude; - - this.additionalProps = additionalProps; - } - - public InlineDmaapTopicSink(List<String> servers, String topic, - String apiKey, String apiSecret, - String userName, String password, - String partitionKey, boolean useHttps, boolean allowSelfSignedCerts) { - - super(servers, topic, apiKey, apiSecret, partitionKey, useHttps, allowSelfSignedCerts); - - this.userName = userName; - this.password = password; - } - - - @Override - public void init() { - if (allNullOrEmpty(this.environment, this.aftEnvironment, this.latitude, this.longitude, this.partner)) { - this.publisher = - new BusPublisher.CambriaPublisherWrapper(this.servers, - this.topic, - this.apiKey, this.apiSecret, - this.userName, this.password, - this.useHttps); - } else { - this.publisher = - new BusPublisher.DmaapDmePublisherWrapper(this.servers, this.topic, - this.userName, this.password, - this.environment, this.aftEnvironment, - this.partner, this.latitude, this.longitude, - this.additionalProps, this.useHttps); - } - - logger.info("{}: DMAAP SINK created", this); - } - - /** - * {@inheritDoc} - */ - @Override - public CommInfrastructure getTopicCommInfrastructure() { - return Topic.CommInfrastructure.DMAAP; - } - - - @Override - public String toString() { - return "InlineDmaapTopicSink [userName=" + userName + ", password=" + password - + ", getTopicCommInfrastructure()=" + getTopicCommInfrastructure() + ", toString()=" - + super.toString() + "]"; - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/InlineUebTopicSink.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/InlineUebTopicSink.java deleted file mode 100644 index d1218f3f..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/InlineUebTopicSink.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus.internal; - -import java.util.List; - -import org.onap.policy.drools.event.comm.Topic; -import org.onap.policy.drools.event.comm.bus.UebTopicSink; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -/** - * This implementation publishes events for the associated UEB topic, - * inline with the calling thread. - */ -public class InlineUebTopicSink extends InlineBusTopicSink implements UebTopicSink { - - /** - * logger - */ - private static Logger logger = LoggerFactory.getLogger(InlineUebTopicSink.class); - - /** - * Argument-based UEB Topic Writer instantiation - * - * @param servers list of UEB servers available for publishing - * @param topic the topic to publish to - * @param apiKey the api key (optional) - * @param apiSecret the api secret (optional) - * @param partitionId the partition key (optional, autogenerated if not provided) - * @param useHttps does connection use HTTPS? - * @param allowSelfSignedCerts are self-signed certificates allow - * - * @throws IllegalArgumentException if invalid arguments are detected - */ - public InlineUebTopicSink(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String partitionId, - boolean useHttps, - boolean allowSelfSignedCerts) { - super(servers, topic, apiKey, apiSecret, partitionId, useHttps, allowSelfSignedCerts); - } - - /** - * Instantiation of internal resources - */ - @Override - public void init() { - - this.publisher = - new BusPublisher.CambriaPublisherWrapper(this.servers, - this.topic, - this.apiKey, - this.apiSecret, - this.useHttps); - logger.info("{}: UEB SINK created", this); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("InlineUebTopicSink [getTopicCommInfrastructure()=").append(getTopicCommInfrastructure()) - .append(", toString()=").append(super.toString()).append("]"); - return builder.toString(); - } - - /** - * {@inheritDoc} - */ - @Override - public CommInfrastructure getTopicCommInfrastructure() { - return Topic.CommInfrastructure.UEB; - } -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedBusTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedBusTopicSource.java deleted file mode 100644 index 768046d0..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedBusTopicSource.java +++ /dev/null @@ -1,332 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus.internal; - -import java.net.MalformedURLException; -import java.util.List; -import java.util.UUID; -import org.onap.policy.drools.event.comm.FilterableTopicSource; -import org.onap.policy.drools.event.comm.TopicListener; -import org.onap.policy.drools.event.comm.bus.BusTopicSource; -import org.onap.policy.drools.event.comm.bus.internal.BusConsumer.FilterableBusConsumer; -import org.onap.policy.drools.utils.NetworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This topic source implementation specializes in reading messages - * over a bus topic source and notifying its listeners - */ -public abstract class SingleThreadedBusTopicSource - extends BusTopicBase - implements Runnable, BusTopicSource, FilterableTopicSource { - - /** - * Not to be converted to PolicyLogger. - * This will contain all instract /out traffic and only that in a single file in a concise format. - */ - private static Logger logger = LoggerFactory.getLogger(InlineBusTopicSink.class); - private static final Logger netLogger = LoggerFactory.getLogger(NETWORK_LOGGER); - - /** - * Bus consumer group - */ - protected final String consumerGroup; - - /** - * Bus consumer instance - */ - protected final String consumerInstance; - - /** - * Bus fetch timeout - */ - protected final int fetchTimeout; - - /** - * Bus fetch limit - */ - protected final int fetchLimit; - - /** - * Message Bus Consumer - */ - protected BusConsumer consumer; - - /** - * Independent thread reading message over my topic - */ - protected Thread busPollerThread; - - - /** - * - * @param servers Bus servers - * @param topic Bus Topic to be monitored - * @param apiKey Bus API Key (optional) - * @param apiSecret Bus API Secret (optional) - * @param consumerGroup Bus Reader Consumer Group - * @param consumerInstance Bus Reader Instance - * @param fetchTimeout Bus fetch timeout - * @param fetchLimit Bus fetch limit - * @param useHttps does the bus use https - * @param allowSelfSignedCerts are self-signed certificates allowed - * @throws IllegalArgumentException An invalid parameter passed in - */ - public SingleThreadedBusTopicSource(List<String> servers, - String topic, - String apiKey, - String apiSecret, - String consumerGroup, - String consumerInstance, - int fetchTimeout, - int fetchLimit, - boolean useHttps, - boolean allowSelfSignedCerts) { - - super(servers, topic, apiKey, apiSecret, useHttps, allowSelfSignedCerts); - - if (consumerGroup == null || consumerGroup.isEmpty()) { - this.consumerGroup = UUID.randomUUID ().toString(); - } else { - this.consumerGroup = consumerGroup; - } - - if (consumerInstance == null || consumerInstance.isEmpty()) { - this.consumerInstance = NetworkUtil.getHostname(); - } else { - this.consumerInstance = consumerInstance; - } - - if (fetchTimeout <= 0) { - this.fetchTimeout = NO_TIMEOUT_MS_FETCH; - } else { - this.fetchTimeout = fetchTimeout; - } - - if (fetchLimit <= 0) { - this.fetchLimit = NO_LIMIT_FETCH; - } else { - this.fetchLimit = fetchLimit; - } - - } - - /** - * Initialize the Bus client - */ - public abstract void init() throws MalformedURLException; - - @Override - public void register(TopicListener topicListener) { - - super.register(topicListener); - - try { - if (!alive && !locked) - this.start(); - else - logger.info("{}: register: start not attempted", this); - } catch (Exception e) { - logger.warn("{}: cannot start after registration of because of: {}", - this, topicListener, e.getMessage(), e); - } - } - - @Override - public void unregister(TopicListener topicListener) { - boolean stop; - synchronized (this) { - super.unregister(topicListener); - stop = this.topicListeners.isEmpty(); - } - - if (stop) { - this.stop(); - } - } - - @Override - public boolean start() { - logger.info("{}: starting", this); - - synchronized(this) { - - if (alive) - return true; - - if (locked) - throw new IllegalStateException(this + " is locked."); - - if (this.busPollerThread == null || - !this.busPollerThread.isAlive() || - this.consumer == null) { - - try { - this.init(); - this.alive = true; - this.busPollerThread = new Thread(this); - this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic()); - busPollerThread.start(); - } catch (Exception e) { - logger.warn("{}: cannot start because of {}", this, e.getMessage(), e); - throw new IllegalStateException(e); - } - } - } - - return this.alive; - } - - @Override - public boolean stop() { - logger.info("{}: stopping", this); - - synchronized(this) { - BusConsumer consumerCopy = this.consumer; - - this.alive = false; - this.consumer = null; - - if (consumerCopy != null) { - try { - consumerCopy.close(); - } catch (Exception e) { - logger.warn("{}: stop failed because of {}", this, e.getMessage(), e); - } - } - } - - Thread.yield(); - - return true; - } - - /** - * Run thread method for the Bus Reader - */ - @Override - public void run() { - while (this.alive) { - try { - for (String event: this.consumer.fetch()) { - synchronized (this) { - this.recentEvents.add(event); - } - - netLogger.info("[IN|{}|{}]{}{}", - this.getTopicCommInfrastructure(), this.topic, - System.lineSeparator(), event); - - broadcast(event); - - if (!this.alive) - break; - } - } catch (Exception e) { - logger.error("{}: cannot fetch because of ", this, e.getMessage(), e); - } - } - - logger.info("{}: exiting thread", this); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean offer(String event) { - if (!this.alive) { - throw new IllegalStateException(this + " is not alive."); - } - - synchronized (this) { - this.recentEvents.add(event); - } - - netLogger.info("[IN|{}|{}]{}{}",this.getTopicCommInfrastructure(),this.topic, - System.lineSeparator(), event); - - - return broadcast(event); - } - - - @Override - public void setFilter(String filter) { - if(consumer instanceof FilterableBusConsumer) { - ((FilterableBusConsumer) consumer).setFilter(filter); - - } else { - throw new UnsupportedOperationException("no server-side filtering for topic " + topic); - } - } - - @Override - public String toString() { - return "SingleThreadedBusTopicSource [consumerGroup=" + consumerGroup + ", consumerInstance=" + consumerInstance - + ", fetchTimeout=" + fetchTimeout + ", fetchLimit=" + fetchLimit + ", consumer=" - + this.consumer + ", alive=" + alive + ", locked=" + locked + ", uebThread=" + busPollerThread - + ", topicListeners=" + topicListeners.size() + ", toString()=" + super.toString() + "]"; - } - - /** - * {@inheritDoc} - */ - @Override - public String getConsumerGroup() { - return consumerGroup; - } - - /** - * {@inheritDoc} - */ - @Override - public String getConsumerInstance() { - return consumerInstance; - } - - /** - * {@inheritDoc} - */ - @Override - public void shutdown() { - this.stop(); - this.topicListeners.clear(); - } - - /** - * {@inheritDoc} - */ - @Override - public int getFetchTimeout() { - return fetchTimeout; - } - - /** - * {@inheritDoc} - */ - @Override - public int getFetchLimit() { - return fetchLimit; - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedDmaapTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedDmaapTopicSource.java deleted file mode 100644 index 6a9a2d6d..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedDmaapTopicSource.java +++ /dev/null @@ -1,197 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus.internal; - -import java.net.MalformedURLException; -import java.util.List; -import java.util.Map; - -import org.onap.policy.drools.event.comm.Topic; -import org.onap.policy.drools.event.comm.bus.DmaapTopicSource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This topic reader implementation specializes in reading messages - * over DMAAP topic and notifying its listeners - */ -public class SingleThreadedDmaapTopicSource extends SingleThreadedBusTopicSource - implements DmaapTopicSource, Runnable { - - private static Logger logger = LoggerFactory.getLogger(SingleThreadedDmaapTopicSource.class); - - - protected final String userName; - protected final String password; - - protected String environment = null; - protected String aftEnvironment = null; - protected String partner = null; - protected String latitude = null; - protected String longitude = null; - - protected Map<String,String> additionalProps = null; - - - /** - * - * @param servers DMaaP servers - * @param topic DMaaP Topic to be monitored - * @param apiKey DMaaP API Key (optional) - * @param apiSecret DMaaP API Secret (optional) - * @param consumerGroup DMaaP Reader Consumer Group - * @param consumerInstance DMaaP Reader Instance - * @param fetchTimeout DMaaP fetch timeout - * @param fetchLimit DMaaP fetch limit - * @param environment DME2 Environment - * @param aftEnvironment DME2 AFT Environment - * @param partner DME2 Partner - * @param latitude DME2 Latitude - * @param longitude DME2 Longitude - * @param additionalProps Additional properties to pass to DME2 - * @param useHttps does connection use HTTPS? - * @param allowSelfSignedCerts are self-signed certificates allow - * - * @throws IllegalArgumentException An invalid parameter passed in - */ - public SingleThreadedDmaapTopicSource(List<String> servers, String topic, - String apiKey, String apiSecret, - String userName, String password, - String consumerGroup, String consumerInstance, - int fetchTimeout, int fetchLimit, - String environment, String aftEnvironment, String partner, - String latitude, String longitude, Map<String,String> additionalProps, - boolean useHttps, boolean allowSelfSignedCerts) { - - super(servers, topic, apiKey, apiSecret, - consumerGroup, consumerInstance, - fetchTimeout, fetchLimit, useHttps,allowSelfSignedCerts); - - this.userName = userName; - this.password = password; - - this.environment = environment; - this.aftEnvironment = aftEnvironment; - this.partner = partner; - - this.latitude = latitude; - this.longitude = longitude; - - this.additionalProps = additionalProps; - try { - this.init(); - } catch (Exception e) { - logger.error("ERROR during init of topic {}", this.topic); - throw new IllegalArgumentException(e); - } - } - - /** - * - * @param servers DMaaP servers - * @param topic DMaaP Topic to be monitored - * @param apiKey DMaaP API Key (optional) - * @param apiSecret DMaaP API Secret (optional) - * @param consumerGroup DMaaP Reader Consumer Group - * @param consumerInstance DMaaP Reader Instance - * @param fetchTimeout DMaaP fetch timeout - * @param fetchLimit DMaaP fetch limit - * @param useHttps does connection use HTTPS? - * @param allowSelfSignedCerts are self-signed certificates allow - * @throws IllegalArgumentException An invalid parameter passed in - */ - public SingleThreadedDmaapTopicSource(List<String> servers, String topic, - String apiKey, String apiSecret, - String userName, String password, - String consumerGroup, String consumerInstance, - int fetchTimeout, int fetchLimit, boolean useHttps, boolean allowSelfSignedCerts) { - - - super(servers, topic, apiKey, apiSecret, - consumerGroup, consumerInstance, - fetchTimeout, fetchLimit, useHttps, allowSelfSignedCerts); - - this.userName = userName; - this.password = password; - - try { - this.init(); - } catch (Exception e) { - logger.warn("dmaap-source: cannot create topic {} because of {}", topic, e.getMessage(), e); - throw new IllegalArgumentException(e); - } - } - - - /** - * Initialize the Cambria or MR Client - */ - @Override - public void init() throws MalformedURLException { - if (anyNullOrEmpty(this.userName, this.password)) { - this.consumer = - new BusConsumer.CambriaConsumerWrapper(this.servers, this.topic, - this.apiKey, this.apiSecret, - this.consumerGroup, this.consumerInstance, - this.fetchTimeout, this.fetchLimit, - this.useHttps, this.allowSelfSignedCerts); - } else if (allNullOrEmpty(this.environment, this.aftEnvironment, this.latitude, this.longitude, this.partner)) { - this.consumer = - new BusConsumer.CambriaConsumerWrapper(this.servers, this.topic, - this.apiKey, this.apiSecret, - this.userName, this.password, - this.consumerGroup, this.consumerInstance, - this.fetchTimeout, this.fetchLimit, - this.useHttps, this.allowSelfSignedCerts); - } else { - this.consumer = - new BusConsumer.DmaapDmeConsumerWrapper(this.servers, this.topic, - this.apiKey, this.apiSecret, - this.userName, this.password, - this.consumerGroup, this.consumerInstance, - this.fetchTimeout, this.fetchLimit, - this.environment, this.aftEnvironment, this.partner, - this.latitude, this.longitude, this.additionalProps, this.useHttps); - } - - logger.info("{}: INITTED", this); - } - - /** - * {@inheritDoc} - */ - @Override - public CommInfrastructure getTopicCommInfrastructure() { - return Topic.CommInfrastructure.DMAAP; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("SingleThreadedDmaapTopicSource [userName=").append(userName).append(", password=") - .append((password == null || password.isEmpty()) ? "-" : password.length()) - .append(", getTopicCommInfrastructure()=").append(getTopicCommInfrastructure()) - .append(", toString()=").append(super.toString()).append("]"); - return builder.toString(); - } - - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedUebTopicSource.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedUebTopicSource.java deleted file mode 100644 index fcbee631..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/SingleThreadedUebTopicSource.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus.internal; - -import java.util.List; - -import org.onap.policy.drools.event.comm.Topic; -import org.onap.policy.drools.event.comm.bus.UebTopicSource; - -/** - * This topic source implementation specializes in reading messages - * over an UEB Bus topic source and notifying its listeners - */ -public class SingleThreadedUebTopicSource extends SingleThreadedBusTopicSource - implements UebTopicSource { - - /** - * - * @param servers UEB servers - * @param topic UEB Topic to be monitored - * @param apiKey UEB API Key (optional) - * @param apiSecret UEB API Secret (optional) - * @param consumerGroup UEB Reader Consumer Group - * @param consumerInstance UEB Reader Instance - * @param fetchTimeout UEB fetch timeout - * @param fetchLimit UEB fetch limit - * @param useHttps does topicSource use HTTPS? - * @param allowSelfSignedCerts does topicSource allow self-signed certs? - * - * @throws IllegalArgumentException An invalid parameter passed in - */ - - - public SingleThreadedUebTopicSource(List<String> servers, String topic, - String apiKey, String apiSecret, - String consumerGroup, String consumerInstance, - int fetchTimeout, int fetchLimit, boolean useHttps, boolean allowSelfSignedCerts) { - - super(servers, topic, apiKey, apiSecret, - consumerGroup, consumerInstance, - fetchTimeout, fetchLimit, useHttps, allowSelfSignedCerts); - - this.allowSelfSignedCerts = allowSelfSignedCerts; - - this.init(); - } - - /** - * Initialize the Cambria client - */ - @Override - public void init() { - this.consumer = - new BusConsumer.CambriaConsumerWrapper(this.servers, this.topic, - this.apiKey, this.apiSecret, - this.consumerGroup, this.consumerInstance, - this.fetchTimeout, this.fetchLimit, this.useHttps, this.allowSelfSignedCerts); - } - - /** - * {@inheritDoc} - */ - @Override - public CommInfrastructure getTopicCommInfrastructure() { - return Topic.CommInfrastructure.UEB; - } - - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("SingleThreadedUebTopicSource [getTopicCommInfrastructure()=") - .append(getTopicCommInfrastructure()).append(", toString()=").append(super.toString()).append("]"); - return builder.toString(); - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/TopicBase.java b/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/TopicBase.java deleted file mode 100644 index 22c6b1d5..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/event/comm/bus/internal/TopicBase.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.event.comm.bus.internal; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.collections4.queue.CircularFifoQueue; -import org.onap.policy.drools.event.comm.Topic; -import org.onap.policy.drools.event.comm.TopicListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class TopicBase implements Topic { - - /** - * logger - */ - private static Logger logger = LoggerFactory.getLogger(TopicBase.class); - - /** - * list of servers - */ - protected List<String> servers; - - /** - * Topic - */ - protected String topic; - - /** - * event cache - */ - protected CircularFifoQueue<String> recentEvents = new CircularFifoQueue<>(10); - - /** - * Am I running? - * reflects invocation of start()/stop() - * !locked & start() => alive - * stop() => !alive - */ - protected volatile boolean alive = false; - - /** - * Am I locked? - * reflects invocation of lock()/unlock() operations - * locked => !alive (but not in the other direction necessarily) - * locked => !offer, !run, !start, !stop (but this last one is obvious - * since locked => !alive) - */ - protected volatile boolean locked = false; - - /** - * All my subscribers for new message notifications - */ - protected final ArrayList<TopicListener> topicListeners = new ArrayList<>(); - - /** - * Instantiates a new Topic Base - * - * @param servers list of servers - * @param topic topic name - * - * @return a Topic Base - * @throws IllegalArgumentException if invalid parameters are present - */ - public TopicBase(List<String> servers, String topic) { - - if (servers == null || servers.isEmpty()) { - throw new IllegalArgumentException("Server(s) must be provided"); - } - - if (topic == null || topic.isEmpty()) { - throw new IllegalArgumentException("A Topic must be provided"); - } - - this.servers = servers; - this.topic = topic; - } - - @Override - public void register(TopicListener topicListener) { - - logger.info("{}: registering {}", this, topicListener); - - synchronized(this) { - if (topicListener == null) - throw new IllegalArgumentException("TopicListener must be provided"); - - for (TopicListener listener: this.topicListeners) { - if (listener == topicListener) return; - } - - this.topicListeners.add(topicListener); - } - } - - @Override - public void unregister(TopicListener topicListener) { - - logger.info("{}: unregistering {}", this, topicListener); - - synchronized (this) { - if (topicListener == null) - throw new IllegalArgumentException("TopicListener must be provided"); - - this.topicListeners.remove(topicListener); - } - } - - /** - * broadcast event to all listeners - * - * @param message the event - * @return true if all notifications are performed with no error, false otherwise - */ - protected boolean broadcast(String message) { - List<TopicListener> snapshotListeners = this.snapshotTopicListeners(); - - boolean success = true; - for (TopicListener topicListener: snapshotListeners) { - try { - topicListener.onTopicEvent(this.getTopicCommInfrastructure(), this.topic, message); - } catch (Exception e) { - logger.warn("{}: notification error @ {} because of {}", - this, topicListener, e.getMessage(), e); - success = false; - } - } - return success; - } - - /** - * take a snapshot of current topic listeners - * - * @return the topic listeners - */ - protected synchronized List<TopicListener> snapshotTopicListeners() { - @SuppressWarnings("unchecked") - List<TopicListener> listeners = (List<TopicListener>) topicListeners.clone(); - return listeners; - } - - @Override - public boolean lock() { - - logger.info("{}: locking", this); - - synchronized (this) { - if (this.locked) - return true; - - this.locked = true; - } - - return this.stop(); - } - - @Override - public boolean unlock() { - logger.info("{}: unlocking", this); - - synchronized(this) { - if (!this.locked) - return true; - - this.locked = false; - } - - try { - return this.start(); - } catch (Exception e) { - logger.warn("{}: cannot after unlocking because of {}", this, e.getMessage(), e); - return false; - } - } - - @Override - public boolean isLocked() { - return this.locked; - } - - @Override - public String getTopic() { - return topic; - } - - @Override - public boolean isAlive() { - return this.alive; - } - - @Override - public List<String> getServers() { - return servers; - } - - @Override - public synchronized String[] getRecentEvents() { - String[] events = new String[recentEvents.size()]; - return recentEvents.toArray(events); - } - - - @Override - public String toString() { - return "TopicBase [servers=" + servers + ", topic=" + topic + ", #recentEvents=" + recentEvents.size() + ", locked=" - + locked + ", #topicListeners=" + topicListeners.size() + "]"; - } -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/HttpClient.java b/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/HttpClient.java deleted file mode 100644 index e5becdf4..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/HttpClient.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.http.client; - -import javax.ws.rs.core.Response; - -import org.onap.policy.drools.properties.Startable; - -public interface HttpClient extends Startable { - - public Response get(String path); - - public Response get(); - - public static <T> T getBody(Response response, Class<T> entityType) { - return response.readEntity(entityType); - } - - public String getName(); - public boolean isHttps(); - public boolean isSelfSignedCerts(); - public String getHostname(); - public int getPort(); - public String getBasePath(); - public String getUserName(); - public String getPassword(); - public String getBaseUrl(); - - - public static final HttpClientFactory factory = new IndexedHttpClientFactory(); -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/HttpClientFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/HttpClientFactory.java deleted file mode 100644 index 1094a2fb..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/HttpClientFactory.java +++ /dev/null @@ -1,221 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.http.client; - -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; - -import org.onap.policy.drools.http.client.internal.JerseyClient; -import org.onap.policy.drools.properties.PolicyProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Http Client Factory - */ -public interface HttpClientFactory { - - /** - * build and http client with the following parameters - */ - public HttpClient build(String name, boolean https, - boolean selfSignedCerts, - String hostname, int port, - String baseUrl, String userName, - String password, boolean managed) - throws KeyManagementException, NoSuchAlgorithmException; - - /** - * build http client from properties - */ - public List<HttpClient> build(Properties properties) - throws KeyManagementException, NoSuchAlgorithmException; - - /** - * get http client - * @param name the name - * @return the http client - */ - public HttpClient get(String name); - - /** - * list of http clients - * @return http clients - */ - public List<HttpClient> inventory(); - - /** - * destroy by name - * @param name name - */ - public void destroy(String name); - - public void destroy(); -} - -/** - * http client factory implementation indexed by name - */ -class IndexedHttpClientFactory implements HttpClientFactory { - - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(IndexedHttpClientFactory.class); - - protected HashMap<String, HttpClient> clients = new HashMap<>(); - - @Override - public synchronized HttpClient build(String name, boolean https, boolean selfSignedCerts, - String hostname, int port, - String baseUrl, String userName, String password, - boolean managed) - throws KeyManagementException, NoSuchAlgorithmException { - if (clients.containsKey(name)) - return clients.get(name); - - JerseyClient client = - new JerseyClient(name, https, selfSignedCerts, hostname, port, baseUrl, userName, password); - - if (managed) - clients.put(name, client); - - return client; - } - - @Override - public synchronized List<HttpClient> build(Properties properties) - throws KeyManagementException, NoSuchAlgorithmException { - ArrayList<HttpClient> clientList = new ArrayList<>(); - - String clientNames = properties.getProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES); - if (clientNames == null || clientNames.isEmpty()) { - return clientList; - } - - List<String> clientNameList = - new ArrayList<>(Arrays.asList(clientNames.split("\\s*,\\s*"))); - - for (String clientName : clientNameList) { - String httpsString = properties.getProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + - clientName + - PolicyProperties.PROPERTY_HTTP_HTTPS_SUFFIX); - boolean https = false; - if (httpsString != null && !httpsString.isEmpty()) { - https = Boolean.parseBoolean(httpsString); - } - - String hostName = properties.getProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + - clientName + - PolicyProperties.PROPERTY_HTTP_HOST_SUFFIX); - - String servicePortString = properties.getProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + - clientName + - PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX); - int port; - try { - if (servicePortString == null || servicePortString.isEmpty()) { - continue; - } - port = Integer.parseInt(servicePortString); - } catch (NumberFormatException nfe) { - logger.error("http-client-factory: cannot parse port {}", servicePortString, nfe); - continue; - } - - String baseUrl = properties.getProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + - clientName + - PolicyProperties.PROPERTY_HTTP_URL_SUFFIX); - - String userName = properties.getProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + - clientName + - PolicyProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX); - - String password = properties.getProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + - clientName + - PolicyProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX); - - String managedString = properties.getProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + - clientName + - PolicyProperties.PROPERTY_MANAGED_SUFFIX); - boolean managed = true; - if (managedString != null && !managedString.isEmpty()) { - managed = Boolean.parseBoolean(managedString); - } - - try { - HttpClient client = - this.build(clientName, https, https, hostName, port, baseUrl, - userName, password, managed); - clientList.add(client); - } catch (Exception e) { - logger.error("http-client-factory: cannot build client {}", clientName, e); - } - } - - return clientList; - } - - @Override - public synchronized HttpClient get(String name) { - if (clients.containsKey(name)) { - return clients.get(name); - } - - throw new IllegalArgumentException("Http Client " + name + " not found"); - } - - @Override - public synchronized List<HttpClient> inventory() { - return new ArrayList<>(this.clients.values()); - } - - @Override - public synchronized void destroy(String name) { - if (!clients.containsKey(name)) { - return; - } - - HttpClient client = clients.remove(name); - try { - client.shutdown(); - } catch (IllegalStateException e) { - logger.error("http-client-factory: cannot shutdown client {}", client, e); - } - } - - @Override - public void destroy() { - List<HttpClient> clientsInventory = this.inventory(); - for (HttpClient client: clientsInventory) { - client.shutdown(); - } - - synchronized(this) { - this.clients.clear(); - } - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/internal/JerseyClient.java b/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/internal/JerseyClient.java deleted file mode 100644 index 6a254e2e..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/http/client/internal/JerseyClient.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.http.client.internal; - -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.core.Response; -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import org.onap.policy.drools.http.client.HttpClient; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class JerseyClient implements HttpClient { - - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(JerseyClient.class); - - protected final String name; - protected final boolean https; - protected final boolean selfSignedCerts; - protected final String hostname; - protected final int port; - protected final String basePath; - protected final String userName; - protected final String password; - - protected final Client client; - protected final String baseUrl; - - protected boolean alive = true; - - - public JerseyClient(String name, boolean https, - boolean selfSignedCerts, - String hostname, int port, - String basePath, String userName, - String password) - throws KeyManagementException, NoSuchAlgorithmException { - - super(); - - if (name == null || name.isEmpty()) - throw new IllegalArgumentException("Name must be provided"); - - if (hostname == null || hostname.isEmpty()) - throw new IllegalArgumentException("Hostname must be provided"); - - if (port <= 0 && port >= 65535) - throw new IllegalArgumentException("Invalid Port provided: " + port); - - this.name = name; - this.https = https; - this.hostname = hostname; - this.port = port; - this.basePath = basePath; - this.userName = userName; - this.password = password; - this.selfSignedCerts = selfSignedCerts; - - StringBuilder tmpBaseUrl = new StringBuilder(); - if (this.https) { - tmpBaseUrl.append("https://"); - ClientBuilder clientBuilder; - SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); - if (this.selfSignedCerts) { - sslContext.init(null, new TrustManager[]{new X509TrustManager() { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - // always trusted - } - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - // always trusted - } - @Override - public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } - - }}, new SecureRandom()); - clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier((host,session) -> true); - } else { - sslContext.init(null, null, null); - clientBuilder = ClientBuilder.newBuilder().sslContext(sslContext); - } - this.client = clientBuilder.build(); - } else { - tmpBaseUrl.append("http://"); - this.client = ClientBuilder.newClient(); - } - - if (this.userName != null && !this.userName.isEmpty() && - this.password != null && !this.password.isEmpty()) { - HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basic(userName, password); - this.client.register(authFeature); - } - - this.baseUrl = tmpBaseUrl.append(this.hostname).append(":"). - append(this.port).append("/"). - append((this.basePath == null) ? "" : this.basePath). - toString(); - } - - @Override - public Response get(String path) { - if (path != null && !path.isEmpty()) - return this.client.target(this.baseUrl).path(path).request().get(); - else - return this.client.target(this.baseUrl).request().get(); - } - - @Override - public Response get() { - return this.client.target(this.baseUrl).request().get(); - } - - - @Override - public boolean start() { - return alive; - } - - @Override - public boolean stop() { - return !alive; - } - - @Override - public void shutdown() { - synchronized(this) { - alive = false; - } - - try { - this.client.close(); - } catch (Exception e) { - logger.warn("{}: cannot close because of {}", this, - e.getMessage(), e); - } - } - - @Override - public synchronized boolean isAlive() { - return this.alive; - } - - @Override - public String getName() { - return name; - } - - @Override - public boolean isHttps() { - return https; - } - - @Override - public boolean isSelfSignedCerts() { - return selfSignedCerts; - } - - @Override - public String getHostname() { - return hostname; - } - - @Override - public int getPort() { - return port; - } - - @Override - public String getBasePath() { - return basePath; - } - - @Override - public String getUserName() { - return userName; - } - - @JsonIgnore - @Override - public String getPassword() { - return password; - } - - @Override - public String getBaseUrl() { - return baseUrl; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("JerseyClient [name="); - builder.append(name); - builder.append(", https="); - builder.append(https); - builder.append(", selfSignedCerts="); - builder.append(selfSignedCerts); - builder.append(", hostname="); - builder.append(hostname); - builder.append(", port="); - builder.append(port); - builder.append(", basePath="); - builder.append(basePath); - builder.append(", userName="); - builder.append(userName); - builder.append(", password="); - builder.append(password); - builder.append(", client="); - builder.append(client); - builder.append(", baseUrl="); - builder.append(baseUrl); - builder.append(", alive="); - builder.append(alive); - builder.append("]"); - return builder.toString(); - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/HttpServletServer.java b/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/HttpServletServer.java deleted file mode 100644 index 3cd702ae..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/HttpServletServer.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.http.server; - -import org.onap.policy.drools.properties.Startable; - -/** - * A Jetty Server to server REST Requests - */ -public interface HttpServletServer extends Startable { - - - /** - * factory for managing and tracking DMAAP sources - */ - public static HttpServletServerFactory factory = new IndexedHttpServletServerFactory(); - - /** - * - * @return port - */ - public int getPort(); - - /** - * enables basic authentication with user and password on the the relative path relativeUriPath - * - * @param user - * @param password - * @param relativeUriPath - */ - public void setBasicAuthentication(String user, String password, String relativeUriPath); - - /** - * adds a JAX-RS servlet class to serve REST requests - * - * @param servletPath servlet path - * @param restClass JAX-RS API Class - * - * @throws IllegalArgumentException unable to process because of invalid input - * @throws IllegalStateException unable to process because of invalid state - */ - public void addServletClass(String servletPath, String restClass); - - /** - * adds a package containing JAX-RS classes to serve REST requests - * - * @param servletPath servlet path - * @param restPackage JAX-RS package to scan - * - * @throws IllegalArgumentException unable to process because of invalid input - * @throws IllegalStateException unable to process because of invalid state - */ - public void addServletPackage(String servletPath, String restPackage); - - /** - * blocking start of the http server - * - * @param maxWaitTime max time to wait for the start to take place - * @return true if start was successful - * - * @throws IllegalArgumentException if arguments are invalid - * @throws InterruptedException if the blocking operation is interrupted - */ - public boolean waitedStart(long maxWaitTime) throws InterruptedException; -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/HttpServletServerFactory.java b/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/HttpServletServerFactory.java deleted file mode 100644 index f4dc85bc..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/HttpServletServerFactory.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.http.server; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Properties; - -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; -import org.onap.policy.drools.http.server.internal.JettyJerseyServer; -import org.onap.policy.drools.properties.PolicyProperties; - -/** - * Factory of HTTP Servlet-Enabled Servlets - */ -public interface HttpServletServerFactory { - - /** - * builds an http server with support for servlets - * - * @param name name - * @param host binding host - * @param port port - * @param contextPath server base path - * @param swagger enable swagger documentation - * @param managed is it managed by infrastructure - * @return http server - * @throws IllegalArgumentException when invalid parameters are provided - */ - public HttpServletServer build(String name, String host, int port, String contextPath, - boolean swagger, boolean managed); - - /** - * list of http servers per properties - * - * @param properties properties based configuration - * @return list of http servers - * @throws IllegalArgumentException when invalid parameters are provided - */ - public List<HttpServletServer> build(Properties properties); - - /** - * gets a server based on the port - * - * @param port port - * @return http server - */ - public HttpServletServer get(int port); - - /** - * provides an inventory of servers - * - * @return inventory of servers - */ - public List<HttpServletServer> inventory(); - - /** - * destroys server bound to a port - * @param port - */ - public void destroy(int port); - - /** - * destroys the factory and therefore all servers - */ - public void destroy(); -} - -/** - * Indexed factory implementation - */ -class IndexedHttpServletServerFactory implements HttpServletServerFactory { - - private static final String SPACES_COMMA_SPACES = "\\s*,\\s*"; - - /** - * logger - */ - protected static Logger logger = LoggerFactory.getLogger(IndexedHttpServletServerFactory.class); - - /** - * servers index - */ - protected HashMap<Integer, HttpServletServer> servers = new HashMap<>(); - - @Override - public synchronized HttpServletServer build(String name, String host, int port, - String contextPath, boolean swagger, - boolean managed) { - - if (servers.containsKey(port)) - return servers.get(port); - - JettyJerseyServer server = new JettyJerseyServer(name, host, port, contextPath, swagger); - if (managed) - servers.put(port, server); - - return server; - } - - @Override - public synchronized List<HttpServletServer> build(Properties properties) { - - ArrayList<HttpServletServer> serviceList = new ArrayList<>(); - - String serviceNames = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES); - if (serviceNames == null || serviceNames.isEmpty()) { - logger.warn("No topic for HTTP Service: {}", properties); - return serviceList; - } - - List<String> serviceNameList = Arrays.asList(serviceNames.split(SPACES_COMMA_SPACES)); - - for (String serviceName : serviceNameList) { - String servicePortString = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX); - - int servicePort; - try { - if (servicePortString == null || servicePortString.isEmpty()) { - if (logger.isWarnEnabled()) - logger.warn("No HTTP port for service in {}", serviceName); - continue; - } - servicePort = Integer.parseInt(servicePortString); - } catch (NumberFormatException nfe) { - if (logger.isWarnEnabled()) - logger.warn("No HTTP port for service in {}", serviceName); - continue; - } - - String hostName = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_HTTP_HOST_SUFFIX); - - String contextUriPath = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_HTTP_CONTEXT_URIPATH_SUFFIX); - - String userName = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX); - - String password = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX); - - String authUriPath = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_HTTP_AUTH_URIPATH_SUFFIX); - - String restClasses = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX); - - String restPackages = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_HTTP_REST_PACKAGES_SUFFIX); - String restUriPath = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_HTTP_REST_URIPATH_SUFFIX); - - String managedString = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_MANAGED_SUFFIX); - boolean managed = true; - if (managedString != null && !managedString.isEmpty()) { - managed = Boolean.parseBoolean(managedString); - } - - String swaggerString = properties.getProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + - serviceName + - PolicyProperties.PROPERTY_HTTP_SWAGGER_SUFFIX); - boolean swagger = false; - if (swaggerString != null && !swaggerString.isEmpty()) { - swagger = Boolean.parseBoolean(swaggerString); - } - - HttpServletServer service = build(serviceName, hostName, servicePort, contextUriPath, swagger, managed); - if (userName != null && !userName.isEmpty() && password != null && !password.isEmpty()) { - service.setBasicAuthentication(userName, password, authUriPath); - } - - if (restClasses != null && !restClasses.isEmpty()) { - List<String> restClassesList = Arrays.asList(restClasses.split(SPACES_COMMA_SPACES)); - for (String restClass : restClassesList) - service.addServletClass(restUriPath, restClass); - } - - if (restPackages != null && !restPackages.isEmpty()) { - List<String> restPackageList = Arrays.asList(restPackages.split(SPACES_COMMA_SPACES)); - for (String restPackage : restPackageList) - service.addServletPackage(restUriPath, restPackage); - } - - serviceList.add(service); - } - - return serviceList; - } - - @Override - public synchronized HttpServletServer get(int port) { - - if (servers.containsKey(port)) { - return servers.get(port); - } - - throw new IllegalArgumentException("Http Server for " + port + " not found"); - } - - @Override - public synchronized List<HttpServletServer> inventory() { - return new ArrayList<>(this.servers.values()); - } - - @Override - public synchronized void destroy(int port) { - - if (!servers.containsKey(port)) { - return; - } - - HttpServletServer server = servers.remove(port); - server.shutdown(); - } - - @Override - public synchronized void destroy() { - List<HttpServletServer> httpServletServers = this.inventory(); - for (HttpServletServer server: httpServletServers) { - server.shutdown(); - } - - synchronized(this) { - this.servers.clear(); - } - } - -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/internal/JettyJerseyServer.java b/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/internal/JettyJerseyServer.java deleted file mode 100644 index 0cbd983d..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/internal/JettyJerseyServer.java +++ /dev/null @@ -1,249 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.http.server.internal; - -import java.util.HashMap; -import org.eclipse.jetty.servlet.ServletHolder; -import org.onap.policy.drools.utils.NetworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import io.swagger.jersey.config.JerseyJaxrsConfig; - -/** - * REST Jetty Server that uses Jersey Servlets to support JAX-RS Web Services - */ -public class JettyJerseyServer extends JettyServletServer { - - /** - * Swagger API Base Path - */ - protected static final String SWAGGER_API_BASEPATH = "swagger.api.basepath"; - - /** - * Swagger Context ID - */ - protected static final String SWAGGER_CONTEXT_ID = "swagger.context.id"; - - /** - * Swagger Scanner ID - */ - protected static final String SWAGGER_SCANNER_ID = "swagger.scanner.id"; - - /** - * Swagger Pretty Print - */ - protected static final String SWAGGER_PRETTY_PRINT = "swagger.pretty.print"; - - /** - * Swagger Packages - */ - protected static final String SWAGGER_INIT_PACKAGES_PARAM_VALUE = "io.swagger.jaxrs.listing"; - - /** - * Jersey Packages Init Param Name - */ - protected static final String JERSEY_INIT_PACKAGES_PARAM_NAME = "jersey.config.server.provider.packages"; - - /** - * Jersey Packages Init Param Value - */ - protected static final String JERSEY_INIT_PACKAGES_PARAM_VALUE = "com.fasterxml.jackson.jaxrs.json"; - - /** - * Jersey Classes Init Param Name - */ - protected static final String JERSEY_INIT_CLASSNAMES_PARAM_NAME = "jersey.config.server.provider.classnames"; - - /** - * Jersey Jackson Classes Init Param Value - */ - protected static final String JERSEY_JACKSON_INIT_CLASSNAMES_PARAM_VALUE = "com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider"; - - /** - * Jersey Swagger Classes Init Param Value - */ - protected static final String SWAGGER_INIT_CLASSNAMES_PARAM_VALUE = "io.swagger.jaxrs.listing.ApiListingResource," + - "io.swagger.jaxrs.listing.SwaggerSerializers"; - /** - * Logger - */ - protected static Logger logger = LoggerFactory.getLogger(JettyJerseyServer.class); - - /** - * Container for servlets - */ - protected HashMap<String, ServletHolder> servlets = new HashMap<>(); - - /** - * Swagger ID - */ - protected String swaggerId = null; - - /** - * Constructor - * - * @param name name - * @param host host server host - * @param port port server port - * @param swagger support swagger? - * @param contextPath context path - * - * @throws IllegalArgumentException in invalid arguments are provided - */ - public JettyJerseyServer(String name, String host, int port, String contextPath, boolean swagger) { - - super(name, host, port, contextPath); - if (swagger) { - this.swaggerId = "swagger-" + this.port; - attachSwaggerServlet(); - } - } - - /** - * attaches a swagger initialization servlet - */ - protected void attachSwaggerServlet() { - - ServletHolder swaggerServlet = context.addServlet(JerseyJaxrsConfig.class, "/"); - - String hostname = this.connector.getHost(); - if (hostname == null || hostname.isEmpty() || hostname.equals(NetworkUtil.IPv4_WILDCARD_ADDRESS)) { - hostname = NetworkUtil.getHostname(); - } - - swaggerServlet.setInitParameter(SWAGGER_API_BASEPATH, - "http://" + hostname + ":" + this.connector.getPort() + "/"); - swaggerServlet.setInitParameter(SWAGGER_CONTEXT_ID, swaggerId); - swaggerServlet.setInitParameter(SWAGGER_SCANNER_ID, swaggerId); - swaggerServlet.setInitParameter(SWAGGER_PRETTY_PRINT, "true"); - swaggerServlet.setInitOrder(2); - - if (logger.isDebugEnabled()) - logger.debug("{}: Swagger Servlet has been attached: {}", this, swaggerServlet.dump()); - } - - /** - * retrieves cached server based on servlet path - * - * @param servletPath servlet path - * @return the jetty servlet holder - * - * @throws IllegalArgumentException if invalid arguments are provided - */ - protected synchronized ServletHolder getServlet(String servletPath) { - - ServletHolder jerseyServlet = servlets.get(servletPath); - if (jerseyServlet == null) { - jerseyServlet = context.addServlet - (org.glassfish.jersey.servlet.ServletContainer.class, servletPath); - jerseyServlet.setInitOrder(0); - servlets.put(servletPath, jerseyServlet); - } - - return jerseyServlet; - } - - @Override - public synchronized void addServletPackage(String servletPath, String restPackage) { - String servPath = servletPath; - if (restPackage == null || restPackage.isEmpty()) - throw new IllegalArgumentException("No discoverable REST package provided"); - - if (servPath == null || servPath.isEmpty()) - servPath = "/*"; - - ServletHolder jerseyServlet = this.getServlet(servPath); - - String initClasses = - jerseyServlet.getInitParameter(JERSEY_INIT_CLASSNAMES_PARAM_NAME); - if (initClasses != null && !initClasses.isEmpty()) - logger.warn("Both packages and classes are used in Jetty+Jersey Configuration: {}", restPackage); - - String initPackages = - jerseyServlet.getInitParameter(JERSEY_INIT_PACKAGES_PARAM_NAME); - if (initPackages == null) { - if (this.swaggerId != null) { - initPackages = JERSEY_INIT_PACKAGES_PARAM_VALUE + "," + - SWAGGER_INIT_PACKAGES_PARAM_VALUE + "," + - restPackage; - - jerseyServlet.setInitParameter(SWAGGER_CONTEXT_ID, swaggerId); - jerseyServlet.setInitParameter(SWAGGER_SCANNER_ID, swaggerId); - } else { - initPackages = JERSEY_INIT_PACKAGES_PARAM_VALUE + "," + - restPackage; - } - } else { - initPackages = initPackages + "," + restPackage; - } - - jerseyServlet.setInitParameter(JERSEY_INIT_PACKAGES_PARAM_NAME, initPackages); - - if (logger.isDebugEnabled()) - logger.debug("{}: added REST package: {}", this, jerseyServlet.dump()); - } - - @Override - public synchronized void addServletClass(String servletPath, String restClass) { - - if (restClass == null || restClass.isEmpty()) - throw new IllegalArgumentException("No discoverable REST class provided"); - - if (servletPath == null || servletPath.isEmpty()) - servletPath = "/*"; - - ServletHolder jerseyServlet = this.getServlet(servletPath); - - String initPackages = - jerseyServlet.getInitParameter(JERSEY_INIT_PACKAGES_PARAM_NAME); - if (initPackages != null && !initPackages.isEmpty()) - logger.warn("Both classes and packages are used in Jetty+Jersey Configuration: {}", restClass); - - String initClasses = - jerseyServlet.getInitParameter(JERSEY_INIT_CLASSNAMES_PARAM_NAME); - if (initClasses == null) { - if (this.swaggerId != null) { - initClasses = JERSEY_JACKSON_INIT_CLASSNAMES_PARAM_VALUE + "," + - SWAGGER_INIT_CLASSNAMES_PARAM_VALUE + "," + - restClass; - - jerseyServlet.setInitParameter(SWAGGER_CONTEXT_ID, swaggerId); - jerseyServlet.setInitParameter(SWAGGER_SCANNER_ID, swaggerId); - } else { - initClasses = JERSEY_JACKSON_INIT_CLASSNAMES_PARAM_VALUE + "," + restClass; - } - } else { - initClasses = initClasses + "," + restClass; - } - - jerseyServlet.setInitParameter(JERSEY_INIT_CLASSNAMES_PARAM_NAME, initClasses); - - if (logger.isDebugEnabled()) - logger.debug("{}: added REST class: {}", this, jerseyServlet.dump()); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("JettyJerseyServer [servlets=").append(servlets).append(", swaggerId=").append(swaggerId) - .append(", toString()=").append(super.toString()).append("]"); - return builder.toString(); - } -} diff --git a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/internal/JettyServletServer.java b/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/internal/JettyServletServer.java deleted file mode 100644 index 08c62445..00000000 --- a/policy-endpoints/src/main/java/org/onap/policy/drools/http/server/internal/JettyServletServer.java +++ /dev/null @@ -1,388 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.http.server.internal; - -import org.eclipse.jetty.security.ConstraintMapping; -import org.eclipse.jetty.security.ConstraintSecurityHandler; -import org.eclipse.jetty.security.HashLoginService; -import org.eclipse.jetty.security.authentication.BasicAuthenticator; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.server.Slf4jRequestLog; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.util.security.Constraint; -import org.eclipse.jetty.util.security.Credential; -import org.onap.policy.drools.http.server.HttpServletServer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -/** - * Http Server implementation using Embedded Jetty - */ -public abstract class JettyServletServer implements HttpServletServer, Runnable { - - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(JettyServletServer.class); - - /** - * server name - */ - protected final String name; - - /** - * server host address - */ - protected final String host; - - /** - * server port to bind - */ - protected final int port; - - /** - * server auth user name - */ - protected String user; - - /** - * server auth password name - */ - protected String password; - - /** - * server base context path - */ - protected final String contextPath; - - /** - * embedded jetty server - */ - protected final Server jettyServer; - - /** - * servlet context - */ - protected final ServletContextHandler context; - - /** - * jetty connector - */ - protected final ServerConnector connector; - - /** - * jetty thread - */ - protected volatile Thread jettyThread; - - /** - * start condition - */ - protected Object startCondition = new Object(); - - /** - * constructor - * - * @param name server name - * @param host server host - * @param port server port - * @param contextPath context path - * - * @throws IllegalArgumentException if invalid parameters are passed in - */ - public JettyServletServer(String name, String host, int port, String contextPath) { - String srvName = name; - String srvHost = host; - String ctxtPath = contextPath; - - if (srvName == null || srvName.isEmpty()) - srvName = "http-" + port; - - if (port <= 0 && port >= 65535) - throw new IllegalArgumentException("Invalid Port provided: " + port); - - if (srvHost == null || srvHost.isEmpty()) - srvHost = "localhost"; - - if (ctxtPath == null || ctxtPath.isEmpty()) - ctxtPath = "/"; - - this.name = srvName; - - this.host = srvHost; - this.port = port; - - this.contextPath = ctxtPath; - - this.context = new ServletContextHandler(ServletContextHandler.SESSIONS); - this.context.setContextPath(ctxtPath); - - this.jettyServer = new Server(); - this.jettyServer.setRequestLog(new Slf4jRequestLog()); - - this.connector = new ServerConnector(this.jettyServer); - this.connector.setName(srvName); - this.connector.setReuseAddress(true); - this.connector.setPort(port); - this.connector.setHost(srvHost); - - this.jettyServer.addConnector(this.connector); - this.jettyServer.setHandler(context); - } - - @Override - public void setBasicAuthentication(String user, String password, String servletPath) { - String srvltPath = servletPath; - - if (user == null || user.isEmpty() || password == null || password.isEmpty()) - throw new IllegalArgumentException("Missing user and/or password"); - - if (srvltPath == null || srvltPath.isEmpty()) - srvltPath = "/*"; - - HashLoginService hashLoginService = new HashLoginService(); - hashLoginService.putUser(user, - Credential.getCredential(password), - new String[] {"user"}); - hashLoginService.setName(this.connector.getName() + "-login-service"); - - Constraint constraint = new Constraint(); - constraint.setName(Constraint.__BASIC_AUTH); - constraint.setRoles(new String[]{"user"}); - constraint.setAuthenticate(true); - - ConstraintMapping constraintMapping = new ConstraintMapping(); - constraintMapping.setConstraint(constraint); - constraintMapping.setPathSpec(srvltPath); - - ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); - securityHandler.setAuthenticator(new BasicAuthenticator()); - securityHandler.setRealmName(this.connector.getName() + "-realm"); - securityHandler.addConstraintMapping(constraintMapping); - securityHandler.setLoginService(hashLoginService); - - this.context.setSecurityHandler(securityHandler); - - this.user = user; - this.password = password; - } - - /** - * jetty server execution - */ - @Override - public void run() { - try { - logger.info("{}: STARTING", this); - - this.jettyServer.start(); - - if (logger.isInfoEnabled()) - logger.info("{}: STARTED: {}", this, this.jettyServer.dump()); - - synchronized(this.startCondition) { - this.startCondition.notifyAll(); - } - - this.jettyServer.join(); - } catch (Exception e) { - logger.error("{}: error found while bringing up server", this, e); - } - } - - @Override - public boolean waitedStart(long maxWaitTime) throws InterruptedException { - logger.info("{}: WAITED-START", this); - - if (maxWaitTime < 0) - throw new IllegalArgumentException("max-wait-time cannot be negative"); - - long pendingWaitTime = maxWaitTime; - - if (!this.start()) - return false; - - synchronized (this.startCondition) { - - while (!this.jettyServer.isRunning()) { - try { - long startTs = System.currentTimeMillis(); - - this.startCondition.wait(pendingWaitTime); - - if (maxWaitTime == 0) - /* spurious notification */ - continue; - - long endTs = System.currentTimeMillis(); - pendingWaitTime = pendingWaitTime - (endTs - startTs); - - logger.info("{}: pending time is {} ms.", this, pendingWaitTime); - - if (pendingWaitTime <= 0) - return false; - - } catch (InterruptedException e) { - logger.warn("{}: waited-start has been interrupted", this); - throw e; - } - } - - return this.jettyServer.isRunning(); - } - } - - @Override - public boolean start() { - logger.info("{}: STARTING", this); - - synchronized(this) { - if (jettyThread == null || - !this.jettyThread.isAlive()) { - - this.jettyThread = new Thread(this); - this.jettyThread.setName(this.name + "-" + this.port); - this.jettyThread.start(); - } - } - - return true; - } - - @Override - public boolean stop() { - logger.info("{}: STOPPING", this); - - synchronized(this) { - if (jettyThread == null) { - return true; - } - - if (!jettyThread.isAlive()) { - this.jettyThread = null; - } - - try { - this.connector.stop(); - } catch (Exception e) { - logger.error("{}: error while stopping management server", this, e); - } - - try { - this.jettyServer.stop(); - } catch (Exception e) { - logger.error("{}: error while stopping management server", this, e); - return false; - } - - Thread.yield(); - } - - return true; - } - - @Override - public void shutdown() { - logger.info("{}: SHUTTING DOWN", this); - - this.stop(); - - if (this.jettyThread == null) - return; - - Thread jettyThreadCopy = this.jettyThread; - - if (jettyThreadCopy.isAlive()) { - try { - jettyThreadCopy.join(2000L); - } catch (InterruptedException e) { - logger.warn("{}: error while shutting down management server", this); - Thread.currentThread().interrupt(); - } - if (!jettyThreadCopy.isInterrupted()) { - try { - jettyThreadCopy.interrupt(); - } catch(Exception e) { - // do nothing - logger.warn("{}: exception while shutting down (OK)", this, e); - } - } - } - - this.jettyServer.destroy(); - } - - @Override - public boolean isAlive() { - if (this.jettyThread != null) - return this.jettyThread.isAlive(); - - return false; - } - - @Override - public int getPort() { - return this.port; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @return the host - */ - public String getHost() { - return host; - } - - /** - * @return the user - */ - public String getUser() { - return user; - } - - /** - * @return the password - */ - @JsonIgnore - public String getPassword() { - return password; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("JettyServer [name=").append(name).append(", host=").append(host).append(", port=").append(port) - .append(", user=").append(user).append(", password=").append(password != null).append(", contextPath=") - .append(contextPath).append(", jettyServer=").append(jettyServer).append(", context=").append(this.context) - .append(", connector=").append(connector).append(", jettyThread=").append(jettyThread) - .append("]"); - return builder.toString(); - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/HttpClientTest.java b/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/HttpClientTest.java deleted file mode 100644 index 6a84d142..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/HttpClientTest.java +++ /dev/null @@ -1,203 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.http.server.test; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.List; -import java.util.Properties; - -import javax.ws.rs.core.Response; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.drools.http.client.HttpClient; -import org.onap.policy.drools.http.server.HttpServletServer; -import org.onap.policy.drools.properties.PolicyProperties; -import org.onap.policy.drools.utils.NetworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class HttpClientTest { - - private static Logger logger = LoggerFactory.getLogger(HttpClientTest.class); - - @BeforeClass - public static void setUp() throws InterruptedException, IOException { - logger.info("-- setup() --"); - - /* echo server */ - - final HttpServletServer echoServerNoAuth = - HttpServletServer.factory.build("echo", "localhost", 6666, "/", false, true); - echoServerNoAuth.addServletPackage("/*", HttpClientTest.class.getPackage().getName()); - echoServerNoAuth.waitedStart(5000); - - if (!NetworkUtil.isTcpPortOpen("localhost", echoServerNoAuth.getPort(), 5, 10000L)) - throw new IllegalStateException("cannot connect to port " + echoServerNoAuth.getPort()); - - /* no auth echo server */ - - final HttpServletServer echoServerAuth = - HttpServletServer.factory.build("echo", "localhost", 6667, "/", false, true); - echoServerAuth.setBasicAuthentication("x", "y", null); - echoServerAuth.addServletPackage("/*", HttpClientTest.class.getPackage().getName()); - echoServerAuth.waitedStart(5000); - - if (!NetworkUtil.isTcpPortOpen("localhost", echoServerAuth.getPort(), 5, 10000L)) - throw new IllegalStateException("cannot connect to port " + echoServerAuth.getPort()); - } - - @AfterClass - public static void tearDown() { - logger.info("-- tearDown() --"); - - HttpServletServer.factory.destroy(); - HttpClient.factory.destroy(); - } - - @Test - public void testHttpNoAuthClient() throws Exception { - logger.info("-- testHttpNoAuthClient() --"); - - final HttpClient client = HttpClient.factory.build("testHttpNoAuthClient", false, false, - "localhost", 6666, "junit/echo", null, null, true); - final Response response = client.get("hello"); - final String body = HttpClient.getBody(response, String.class); - - assertTrue(response.getStatus() == 200); - assertTrue(body.equals("hello")); - } - - @Test - public void testHttpAuthClient() throws Exception { - logger.info("-- testHttpAuthClient() --"); - - final HttpClient client = HttpClient.factory.build("testHttpAuthClient", false, false, - "localhost", 6667, "junit/echo", "x", "y", true); - final Response response = client.get("hello"); - final String body = HttpClient.getBody(response, String.class); - - assertTrue(response.getStatus() == 200); - assertTrue(body.equals("hello")); - } - - @Test - public void testHttpAuthClient401() throws Exception { - logger.info("-- testHttpAuthClient401() --"); - - final HttpClient client = HttpClient.factory.build("testHttpAuthClient401", false, false, - "localhost", 6667, "junit/echo", null, null, true); - final Response response = client.get("hello"); - assertTrue(response.getStatus() == 401); - } - - @Test - public void testHttpAuthClientProps() throws Exception { - logger.info("-- testHttpAuthClientProps() --"); - - final Properties httpProperties = new Properties(); - - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES, "PAP,PDP"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX, "7777"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpap"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, "alpha123"); - httpProperties.setProperty( - PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, - RestMockHealthCheck.class.getName()); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_MANAGED_SUFFIX, "true"); - - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX, "7778"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpdp"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, "alpha123"); - httpProperties.setProperty( - PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, - RestMockHealthCheck.class.getName()); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_MANAGED_SUFFIX, "true"); - - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES, "PAP,PDP"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX, "7777"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_URL_SUFFIX, "pap/test"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpap"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, "alpha123"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PAP" - + PolicyProperties.PROPERTY_MANAGED_SUFFIX, "true"); - - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX, "7778"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_URL_SUFFIX, "pdp"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, "testpdp"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_HTTP_AUTH_PASSWORD_SUFFIX, "alpha123"); - httpProperties.setProperty(PolicyProperties.PROPERTY_HTTP_CLIENT_SERVICES + "." + "PDP" - + PolicyProperties.PROPERTY_MANAGED_SUFFIX, "true"); - - final List<HttpServletServer> servers = HttpServletServer.factory.build(httpProperties); - assertTrue(servers.size() == 2); - - final List<HttpClient> clients = HttpClient.factory.build(httpProperties); - assertTrue(clients.size() == 2); - - for (final HttpServletServer server : servers) { - server.waitedStart(10000); - } - - final HttpClient clientPAP = HttpClient.factory.get("PAP"); - final Response response = clientPAP.get(); - assertTrue(response.getStatus() == 200); - - final HttpClient clientPDP = HttpClient.factory.get("PDP"); - final Response response2 = clientPDP.get("test"); - assertTrue(response2.getStatus() == 500); - } - - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/HttpServerTest.java b/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/HttpServerTest.java deleted file mode 100644 index aa3fa584..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/HttpServerTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.http.server.test; - -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.ConnectException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.UUID; - -import org.junit.Test; -import org.onap.policy.drools.http.server.HttpServletServer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * HttpServletServer JUNIT tests - */ -public class HttpServerTest { - - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(HttpServerTest.class); - - @Test - public void testSingleServer() throws Exception { - logger.info("-- testSingleServer() --"); - - HttpServletServer server = HttpServletServer.factory.build("echo", "localhost", 5678, "/", false, true); - server.addServletPackage("/*", this.getClass().getPackage().getName()); - server.waitedStart(5000); - - assertTrue(HttpServletServer.factory.get(5678).isAlive()); - - String response = - http(HttpServletServer.factory.get(5678), "http://localhost:5678/junit/echo/hello"); - assertTrue("hello".equals(response)); - - response = null; - try { - response = http(HttpServletServer.factory.get(5678), "http://localhost:5678/swagger.json"); - } catch (IOException e) { - // Expected - } - assertTrue(response == null); - - assertTrue(HttpServletServer.factory.get(5678).isAlive()); - assertTrue(HttpServletServer.factory.inventory().size() == 1); - - HttpServletServer.factory.destroy(5678); - assertTrue(HttpServletServer.factory.inventory().size() == 0); - } - - @Test - public void testMultipleServers() throws Exception { - logger.info("-- testMultipleServers() --"); - - HttpServletServer server1 = HttpServletServer.factory.build("echo-1", "localhost", 5688, "/", true, true); - server1.addServletPackage("/*", this.getClass().getPackage().getName()); - server1.waitedStart(5000); - - HttpServletServer server2 = HttpServletServer.factory.build("echo-2", "localhost", 5689, "/", false, true); - server2.addServletPackage("/*", this.getClass().getPackage().getName()); - server2.waitedStart(5000); - - assertTrue(HttpServletServer.factory.get(5688).isAlive()); - assertTrue(HttpServletServer.factory.get(5689).isAlive()); - - String response = - http(HttpServletServer.factory.get(5688), "http://localhost:5688/junit/echo/hello"); - assertTrue("hello".equals(response)); - - response = - http(HttpServletServer.factory.get(5688), "http://localhost:5688/swagger.json"); - assertTrue(response != null); - - response = - http(HttpServletServer.factory.get(5689), "http://localhost:5689/junit/echo/hello"); - assertTrue("hello".equals(response)); - - response = null; - try { - response = http(HttpServletServer.factory.get(5689), "http://localhost:5689/swagger.json"); - } catch (IOException e) { - // Expected - } - assertTrue(response == null); - - HttpServletServer.factory.destroy(); - assertTrue(HttpServletServer.factory.inventory().size() == 0); - } - - @Test - public void testMultiServicePackage() throws Exception { - logger.info("-- testMultiServicePackage() --"); - - String randomName = UUID.randomUUID().toString(); - - HttpServletServer server = HttpServletServer.factory.build(randomName, "localhost", 5668, "/", false, true); - server.addServletPackage("/*", this.getClass().getPackage().getName()); - server.waitedStart(5000); - - assertTrue(HttpServletServer.factory.get(5668).isAlive()); - - String response = - http(HttpServletServer.factory.get(5668), "http://localhost:5668/junit/echo/hello"); - assertTrue("hello".equals(response)); - - response = - http(HttpServletServer.factory.get(5668), "http://localhost:5668/junit/endpoints/http/servers"); - assertTrue(response.contains(randomName)); - - HttpServletServer.factory.destroy(); - assertTrue(HttpServletServer.factory.inventory().size() == 0); - } - - @Test - public void testServiceClass() throws Exception { - logger.info("-- testServiceClass() --"); - String randomName = UUID.randomUUID().toString(); - - HttpServletServer server = HttpServletServer.factory.build(randomName, "localhost", 5658, "/", false, true); - server.addServletClass("/*", RestEchoService.class.getCanonicalName()); - server.waitedStart(5000); - - assertTrue(HttpServletServer.factory.get(5658).isAlive()); - - String response = - http(HttpServletServer.factory.get(5658), "http://localhost:5658/junit/echo/hello"); - assertTrue("hello".equals(response)); - - HttpServletServer.factory.destroy(); - assertTrue(HttpServletServer.factory.inventory().size() == 0); - } - - @Test - public void testMultiServiceClass() throws Exception { - logger.info("-- testMultiServiceClass() --"); - - String randomName = UUID.randomUUID().toString(); - - HttpServletServer server = HttpServletServer.factory.build(randomName, "localhost", 5648, "/", false, true); - server.addServletClass("/*", RestEchoService.class.getCanonicalName()); - server.addServletClass("/*", RestEndpoints.class.getCanonicalName()); - server.waitedStart(5000); - - assertTrue(HttpServletServer.factory.get(5648).isAlive()); - - String response = - http(HttpServletServer.factory.get(5648), "http://localhost:5648/junit/echo/hello"); - assertTrue("hello".equals(response)); - - response = - http(HttpServletServer.factory.get(5648), "http://localhost:5648/junit/endpoints/http/servers"); - assertTrue(response.contains(randomName)); - - HttpServletServer.factory.destroy(); - assertTrue(HttpServletServer.factory.inventory().size() == 0); - } - - /** - * performs an http request - * - * @throws MalformedURLException - * @throws IOException - * @throws InterruptedException - */ - protected String http(HttpServletServer server, String aUrl) - throws MalformedURLException, IOException, InterruptedException { - URL url = new URL(aUrl); - String response = null; - int numRetries = 1, maxNumberRetries = 5; - while (numRetries <= maxNumberRetries) { - try { - response = response(url); - break; - } catch (ConnectException e) { - logger.warn("http server {} @ {} ({}) - cannot connect yet ..", - server, aUrl, numRetries, e); - numRetries++; - Thread.sleep(10000L); - } catch (Exception e) { - throw e; - } - } - - return response; - } - - /** - * gets http response - * - * @param url url - * - * @throws IOException - */ - protected String response(URL url) throws IOException { - String response = ""; - try (BufferedReader ioReader = new BufferedReader(new InputStreamReader(url.openStream()))) { - String line; - while ((line = ioReader.readLine()) != null) { - response += line; - } - } - return response; - } - - - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/NoopTopicTest.java b/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/NoopTopicTest.java deleted file mode 100644 index 65269038..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/NoopTopicTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.http.server.test; - -import static org.junit.Assert.assertTrue; - -import java.util.List; -import java.util.Properties; - -import org.junit.Test; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; -import org.onap.policy.drools.event.comm.TopicEndpoint; -import org.onap.policy.drools.event.comm.TopicListener; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.bus.NoopTopicSink; -import org.onap.policy.drools.properties.PolicyProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * NOOP Endpoint Tests - */ -public class NoopTopicTest implements TopicListener { - - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(NoopTopicTest.class); - - private final String topicName = "junit-noop"; - private final String outMessage = "blah"; - private String inMessage = null; - - @Test - public void testNoopEndpoint() { - logger.info("-- testNoopEndpoint() --"); - - Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, topicName); - - List<? extends TopicSink> noopTopics = - TopicEndpoint.manager.addTopicSinks(noopSinkProperties); - - TopicSink sink = NoopTopicSink.factory.get(topicName); - - assertTrue(noopTopics.size() == 1); - assertTrue(noopTopics.size() == NoopTopicSink.factory.inventory().size()); - assertTrue(noopTopics.get(0) == sink); - assertTrue(sink == NoopTopicSink.factory.inventory().get(0)); - - assertTrue(!sink.isAlive()); - - boolean badState = false; - try{ - sink.send(outMessage); - } catch(IllegalStateException e) { - badState = true; - } - assertTrue(badState); - - sink.start(); - assertTrue(sink.isAlive()); - - sink.send(outMessage); - assertTrue(sink.getRecentEvents().length == 1); - assertTrue(sink.getRecentEvents()[0].equals(outMessage)); - assertTrue(this.inMessage == null); - - sink.register(this); - sink.send(this.outMessage); - assertTrue(outMessage.equals(this.inMessage)); - this.inMessage = null; - - sink.unregister(this); - sink.send(this.outMessage); - assertTrue(!outMessage.equals(this.inMessage)); - - sink.stop(); - try{ - sink.send(outMessage); - } catch(IllegalStateException e) { - badState = true; - } - assertTrue(badState); - - NoopTopicSink.factory.destroy(topicName); - assertTrue(NoopTopicSink.factory.inventory().size() == 0); - } - - @Override - public void onTopicEvent(CommInfrastructure commType, String topic, String event) { - if (commType != CommInfrastructure.NOOP) - return; - - if (topic == null || !topic.equals(topicName)) - return; - - this.inMessage = event; - } -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/RestEchoService.java b/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/RestEchoService.java deleted file mode 100644 index 3978caf2..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/RestEchoService.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.http.server.test; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - -@Api(value="echo") -@Path("/junit/echo") -public class RestEchoService { - - @GET - @Path("{word}") - @Produces(MediaType.TEXT_PLAIN) - @ApiOperation( - value="echoes back whatever received" - ) - public String echo(@PathParam("word") String word) { - return word; - } - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/RestEndpoints.java b/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/RestEndpoints.java deleted file mode 100644 index a21c9d3b..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/RestEndpoints.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.http.server.test; - -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -import org.onap.policy.drools.http.server.HttpServletServer; - -@Path("/junit/endpoints") -public class RestEndpoints { - - @GET - @Path("http/servers") - @Produces(MediaType.TEXT_PLAIN) - public String httpServers() { - List<HttpServletServer> servers = - HttpServletServer.factory.inventory(); - return servers.toString(); - } - - -} diff --git a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/RestMockHealthCheck.java b/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/RestMockHealthCheck.java deleted file mode 100644 index cb1405f6..00000000 --- a/policy-endpoints/src/test/java/org/onap/policy/drools/http/server/test/RestMockHealthCheck.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-endpoints - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.http.server.test; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - -@Path("/") -public class RestMockHealthCheck { - - @GET - @Path("pap/test") - @Produces(MediaType.APPLICATION_JSON) - public Response papHealthCheck() { - return Response.status(Status.OK).entity("All Alive").build(); - } - - @GET - @Path("pdp/test") - @Produces(MediaType.APPLICATION_JSON) - public Response pdpHealthCheck() { - return Response.status(Status.INTERNAL_SERVER_ERROR).entity("At least some Dead").build(); - } - - -} diff --git a/policy-endpoints/src/test/resources/logback-test.xml b/policy-endpoints/src/test/resources/logback-test.xml deleted file mode 100644 index b3feef90..00000000 --- a/policy-endpoints/src/test/resources/logback-test.xml +++ /dev/null @@ -1,36 +0,0 @@ -<!-- - ============LICENSE_START======================================================= - ONAP - ================================================================================ - Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - ================================================================================ - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - ============LICENSE_END========================================================= - --> -<configuration> - - <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> - <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> - <Pattern> - %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M\(%line\) - %msg%n - </Pattern> - </encoder> - </appender> - - <logger name="org.onap.policy.drools.http.server.test" level="INFO"/> - - <root level="WARN"> - <appender-ref ref="STDOUT"/> - </root> - -</configuration>
\ No newline at end of file diff --git a/policy-management/pom.xml b/policy-management/pom.xml index 47404c9d..8a408f95 100644 --- a/policy-management/pom.xml +++ b/policy-management/pom.xml @@ -145,7 +145,7 @@ </dependency> <dependency> - <groupId>org.onap.policy.drools-pdp</groupId> + <groupId>org.onap.policy.common</groupId> <artifactId>policy-endpoints</artifactId> <version>${project.version}</version> </dependency> diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsController.java b/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsController.java index bdb95e77..7f68930e 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsController.java @@ -23,194 +23,195 @@ package org.onap.policy.drools.controller; import java.util.List; import java.util.Map; +import org.onap.policy.common.capabilities.Lockable; +import org.onap.policy.common.capabilities.Startable; +import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.drools.core.PolicyContainer; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.properties.Lockable; -import org.onap.policy.drools.properties.Startable; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration; /** - * Drools Controller is the abstractions that wraps the - * drools layer (policy-core) + * Drools Controller is the abstractions that wraps the drools layer (policy-core) */ -public interface DroolsController extends Startable, Lockable { - - /** - * No Group ID identifier - */ - public static final String NO_GROUP_ID = "NO-GROUP-ID"; - - /** - * No Artifact ID identifier - */ - public static final String NO_ARTIFACT_ID = "NO-ARTIFACT-ID"; - - /** - * No version identifier - */ - public static final String NO_VERSION = "NO-VERSION"; - - /** - * Factory to track and manage drools controllers - */ - public static final DroolsControllerFactory factory = - new IndexedDroolsControllerFactory(); - - /** - * get group id - * @return group id - */ - public String getGroupId(); - - /** - * get artifact id - * @return artifact id - */ - public String getArtifactId(); - - /** - * get version - * @return version - */ - public String getVersion(); - - /** - * return the policy session names - * - * @return policy session - */ - public List<String> getSessionNames(); - - /** - * return the policy full session names - * - * @return policy session - */ - public List<String> getCanonicalSessionNames(); - - /** - * offers an event to this controller for processing - * - * @param topic topic associated with the event - * @param event the event - * - * @return true if the operation was successful - */ - public boolean offer(String topic, String event); - - /** - * delivers "event" to "sink" - * - * @param sink destination - * @param event - * @return true if successful, false if a failure has occurred. - * @throws IllegalArgumentException when invalid or insufficient - * properties are provided - * @throws IllegalStateException when the engine is in a state where - * this operation is not permitted (ie. locked or stopped). - * @throws UnsupportedOperationException when the engine cannot deliver due - * to the functionality missing (ie. communication infrastructure - * not supported. - */ - public boolean deliver(TopicSink sink, Object event); - - /** - * - * @return the most recent received events - */ - public Object[] getRecentSourceEvents(); - - /** - * - * @return the most recent delivered events - */ - public String[] getRecentSinkEvents(); - - /** - * @return the underlying policy container - */ - public PolicyContainer getContainer(); - - /** - * Supports this encoder? - * - * @param encodedObject - * @return - */ - public boolean ownsCoder(Class<? extends Object> coderClass, int modelHash); - - /** - * fetches a class from the model - * - * @param className the class to fetch - * @return the actual class object, or null if not found - */ - public Class<?> fetchModelClass(String className); - - /** - * is this controller Smart? - */ - public boolean isBrained(); - - /** - * update the new version of the maven jar rules file - * - * @param newGroupId - new group id - * @param newArtifactId - new artifact id - * @param newVersion - new version - * @param decoderConfigurations - decoder configurations - * @param encoderConfigurations - encoder configurations - * - * @throws Exception from within drools libraries - * @throws LinkageError from within drools libraries - * @throws ArgumentException bad parameter passed in - */ - public void updateToVersion(String newGroupId, String newArtifactId, String newVersion, - List<TopicCoderFilterConfiguration> decoderConfigurations, - List<TopicCoderFilterConfiguration> encoderConfigurations) - throws LinkageError; - - /** - * gets the classnames of facts as well as the current count - * @param sessionName the session name - * @return map of class to count - */ - public Map<String,Integer> factClassNames(String sessionName); - - /** - * gets the count of facts for a given session - * @param sessionName the session name - * @return the fact count - * @throws IllegalArgumentException - */ - public long factCount(String sessionName); - - /** - * gets all the facts of a given class for a given session - * - * @param sessionName the session identifier - * @param className the class type - * @param delete retract from drools the results of the query? - * @return the list of facts returned by the query - */ - public List<Object> facts(String sessionName, String className, boolean delete); - - /** - * gets the facts associated with a query for a give session for a given queried entity - * - * @param sessionName the session - * @param queryName the query identifier - * @param queriedEntity the queried entity - * @param delete retract from drools the results of the query? - * @param queryParams query parameters - * @return list of facts returned by the query - */ - public List<Object> factQuery(String sessionName, String queryName, String queriedEntity, - boolean delete, Object... queryParams); - - /** - * halts and permanently releases all resources - * @throws IllegalStateException - */ - public void halt(); +public interface DroolsController extends Startable, Lockable { + + /** + * No Group ID identifier + */ + public static final String NO_GROUP_ID = "NO-GROUP-ID"; + + /** + * No Artifact ID identifier + */ + public static final String NO_ARTIFACT_ID = "NO-ARTIFACT-ID"; + + /** + * No version identifier + */ + public static final String NO_VERSION = "NO-VERSION"; + + /** + * Factory to track and manage drools controllers + */ + public static final DroolsControllerFactory factory = new IndexedDroolsControllerFactory(); + + /** + * get group id + * + * @return group id + */ + public String getGroupId(); + + /** + * get artifact id + * + * @return artifact id + */ + public String getArtifactId(); + + /** + * get version + * + * @return version + */ + public String getVersion(); + + /** + * return the policy session names + * + * @return policy session + */ + public List<String> getSessionNames(); + + /** + * return the policy full session names + * + * @return policy session + */ + public List<String> getCanonicalSessionNames(); + + /** + * offers an event to this controller for processing + * + * @param topic topic associated with the event + * @param event the event + * + * @return true if the operation was successful + */ + public boolean offer(String topic, String event); + + /** + * delivers "event" to "sink" + * + * @param sink destination + * @param event + * @return true if successful, false if a failure has occurred. + * @throws IllegalArgumentException when invalid or insufficient properties are provided + * @throws IllegalStateException when the engine is in a state where this operation is not + * permitted (ie. locked or stopped). + * @throws UnsupportedOperationException when the engine cannot deliver due to the functionality + * missing (ie. communication infrastructure not supported. + */ + public boolean deliver(TopicSink sink, Object event); + + /** + * + * @return the most recent received events + */ + public Object[] getRecentSourceEvents(); + + /** + * + * @return the most recent delivered events + */ + public String[] getRecentSinkEvents(); + + /** + * @return the underlying policy container + */ + public PolicyContainer getContainer(); + + /** + * Supports this encoder? + * + * @param encodedObject + * @return + */ + public boolean ownsCoder(Class<? extends Object> coderClass, int modelHash); + + /** + * fetches a class from the model + * + * @param className the class to fetch + * @return the actual class object, or null if not found + */ + public Class<?> fetchModelClass(String className); + + /** + * is this controller Smart? + */ + public boolean isBrained(); + + /** + * update the new version of the maven jar rules file + * + * @param newGroupId - new group id + * @param newArtifactId - new artifact id + * @param newVersion - new version + * @param decoderConfigurations - decoder configurations + * @param encoderConfigurations - encoder configurations + * + * @throws Exception from within drools libraries + * @throws LinkageError from within drools libraries + * @throws ArgumentException bad parameter passed in + */ + public void updateToVersion(String newGroupId, String newArtifactId, String newVersion, + List<TopicCoderFilterConfiguration> decoderConfigurations, + List<TopicCoderFilterConfiguration> encoderConfigurations) throws LinkageError; + + /** + * gets the classnames of facts as well as the current count + * + * @param sessionName the session name + * @return map of class to count + */ + public Map<String, Integer> factClassNames(String sessionName); + + /** + * gets the count of facts for a given session + * + * @param sessionName the session name + * @return the fact count + * @throws IllegalArgumentException + */ + public long factCount(String sessionName); + + /** + * gets all the facts of a given class for a given session + * + * @param sessionName the session identifier + * @param className the class type + * @param delete retract from drools the results of the query? + * @return the list of facts returned by the query + */ + public List<Object> facts(String sessionName, String className, boolean delete); + + /** + * gets the facts associated with a query for a give session for a given queried entity + * + * @param sessionName the session + * @param queryName the query identifier + * @param queriedEntity the queried entity + * @param delete retract from drools the results of the query? + * @param queryParams query parameters + * @return list of facts returned by the query + */ + public List<Object> factQuery(String sessionName, String queryName, String queriedEntity, boolean delete, + Object... queryParams); + + /** + * halts and permanently releases all resources + * + * @throws IllegalStateException + */ + public void halt(); } diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsControllerFactory.java b/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsControllerFactory.java index 65c9f334..b3aaaa7f 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsControllerFactory.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/DroolsControllerFactory.java @@ -26,498 +26,472 @@ import java.util.HashMap; import java.util.List; import java.util.Properties; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.drools.controller.internal.MavenDroolsController; import org.onap.policy.drools.controller.internal.NullDroolsController; -import org.onap.policy.drools.event.comm.Topic; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.onap.policy.drools.event.comm.TopicSource; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.common.endpoints.event.comm.Topic; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; +import org.onap.policy.drools.properties.DroolsProperties; import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomJacksonCoder; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.PotentialCoderFilter; import org.onap.policy.drools.utils.Pair; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * Drools Controller Factory to manage controller creation, destruction, - * and retrieval for management interfaces + * Drools Controller Factory to manage controller creation, destruction, and retrieval for + * management interfaces */ public interface DroolsControllerFactory { - - /** - * Constructs a Drools Controller based on properties - * - * @param properties properties containing initialization parameters - * @param eventSources list of event sources - * @param eventSinks list of event sinks - * - * @return the instantiated Drools Controller - * @throws IllegalArgumentException with invalid parameters - * @throws LinkageError Failure to link rules and models in Drools Libraries - */ - public DroolsController build(Properties properties, - List<? extends TopicSource> eventSources, - List<? extends TopicSink> eventSinks) - throws LinkageError; - - /** - * Explicit construction of a Drools Controller - * - * @param groupId maven group id of drools artifact - * @param artifactId maven artifact id of drools artifact - * @param version maven version id of drools artifact - * @param decoderConfigurations list of decoder configurations - * @param encoderConfigurations list of encoder configurations - * - * @return the instantiated Drools Controller - * @throws IllegalArgumentException with invalid parameters - * @throws LinkageError Failure to link rules and models in Drools Libraries - */ - public DroolsController build(String groupId, - String artifactId, - String version, - List<TopicCoderFilterConfiguration> decoderConfigurations, - List<TopicCoderFilterConfiguration> encoderConfigurations) - throws LinkageError; - - /** - * Releases the Drools Controller from operation - * - * @param controller the Drools Controller to shut down - */ - public void shutdown(DroolsController controller); - - /** - * Disables all Drools Controllers from operation - */ - public void shutdown(); - - /** - * Destroys and releases resources for a Drools Controller - * - * @param controller the Drools Controller to destroy - */ - public void destroy(DroolsController controller); - - /** - * Destroys all Drools Controllers - */ - public void destroy(); - - /** - * Gets the Drools Controller associated with the maven group - * and artifact id - * - * @param groupId maven group id of drools artifact - * @param artifactId maven artifact id of drools artifact - * @param version maven version id of drools artifact - * - * @return the Drools Controller - * @throws IllegalArgumentException with invalid parameters - */ - public DroolsController get(String groupId, - String artifactId, - String version); - - /** - * returns the current inventory of Drools Controllers - * - * @return a list of Drools Controllers - */ - public List<DroolsController> inventory(); + + /** + * Constructs a Drools Controller based on properties + * + * @param properties properties containing initialization parameters + * @param eventSources list of event sources + * @param eventSinks list of event sinks + * + * @return the instantiated Drools Controller + * @throws IllegalArgumentException with invalid parameters + * @throws LinkageError Failure to link rules and models in Drools Libraries + */ + public DroolsController build(Properties properties, List<? extends TopicSource> eventSources, + List<? extends TopicSink> eventSinks) throws LinkageError; + + /** + * Explicit construction of a Drools Controller + * + * @param groupId maven group id of drools artifact + * @param artifactId maven artifact id of drools artifact + * @param version maven version id of drools artifact + * @param decoderConfigurations list of decoder configurations + * @param encoderConfigurations list of encoder configurations + * + * @return the instantiated Drools Controller + * @throws IllegalArgumentException with invalid parameters + * @throws LinkageError Failure to link rules and models in Drools Libraries + */ + public DroolsController build(String groupId, String artifactId, String version, + List<TopicCoderFilterConfiguration> decoderConfigurations, + List<TopicCoderFilterConfiguration> encoderConfigurations) throws LinkageError; + + /** + * Releases the Drools Controller from operation + * + * @param controller the Drools Controller to shut down + */ + public void shutdown(DroolsController controller); + + /** + * Disables all Drools Controllers from operation + */ + public void shutdown(); + + /** + * Destroys and releases resources for a Drools Controller + * + * @param controller the Drools Controller to destroy + */ + public void destroy(DroolsController controller); + + /** + * Destroys all Drools Controllers + */ + public void destroy(); + + /** + * Gets the Drools Controller associated with the maven group and artifact id + * + * @param groupId maven group id of drools artifact + * @param artifactId maven artifact id of drools artifact + * @param version maven version id of drools artifact + * + * @return the Drools Controller + * @throws IllegalArgumentException with invalid parameters + */ + public DroolsController get(String groupId, String artifactId, String version); + + /** + * returns the current inventory of Drools Controllers + * + * @return a list of Drools Controllers + */ + public List<DroolsController> inventory(); } -/* ---------------- implementation -----------------*/ + +/* ---------------- implementation ----------------- */ /** - * Factory of Drools Controllers indexed by the Maven coordinates + * Factory of Drools Controllers indexed by the Maven coordinates */ class IndexedDroolsControllerFactory implements DroolsControllerFactory { - /** - * logger - */ - private static Logger logger = LoggerFactory.getLogger(MavenDroolsController.class); - - /** - * Policy Controller Name Index - */ - protected HashMap<String, DroolsController> droolsControllers = new HashMap<>(); - - /** - * Null Drools Controller - */ - protected NullDroolsController nullDroolsController = new NullDroolsController(); - - - public IndexedDroolsControllerFactory() { - - /* Add a NULL controller which will always be present in the hash */ - - DroolsController controller = new NullDroolsController(); - String controllerId = controller.getGroupId() + ":" + controller.getArtifactId(); - - synchronized(this) { - droolsControllers.put(controllerId, controller); - } - } - - @Override - public DroolsController build(Properties properties, - List<? extends TopicSource> eventSources, - List<? extends TopicSink> eventSinks) - throws LinkageError { - - String groupId = properties.getProperty(PolicyProperties.RULES_GROUPID); - if (groupId == null || groupId.isEmpty()) - groupId = DroolsController.NO_GROUP_ID; - - String artifactId = properties.getProperty(PolicyProperties.RULES_ARTIFACTID); - if (artifactId == null || artifactId.isEmpty()) - artifactId = DroolsController.NO_ARTIFACT_ID; - - String version = properties.getProperty(PolicyProperties.RULES_VERSION); - if (version == null || version.isEmpty()) - version = DroolsController.NO_VERSION; - - List<TopicCoderFilterConfiguration> - topics2DecodedClasses2Filters = codersAndFilters(properties, eventSources); - - List<TopicCoderFilterConfiguration> - topics2EncodedClasses2Filters = codersAndFilters(properties, eventSinks); - - return this.build(groupId, artifactId, version, - topics2DecodedClasses2Filters, - topics2EncodedClasses2Filters); - } - - /** - * find out decoder classes and filters - * - * @param properties properties with information about decoders - * @param topicEntities topic sources - * @return list of topics, each with associated decoder classes, each - * with a list of associated filters - * @throws IllegalArgumentException invalid input data - */ - protected List<TopicCoderFilterConfiguration> codersAndFilters - (Properties properties, List<? extends Topic> topicEntities) { - - String propertyTopicEntityPrefix; - - List<TopicCoderFilterConfiguration> - topics2DecodedClasses2Filters = new ArrayList<>(); - - if (topicEntities == null || topicEntities.isEmpty()) - return topics2DecodedClasses2Filters; - - for (Topic topic: topicEntities) { - - /* source or sink ? ueb or dmaap? */ - boolean isSource = topic instanceof TopicSource; - CommInfrastructure commInfra = topic.getTopicCommInfrastructure(); - if (commInfra == CommInfrastructure.UEB) { - if (isSource) { - propertyTopicEntityPrefix = PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "."; - } else { - propertyTopicEntityPrefix = PolicyProperties.PROPERTY_UEB_SINK_TOPICS + "."; - } - } else if (commInfra == CommInfrastructure.DMAAP) { - if (isSource) { - propertyTopicEntityPrefix = PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "."; - } else { - propertyTopicEntityPrefix = PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "."; - } - } else if (commInfra == CommInfrastructure.NOOP) { - if (!isSource) - propertyTopicEntityPrefix = PolicyProperties.PROPERTY_NOOP_SINK_TOPICS + "."; - else - continue; - } else { - throw new IllegalArgumentException("Invalid Communication Infrastructure: " + commInfra); - } - - // 1. first the topic - - String aTopic = topic.getTopic(); - - // 2. check if there is a custom decoder for this topic that the user prefers to use - // instead of the ones provided in the platform - - String customGson = properties.getProperty - (propertyTopicEntityPrefix + - aTopic + - PolicyProperties.PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_GSON_SUFFIX); - - CustomGsonCoder customGsonCoder = null; - if (customGson != null && !customGson.isEmpty()) { - try { - customGsonCoder = new CustomGsonCoder(customGson); - } catch (IllegalArgumentException e) { - logger.warn("{}: cannot create custom-gson-coder {} because of {}", - this, customGson, e.getMessage(), e); - } - } - - String customJackson = properties.getProperty - (propertyTopicEntityPrefix + - aTopic + - PolicyProperties.PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_JACKSON_SUFFIX); - - CustomJacksonCoder customJacksonCoder = null; - if (customJackson != null && !customJackson.isEmpty()) { - try { - customJacksonCoder = new CustomJacksonCoder(customJackson); - } catch (IllegalArgumentException e) { - logger.warn("{}: cannot create custom-jackson-coder {} because of {}", - this, customJackson, e.getMessage(), e); - } - } - - // 3. second the list of classes associated with each topic - - String eventClasses = - properties.getProperty(propertyTopicEntityPrefix + aTopic + PolicyProperties.PROPERTY_TOPIC_EVENTS_SUFFIX); - - if (eventClasses == null || eventClasses.isEmpty()) { - // TODO warn - continue; - } - - List<PotentialCoderFilter> classes2Filters = new ArrayList<>(); - - List<String> aTopicClasses = - new ArrayList<>(Arrays.asList(eventClasses.split("\\s*,\\s*"))); - - for (String aClass: aTopicClasses) { - - - // 4. third, for each coder class, get the list of field filters - - String filter = properties.getProperty - (propertyTopicEntityPrefix + - aTopic + - PolicyProperties.PROPERTY_TOPIC_EVENTS_SUFFIX + - "." + aClass + - PolicyProperties.PROPERTY_TOPIC_EVENTS_FILTER_SUFFIX); - - List<Pair<String,String>> filters = new ArrayList<>(); - - if (filter == null || filter.isEmpty()) { - // 4. topic -> class -> with no filters - - JsonProtocolFilter protocolFilter = JsonProtocolFilter.fromRawFilters(filters); - PotentialCoderFilter class2Filters = - new PotentialCoderFilter(aClass, protocolFilter); - classes2Filters.add(class2Filters); - continue; - } - - // There are filters associated with the applicability of - // this class for decoding. - List<String> listOfFilters = - new ArrayList<>(Arrays.asList(filter.split("\\s*,\\s*"))); - - for (String nameValue: listOfFilters) { - String fieldName; - String regexValue; - - String[] nameValueSplit = nameValue.split("\\s*=\\s*"); - if (nameValueSplit.length <= 0 || nameValueSplit.length > 2) { - // TODO warn - // skip - continue; - } - - if (nameValueSplit.length == 2) { - fieldName = nameValueSplit[0]; - regexValue = nameValueSplit[1]; - } else if (nameValueSplit.length == 1) { - fieldName = nameValueSplit[0]; - regexValue = null; - } else { - // unreachable - continue; - } - - filters.add(new Pair<String,String>(fieldName, regexValue)); - } - - JsonProtocolFilter protocolFilter = JsonProtocolFilter.fromRawFilters(filters); - PotentialCoderFilter class2Filters = - new PotentialCoderFilter(aClass, protocolFilter); - classes2Filters.add(class2Filters); - } - - TopicCoderFilterConfiguration topic2Classes2Filters = - new TopicCoderFilterConfiguration(aTopic,classes2Filters, customGsonCoder, customJacksonCoder); - topics2DecodedClasses2Filters.add(topic2Classes2Filters); - } - - return topics2DecodedClasses2Filters; - } - - @Override - public DroolsController build(String newGroupId, - String newArtifactId, - String newVersion, - List<TopicCoderFilterConfiguration> decoderConfigurations, - List<TopicCoderFilterConfiguration> encoderConfigurations) - throws LinkageError { - - if (newGroupId == null || newGroupId.isEmpty()) - throw new IllegalArgumentException("Missing maven group-id coordinate"); - - if (newArtifactId == null || newArtifactId.isEmpty()) - throw new IllegalArgumentException("Missing maven artifact-id coordinate"); - - if (newVersion == null || newVersion.isEmpty()) - throw new IllegalArgumentException("Missing maven version coordinate"); - - String controllerId = newGroupId + ":" + newArtifactId; - DroolsController controllerCopy = null; - synchronized (this) { - /* - * The Null Drools Controller for no maven coordinates is always here - * so when no coordinates present, this is the return point - * - * assert (controllerCopy instanceof NullDroolsController) - */ - if (droolsControllers.containsKey(controllerId)) { - controllerCopy = droolsControllers.get(controllerId); - if (controllerCopy.getVersion().equalsIgnoreCase(newVersion)) { - return controllerCopy; - } - } - } - - if (controllerCopy != null) { - /* - * a controller keyed by group id + artifact id exists - * but with different version => version upgrade/downgrade - */ - - controllerCopy.updateToVersion(newGroupId, newArtifactId, newVersion, - decoderConfigurations, encoderConfigurations); - - return controllerCopy; - } - - /* new drools controller */ - - DroolsController controller = new MavenDroolsController - (newGroupId, newArtifactId, newVersion, - decoderConfigurations, - encoderConfigurations); - - synchronized(this) { - droolsControllers.put(controllerId, controller); - } - - return controller; - } - - @Override - public void destroy(DroolsController controller) { - unmanage(controller); - controller.halt(); - } - - @Override - public void destroy() { - List<DroolsController> controllers = this.inventory(); - for (DroolsController controller: controllers) { - controller.halt(); - } - - synchronized(this) { - this.droolsControllers.clear(); - } - } - - /** - * unmanage the drools controller - * - * @param controller - * @return - * @throws IllegalArgumentException - */ - protected void unmanage(DroolsController controller) { - if (controller == null) { - throw new IllegalArgumentException("No controller provided"); - } - - if (!controller.isBrained()) { - logger.info("Drools Controller is NOT OPERATIONAL - nothing to destroy"); - return; - } - - String controllerId = controller.getGroupId() + ":" + controller.getArtifactId(); - synchronized(this) { - if (!this.droolsControllers.containsKey(controllerId)) { - return; - } - - droolsControllers.remove(controllerId); - } - } - - @Override - public void shutdown(DroolsController controller) { - this.unmanage(controller); - controller.shutdown(); - } - - @Override - public void shutdown() { - List<DroolsController> controllers = this.inventory(); - for (DroolsController controller: controllers) { - controller.shutdown(); - } - - synchronized(this) { - this.droolsControllers.clear(); - } - } - - @Override - public DroolsController get(String groupId, - String artifactId, - String version) { - - if (groupId == null || artifactId == null || - groupId.isEmpty() || artifactId.isEmpty()) { - throw new IllegalArgumentException("Missing maven coordinates: " + - groupId + ":" + artifactId); - } - - String controllerId = groupId + ":" + artifactId; - - synchronized(this) { - if (this.droolsControllers.containsKey(controllerId)) { - return droolsControllers.get(controllerId); - } else { - throw new IllegalStateException("DroolController for " + - controllerId + " not found"); - } - } - } - - @Override - public List<DroolsController> inventory() { - return new ArrayList<>(this.droolsControllers.values()); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("IndexedDroolsControllerFactory [#droolsControllers=").append(droolsControllers.size()) - .append("]"); - return builder.toString(); - } - + /** + * logger + */ + private static Logger logger = LoggerFactory.getLogger(MavenDroolsController.class); + + /** + * Policy Controller Name Index + */ + protected HashMap<String, DroolsController> droolsControllers = new HashMap<>(); + + /** + * Null Drools Controller + */ + protected NullDroolsController nullDroolsController = new NullDroolsController(); + + + public IndexedDroolsControllerFactory() { + + /* Add a NULL controller which will always be present in the hash */ + + DroolsController controller = new NullDroolsController(); + String controllerId = controller.getGroupId() + ":" + controller.getArtifactId(); + + synchronized (this) { + droolsControllers.put(controllerId, controller); + } + } + + @Override + public DroolsController build(Properties properties, List<? extends TopicSource> eventSources, + List<? extends TopicSink> eventSinks) throws LinkageError { + + String groupId = properties.getProperty(DroolsProperties.RULES_GROUPID); + if (groupId == null || groupId.isEmpty()) { + groupId = DroolsController.NO_GROUP_ID; + } + + String artifactId = properties.getProperty(DroolsProperties.RULES_ARTIFACTID); + if (artifactId == null || artifactId.isEmpty()) { + artifactId = DroolsController.NO_ARTIFACT_ID; + } + + String version = properties.getProperty(DroolsProperties.RULES_VERSION); + if (version == null || version.isEmpty()) { + version = DroolsController.NO_VERSION; + } + + List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = codersAndFilters(properties, eventSources); + + List<TopicCoderFilterConfiguration> topics2EncodedClasses2Filters = codersAndFilters(properties, eventSinks); + + return this.build(groupId, artifactId, version, topics2DecodedClasses2Filters, topics2EncodedClasses2Filters); + } + + /** + * find out decoder classes and filters + * + * @param properties properties with information about decoders + * @param topicEntities topic sources + * @return list of topics, each with associated decoder classes, each with a list of associated + * filters + * @throws IllegalArgumentException invalid input data + */ + protected List<TopicCoderFilterConfiguration> codersAndFilters(Properties properties, + List<? extends Topic> topicEntities) { + + String propertyTopicEntityPrefix; + + List<TopicCoderFilterConfiguration> topics2DecodedClasses2Filters = new ArrayList<>(); + + if (topicEntities == null || topicEntities.isEmpty()) { + return topics2DecodedClasses2Filters; + } + + for (Topic topic : topicEntities) { + + /* source or sink ? ueb or dmaap? */ + boolean isSource = topic instanceof TopicSource; + CommInfrastructure commInfra = topic.getTopicCommInfrastructure(); + if (commInfra == CommInfrastructure.UEB) { + if (isSource) { + propertyTopicEntityPrefix = PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + "."; + } else { + propertyTopicEntityPrefix = PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + "."; + } + } else if (commInfra == CommInfrastructure.DMAAP) { + if (isSource) { + propertyTopicEntityPrefix = PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "."; + } else { + propertyTopicEntityPrefix = PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "."; + } + } else if (commInfra == CommInfrastructure.NOOP) { + if (!isSource) { + propertyTopicEntityPrefix = PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS + "."; + } else { + continue; + } + } else { + throw new IllegalArgumentException("Invalid Communication Infrastructure: " + commInfra); + } + + // 1. first the topic + + String aTopic = topic.getTopic(); + + // 2. check if there is a custom decoder for this topic that the user prefers to use + // instead of the ones provided in the platform + + String customGson = properties.getProperty(propertyTopicEntityPrefix + aTopic + + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_GSON_SUFFIX); + + CustomGsonCoder customGsonCoder = null; + if (customGson != null && !customGson.isEmpty()) { + try { + customGsonCoder = new CustomGsonCoder(customGson); + } catch (IllegalArgumentException e) { + logger.warn("{}: cannot create custom-gson-coder {} because of {}", this, customGson, + e.getMessage(), e); + } + } + + String customJackson = properties.getProperty(propertyTopicEntityPrefix + aTopic + + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_CUSTOM_MODEL_CODER_JACKSON_SUFFIX); + + CustomJacksonCoder customJacksonCoder = null; + if (customJackson != null && !customJackson.isEmpty()) { + try { + customJacksonCoder = new CustomJacksonCoder(customJackson); + } catch (IllegalArgumentException e) { + logger.warn("{}: cannot create custom-jackson-coder {} because of {}", this, customJackson, + e.getMessage(), e); + } + } + + // 3. second the list of classes associated with each topic + + String eventClasses = properties + .getProperty(propertyTopicEntityPrefix + aTopic + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX); + + if (eventClasses == null || eventClasses.isEmpty()) { + // TODO warn + continue; + } + + List<PotentialCoderFilter> classes2Filters = new ArrayList<>(); + + List<String> aTopicClasses = new ArrayList<>(Arrays.asList(eventClasses.split("\\s*,\\s*"))); + + for (String aClass : aTopicClasses) { + + + // 4. third, for each coder class, get the list of field filters + + String filter = properties + .getProperty(propertyTopicEntityPrefix + aTopic + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX + + "." + aClass + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_FILTER_SUFFIX); + + List<Pair<String, String>> filters = new ArrayList<>(); + + if (filter == null || filter.isEmpty()) { + // 4. topic -> class -> with no filters + + JsonProtocolFilter protocolFilter = JsonProtocolFilter.fromRawFilters(filters); + PotentialCoderFilter class2Filters = new PotentialCoderFilter(aClass, protocolFilter); + classes2Filters.add(class2Filters); + continue; + } + + // There are filters associated with the applicability of + // this class for decoding. + List<String> listOfFilters = new ArrayList<>(Arrays.asList(filter.split("\\s*,\\s*"))); + + for (String nameValue : listOfFilters) { + String fieldName; + String regexValue; + + String[] nameValueSplit = nameValue.split("\\s*=\\s*"); + if (nameValueSplit.length <= 0 || nameValueSplit.length > 2) { + // TODO warn + // skip + continue; + } + + if (nameValueSplit.length == 2) { + fieldName = nameValueSplit[0]; + regexValue = nameValueSplit[1]; + } else if (nameValueSplit.length == 1) { + fieldName = nameValueSplit[0]; + regexValue = null; + } else { + // unreachable + continue; + } + + filters.add(new Pair<String, String>(fieldName, regexValue)); + } + + JsonProtocolFilter protocolFilter = JsonProtocolFilter.fromRawFilters(filters); + PotentialCoderFilter class2Filters = new PotentialCoderFilter(aClass, protocolFilter); + classes2Filters.add(class2Filters); + } + + TopicCoderFilterConfiguration topic2Classes2Filters = + new TopicCoderFilterConfiguration(aTopic, classes2Filters, customGsonCoder, customJacksonCoder); + topics2DecodedClasses2Filters.add(topic2Classes2Filters); + } + + return topics2DecodedClasses2Filters; + } + + @Override + public DroolsController build(String newGroupId, String newArtifactId, String newVersion, + List<TopicCoderFilterConfiguration> decoderConfigurations, + List<TopicCoderFilterConfiguration> encoderConfigurations) throws LinkageError { + + if (newGroupId == null || newGroupId.isEmpty()) { + throw new IllegalArgumentException("Missing maven group-id coordinate"); + } + + if (newArtifactId == null || newArtifactId.isEmpty()) { + throw new IllegalArgumentException("Missing maven artifact-id coordinate"); + } + + if (newVersion == null || newVersion.isEmpty()) { + throw new IllegalArgumentException("Missing maven version coordinate"); + } + + String controllerId = newGroupId + ":" + newArtifactId; + DroolsController controllerCopy = null; + synchronized (this) { + /* + * The Null Drools Controller for no maven coordinates is always here so when no + * coordinates present, this is the return point + * + * assert (controllerCopy instanceof NullDroolsController) + */ + if (droolsControllers.containsKey(controllerId)) { + controllerCopy = droolsControllers.get(controllerId); + if (controllerCopy.getVersion().equalsIgnoreCase(newVersion)) { + return controllerCopy; + } + } + } + + if (controllerCopy != null) { + /* + * a controller keyed by group id + artifact id exists but with different version => + * version upgrade/downgrade + */ + + controllerCopy.updateToVersion(newGroupId, newArtifactId, newVersion, decoderConfigurations, + encoderConfigurations); + + return controllerCopy; + } + + /* new drools controller */ + + DroolsController controller = new MavenDroolsController(newGroupId, newArtifactId, newVersion, + decoderConfigurations, encoderConfigurations); + + synchronized (this) { + droolsControllers.put(controllerId, controller); + } + + return controller; + } + + @Override + public void destroy(DroolsController controller) { + unmanage(controller); + controller.halt(); + } + + @Override + public void destroy() { + List<DroolsController> controllers = this.inventory(); + for (DroolsController controller : controllers) { + controller.halt(); + } + + synchronized (this) { + this.droolsControllers.clear(); + } + } + + /** + * unmanage the drools controller + * + * @param controller + * @return + * @throws IllegalArgumentException + */ + protected void unmanage(DroolsController controller) { + if (controller == null) { + throw new IllegalArgumentException("No controller provided"); + } + + if (!controller.isBrained()) { + logger.info("Drools Controller is NOT OPERATIONAL - nothing to destroy"); + return; + } + + String controllerId = controller.getGroupId() + ":" + controller.getArtifactId(); + synchronized (this) { + if (!this.droolsControllers.containsKey(controllerId)) { + return; + } + + droolsControllers.remove(controllerId); + } + } + + @Override + public void shutdown(DroolsController controller) { + this.unmanage(controller); + controller.shutdown(); + } + + @Override + public void shutdown() { + List<DroolsController> controllers = this.inventory(); + for (DroolsController controller : controllers) { + controller.shutdown(); + } + + synchronized (this) { + this.droolsControllers.clear(); + } + } + + @Override + public DroolsController get(String groupId, String artifactId, String version) { + + if (groupId == null || artifactId == null || groupId.isEmpty() || artifactId.isEmpty()) { + throw new IllegalArgumentException("Missing maven coordinates: " + groupId + ":" + artifactId); + } + + String controllerId = groupId + ":" + artifactId; + + synchronized (this) { + if (this.droolsControllers.containsKey(controllerId)) { + return droolsControllers.get(controllerId); + } else { + throw new IllegalStateException("DroolController for " + controllerId + " not found"); + } + } + } + + @Override + public List<DroolsController> inventory() { + return new ArrayList<>(this.droolsControllers.values()); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("IndexedDroolsControllerFactory [#droolsControllers=").append(droolsControllers.size()) + .append("]"); + return builder.toString(); + } + } diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java index 526b7251..7b44817a 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java @@ -39,7 +39,7 @@ import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.core.PolicyContainer; import org.onap.policy.drools.core.PolicySession; import org.onap.policy.drools.core.jmx.PdpJmx; -import org.onap.policy.drools.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.drools.features.DroolsControllerFeatureAPI; import org.onap.policy.drools.protocol.coders.EventProtocolCoder; import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; diff --git a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java index 245b0b58..31ac1008 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/controller/internal/NullDroolsController.java @@ -27,7 +27,7 @@ import java.util.Map; import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.core.PolicyContainer; -import org.onap.policy.drools.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration; /** diff --git a/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureAPI.java b/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureAPI.java index d4ebc232..94d1b15e 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureAPI.java +++ b/policy-management/src/main/java/org/onap/policy/drools/features/PolicyControllerFeatureAPI.java @@ -22,7 +22,7 @@ package org.onap.policy.drools.features; import java.util.Properties; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.drools.system.PolicyController; import org.onap.policy.drools.utils.OrderedService; import org.onap.policy.drools.utils.OrderedServiceImpl; diff --git a/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java b/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java index 45c5c428..b1e49ec2 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java +++ b/policy-management/src/main/java/org/onap/policy/drools/persistence/FileSystemPersistence.java @@ -31,7 +31,7 @@ import java.util.Arrays; import java.util.List; import java.util.Properties; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.drools.properties.DroolsProperties; import org.onap.policy.drools.utils.PropertyUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -226,9 +226,9 @@ public class FileSystemPersistence implements SystemPersistence { try { final Properties controllerProperties = this.getControllerProperties(name); final String controllerName = - controllerProperties.getProperty(PolicyProperties.PROPERTY_CONTROLLER_NAME); + controllerProperties.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME); if (controllerName == null) { - controllerProperties.setProperty(PolicyProperties.PROPERTY_CONTROLLER_NAME, name); + controllerProperties.setProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME, name); } else if (!controllerName.equals(name)) { logger.error("{}: mismatch controller named {} with file name {}", this, controllerName, controllerFile.getName()); diff --git a/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java b/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java index 15c97237..26bed5e4 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java +++ b/policy-management/src/main/java/org/onap/policy/drools/server/restful/RestManager.java @@ -20,6 +20,8 @@ package org.onap.policy.drools.server.restful; +import ch.qos.logback.classic.LoggerContext; + import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -43,18 +45,19 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; +import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicSink; +import org.onap.policy.common.endpoints.event.comm.bus.DmaapTopicSource; +import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink; +import org.onap.policy.common.endpoints.event.comm.bus.UebTopicSink; +import org.onap.policy.common.endpoints.event.comm.bus.UebTopicSource; +import org.onap.policy.common.endpoints.event.comm.impl.ProxyTopicEndpointManager; import org.onap.policy.drools.controller.DroolsController; -import org.onap.policy.drools.event.comm.TopicEndpoint; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.TopicSource; -import org.onap.policy.drools.event.comm.bus.DmaapTopicSink; -import org.onap.policy.drools.event.comm.bus.DmaapTopicSource; -import org.onap.policy.drools.event.comm.bus.NoopTopicSink; -import org.onap.policy.drools.event.comm.bus.UebTopicSink; -import org.onap.policy.drools.event.comm.bus.UebTopicSource; import org.onap.policy.drools.features.PolicyControllerFeatureAPI; import org.onap.policy.drools.features.PolicyEngineFeatureAPI; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.drools.properties.DroolsProperties; import org.onap.policy.drools.protocol.coders.EventProtocolCoder; import org.onap.policy.drools.protocol.coders.EventProtocolCoder.CoderFilters; import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; @@ -68,7 +71,6 @@ import org.onap.policy.drools.utils.logging.LoggerUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import ch.qos.logback.classic.LoggerContext; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @@ -87,2076 +89,1926 @@ import io.swagger.annotations.Tag; @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Api -@SwaggerDefinition( - info = @Info(description = "PDP-D Telemetry Services", version = "v1.0", - title = "PDP-D Telemetry"), - consumes = {MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}, - produces = {MediaType.APPLICATION_JSON}, schemes = {SwaggerDefinition.Scheme.HTTP}, - tags = {@Tag(name = "pdp-d-telemetry", description = "Drools PDP Telemetry Operations")}) +@SwaggerDefinition(info = @Info(description = "PDP-D Telemetry Services", version = "v1.0", title = "PDP-D Telemetry"), + consumes = {MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}, produces = {MediaType.APPLICATION_JSON}, + schemes = {SwaggerDefinition.Scheme.HTTP}, + tags = {@Tag(name = "pdp-d-telemetry", description = "Drools PDP Telemetry Operations")}) public class RestManager { - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(RestManager.class); - - @GET - @Path("engine") - @ApiOperation(value = "Retrieves the Engine Operational Status", - notes = "Top-level abstraction. Provides a global view of resources", - response = PolicyEngine.class) - public Response engine() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); - } - - @DELETE - @Path("engine") - @ApiOperation(value = "Shuts down the Engine", - notes = "Deleting the engine, the top-level abstraction, equivalenty shuts it down", - response = PolicyEngine.class) - public Response engineShutdown() { - try { - PolicyEngine.manager.shutdown(); - } catch (final IllegalStateException e) { - logger.error("{}: cannot shutdown {} because of {}", this, PolicyEngine.manager, - e.getMessage(), e); - return Response.status(Response.Status.BAD_REQUEST).entity(PolicyEngine.manager).build(); - } - - return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); - } - - @GET - @Path("engine/features") - @ApiOperation(value = "Engine Features", - notes = "Provides the list of loaded features using the PolicyEngineFeatureAPI", - responseContainer = "List") - public Response engineFeatures() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatures()).build(); - } - - @GET - @Path("engine/features/inventory") - @ApiOperation(value = "Engine Detailed Feature Inventory", - notes = "Provides detailed list of loaded features using the PolicyEngineFeatureAPI", - responseContainer = "List", response = PolicyEngineFeatureAPI.class) - public Response engineFeaturesInventory() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatureProviders()) - .build(); - } - - @GET - @Path("engine/features/{featureName}") - @ApiOperation(value = "Engine Feature", - notes = "Provides Details for a given feature Engine Provider", - response = PolicyEngineFeatureAPI.class) - @ApiResponses(value = {@ApiResponse(code = 404, message = "The feature cannot be found")}) - public Response engineFeature(@ApiParam(value = "Feature Name", - required = true) @PathParam("featureName") String featureName) { - try { - return Response.status(Response.Status.OK) - .entity(PolicyEngine.manager.getFeatureProvider(featureName)).build(); - } catch (final IllegalArgumentException iae) { - logger.debug("feature unavailable: {}", featureName, iae); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(iae.getMessage())).build(); - } - } - - @GET - @Path("engine/inputs") - @ApiOperation(value = "Engine Input Ports", notes = "List of input ports", - responseContainer = "List") - public Response engineInputs() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Inputs.values())).build(); - } - - @POST - @Path("engine/inputs/configuration") - @ApiOperation(value = "Engine Input Configuration Requests", - notes = "Feeds a configuration request input into the Engine") - @ApiResponses( - value = {@ApiResponse(code = 406, message = "The configuration request cannot be honored")}) - public Response engineUpdate(@ApiParam(value = "Configuration to apply", - required = true) PdpdConfiguration configuration) { - final PolicyController controller = null; - boolean success = true; - try { - success = PolicyEngine.manager.configure(configuration); - } catch (final Exception e) { - success = false; - logger.info("{}: cannot configure {} because of {}", this, PolicyEngine.manager, - e.getMessage(), e); - } - - if (!success) - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error("cannot perform operation")).build(); - else - return Response.status(Response.Status.OK).entity(controller).build(); - } - - @GET - @Path("engine/properties") - @ApiOperation(value = "Engine Configuration Properties", - notes = "Used for booststrapping the engine", response = Properties.class) - public Response engineProperties() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getProperties()).build(); - } - - @GET - @Path("engine/environment") - @ApiOperation(value = "Engine Environment Properties", - notes = "Installation and OS environment properties used by the engine", - response = Properties.class) - public Response engineEnvironment() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getEnvironment()) - .build(); - } - - @GET - @Path("engine/environment/{envProperty}") - @Consumes(MediaType.TEXT_PLAIN) - @ApiOperation(value = "Gets an environment variable", response = String.class) - public Response engineEnvironment(@ApiParam(value = "Environment Property", - required = true) @PathParam("envProperty") String envProperty) { - return Response.status(Response.Status.OK) - .entity(PolicyEngine.manager.getEnvironmentProperty(envProperty)).build(); - } - - @PUT - @Path("engine/environment/{envProperty}") - @Consumes(MediaType.TEXT_PLAIN) - @Produces(MediaType.TEXT_PLAIN) - @ApiOperation(value = "Adds a new environment value to the engine", response = String.class) - public Response engineEnvironmentAdd( - @ApiParam(value = "Environment Property", - required = true) @PathParam("envProperty") String envProperty, - @ApiParam(value = "Environment Value", required = true) String envValue) { - final String previousValue = PolicyEngine.manager.setEnvironmentProperty(envProperty, envValue); - return Response.status(Response.Status.OK).entity(previousValue).build(); - } - - @GET - @Path("engine/switches") - @ApiOperation(value = "Engine Control Switches", notes = "List of the Engine Control Switches", - responseContainer = "List") - public Response engineSwitches() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); - } - - @PUT - @Path("engine/switches/activation") - @ApiOperation(value = "Switches on the Engine Activation Switch", - notes = "Turns on Activation Switch on the Engine. This order entails that the engine " - + "and controllers are unlocked and started", - response = PolicyEngine.class) - public Response engineActivation() { - boolean success = true; - try { - PolicyEngine.manager.activate(); - } catch (final Exception e) { - success = false; - logger.info("{}: cannot activate {} because of {}", this, PolicyEngine.manager, - e.getMessage(), e); - } - - if (!success) - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error("cannot perform operation")).build(); - else - return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); - } - - @DELETE - @Path("engine/switches/activation") - @ApiOperation(value = "Switches off Engine Activation Switch", - notes = "Turns off the Activation Switch on the Engine. This order entails that the engine " - + "and controllers are locked (with the exception of those resources defined as unmanaged)", - response = PolicyEngine.class) - public Response engineDeactivation() { - boolean success = true; - try { - PolicyEngine.manager.deactivate(); - } catch (final Exception e) { - success = false; - logger.info("{}: cannot deactivate {} because of {}", this, PolicyEngine.manager, - e.getMessage(), e); - } - - if (!success) - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error("cannot perform operation")).build(); - else - return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); - } - - @PUT - @Path("engine/switches/lock") - @ApiOperation(value = "Switches on the Engine Lock Control", - notes = "This switch locks all the engine resources as a whole, except those that are defined unmanaged", - response = PolicyEngine.class) - @ApiResponses(value = { - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response engineLock() { - final boolean success = PolicyEngine.manager.lock(); - if (success) - return Response.status(Status.OK).entity(PolicyEngine.manager).build(); - else - return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")) - .build(); - } - - @DELETE - @Path("engine/switches/lock") - @ApiOperation(value = "Switches off the Lock control", - notes = "This switch locks all the engine resources as a whole, except those that are defined unmanaged", - response = PolicyEngine.class) - @ApiResponses(value = { - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response engineUnlock() { - final boolean success = PolicyEngine.manager.unlock(); - if (success) - return Response.status(Status.OK).entity(PolicyEngine.manager).build(); - else - return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")) - .build(); - } - - @GET - @Path("engine/controllers") - @ApiOperation(value = "Lists the Policy Controllers Names", - notes = "Unique Policy Controller Identifiers", responseContainer = "List") - public Response controllers() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getPolicyControllerIds()) - .build(); - } - - @GET - @Path("engine/controllers/inventory") - @ApiOperation(value = "Lists the Policy Controllers", - notes = "Detailed list of Policy Controllers", responseContainer = "List", - response = PolicyController.class) - public Response controllerInventory() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getPolicyControllers()) - .build(); - } - - @POST - @Path("engine/controllers") - @ApiOperation(value = "Creates and starts a new Policy Controller", - notes = "Controller creation based on properties", response = PolicyController.class) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid configuration information has been provided"), - @ApiResponse(code = 304, message = "The controller already exists"), - @ApiResponse(code = 406, - message = "The administrative state of the system prevents it " - + "from processing this request"), - @ApiResponse(code = 206, - message = "The controller has been created " + "but cannot be started"), - @ApiResponse(code = 201, - message = "The controller has been succesfully created and started")}) - public Response controllerAdd( - @ApiParam(value = "Configuration Properties to apply", required = true) Properties config) { - if (config == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error("A configuration must be provided")).build(); - - final String controllerName = config.getProperty(PolicyProperties.PROPERTY_CONTROLLER_NAME); - if (controllerName == null || controllerName.isEmpty()) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error( - "Configuration must have an entry for " + PolicyProperties.PROPERTY_CONTROLLER_NAME)) - .build(); - - PolicyController controller; - try { - controller = PolicyController.factory.get(controllerName); - if (controller != null) - return Response.status(Response.Status.NOT_MODIFIED).entity(controller).build(); - } catch (final IllegalArgumentException e) { - logger.trace("OK ", e); - // This is OK - } catch (final IllegalStateException e) { - logger.info("{}: cannot get policy-controller because of {}", this, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " not found")).build(); - } - - try { - controller = PolicyEngine.manager.createPolicyController( - config.getProperty(PolicyProperties.PROPERTY_CONTROLLER_NAME), config); - } catch (IllegalArgumentException | IllegalStateException e) { - logger.warn("{}: cannot create policy-controller because of {}", this, e.getMessage(), e); - return Response.status(Response.Status.BAD_REQUEST).entity(new Error(e.getMessage())).build(); - } - - try { - final boolean success = controller.start(); - if (!success) { - logger.info("{}: cannot start {}", this, controller); - return Response.status(Response.Status.PARTIAL_CONTENT) - .entity(new Error(controllerName + " can't be started")).build(); - } - } catch (final IllegalStateException e) { - logger.info("{}: cannot start {} because of {}", this, controller, e.getMessage(), e);; - return Response.status(Response.Status.PARTIAL_CONTENT).entity(controller).build(); - } - - return Response.status(Response.Status.CREATED).entity(controller).build(); - } - - @GET - @Path("engine/controllers/features") - @ApiOperation(value = "Lists of Feature Providers Identifiers", - notes = "Unique Policy Controller Identifiers", responseContainer = "List") - public Response controllerFeatures() { - return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatures()).build(); - } - - @GET - @Path("engine/controllers/features/inventory") - @ApiOperation(value = "Detailed Controllers Feature Inventory", - notes = "Provides detailed list of loaded features using the PolicyControllerFeatureAPI", - responseContainer = "List", response = PolicyControllerFeatureAPI.class) - public Response controllerFeaturesInventory() { - return Response.status(Response.Status.OK) - .entity(PolicyController.factory.getFeatureProviders()).build(); - } - - @GET - @Path("engine/controllers/features/{featureName}") - @ApiOperation(value = "Controller Feature", - notes = "Provides Details for a given Policy Controller feature provider", - response = PolicyControllerFeatureAPI.class) - @ApiResponses(value = {@ApiResponse(code = 404, message = "The feature cannot be found")}) - public Response controllerFeature(@ApiParam(value = "Feature Name", - required = true) @PathParam("featureName") String featureName) { - try { - return Response.status(Response.Status.OK) - .entity(PolicyController.factory.getFeatureProvider(featureName)).build(); - } catch (final IllegalArgumentException iae) { - logger.debug("{}: cannot feature {} because of {}", this, featureName, iae.getMessage(), iae); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(iae.getMessage())).build(); - } - } - - @GET - @Path("engine/controllers/{controller}") - @ApiOperation(value = "Retrieves a Policy Controller", - notes = "A Policy Controller is a concrete drools application abstraction. " - + "It aggregates networking, drools, and other resources," - + "as provides operational controls over drools applications", - response = PolicyController.class) - @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response controller(@ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName) { - try { - return Response.status(Response.Status.OK) - .entity(PolicyController.factory.get(controllerName)).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " not acceptable")).build(); - } - } - - @DELETE - @Path("engine/controllers/{controller}") - @ApiOperation(value = "Deletes a Policy Controller", - notes = "A Policy Controller is a concrete drools application abstraction. " - + "It aggregates networking, drools, and other resources," - + "as provides operational controls over drools applications", - response = PolicyController.class) - @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller cannot be found"), - @ApiResponse(code = 406, - message = "The system is an administrative state that prevents " - + "this request to be fulfilled"), - @ApiResponse(code = 500, - message = "A problem has occurred while deleting the Policy Controller")}) - public Response controllerDelete(@ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName) { - - PolicyController controller; - try { - controller = PolicyController.factory.get(controllerName); - if (controller == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + " does not exist")).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + " not found: " + e.getMessage())).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " not acceptable")).build(); - } - - try { - PolicyEngine.manager.removePolicyController(controllerName); - } catch (IllegalArgumentException | IllegalStateException e) { - logger.debug("{}: cannot remove policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Error(e.getMessage())).build(); - } - - return Response.status(Response.Status.OK).entity(controller).build(); - } - - @GET - @Path("engine/controllers/{controller}/properties") - @ApiOperation(value = "Retrieves the configuration properties of a Policy Controller", - notes = "Configuration resources used by the controller if Properties format", - response = PolicyController.class) - @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response controllerProperties(@ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName) { - try { - final PolicyController controller = PolicyController.factory.get(controllerName); - return Response.status(Response.Status.OK).entity(controller.getProperties()).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " not acceptable")).build(); - } - } - - @GET - @Path("engine/controllers/{controller}/inputs") - @ApiOperation(value = "Policy Controller Input Ports", notes = "List of input ports", - responseContainer = "List") - public Response controllerInputs() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Inputs.values())).build(); - } - - @POST - @Path("engine/controllers/{controller}/inputs/configuration") - @ApiOperation(value = "Policy Controller Input Configuration Requests", - notes = "Feeds a configuration request input into the given Policy Controller") - @ApiResponses(value = {@ApiResponse(code = 400, message = "The configuration request is invalid"), - @ApiResponse(code = 406, message = "The configuration request cannot be honored")}) - public Response controllerUpdate( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Configuration to apply", - required = true) ControllerConfiguration controllerConfiguration) { - - if (controllerName == null || controllerName.isEmpty() || controllerConfiguration == null - || controllerConfiguration.getName().intern() != controllerName) - return Response.status(Response.Status.BAD_REQUEST) - .entity("A valid or matching controller names must be provided").build(); - - PolicyController controller; - try { - controller = PolicyEngine.manager.updatePolicyController(controllerConfiguration); - if (controller == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + " does not exist")).build(); - } catch (final IllegalArgumentException e) { - logger.info("{}: cannot update policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + " not found: " + e.getMessage())).build(); - } catch (final Exception e) { - logger.info("{}: cannot update policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " not acceptable")).build(); - } - - return Response.status(Response.Status.OK).entity(controller).build(); - } - - @GET - @Path("engine/controllers/{controller}/switches") - @ApiOperation(value = "Policy Controller Switches", - notes = "List of the Policy Controller Switches", responseContainer = "List") - public Response controllerSwitches() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); - } - - @PUT - @Path("engine/controllers/{controller}/switches/lock") - @ApiOperation(value = "Switches on the Policy Controller Lock Control", - notes = "This action on the switch locks the Policy Controller", - response = PolicyController.class) - @ApiResponses(value = { - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response controllerLock(@ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName) { - final PolicyController policyController = PolicyController.factory.get(controllerName); - final boolean success = policyController.lock(); - if (success) - return Response.status(Status.OK).entity(policyController).build(); - else - return Response.status(Status.NOT_ACCEPTABLE) - .entity(new Error("Controller " + controllerName + " cannot be locked")).build(); - } - - @DELETE - @Path("engine/controllers/{controller}/switches/lock") - @ApiOperation(value = "Switches off the Policy Controller Lock Control", - notes = "This action on the switch unlocks the Policy Controller", - response = PolicyController.class) - @ApiResponses(value = { - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response controllerUnlock(@ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName) { - final PolicyController policyController = PolicyController.factory.get(controllerName); - final boolean success = policyController.unlock(); - if (success) - return Response.status(Status.OK).entity(policyController).build(); - else - return Response.status(Status.NOT_ACCEPTABLE) - .entity(new Error("Controller " + controllerName + " cannot be unlocked")).build(); - } - - @GET - @Path("engine/controllers/{controller}/drools") - @ApiOperation(value = "Retrieves the Drools Controller subcomponent of the Policy Controller", - notes = "The Drools Controller provides an abstraction over the Drools subsystem", - response = DroolsController.class) - @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response drools(@ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - return Response.status(Response.Status.OK).entity(drools).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " not acceptable")).build(); - } - } - - @GET - @Path("engine/controllers/{controller}/drools/facts") - @ApiOperation(value = "Retrieves Facts Summary information for a given controller", - notes = "Provides the session names, and a count of fact object in the drools working memory", - responseContainer = "Map") - @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response droolsFacts(@ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName) { - try { - final Map<String, Long> sessionCounts = new HashMap<>(); - final DroolsController drools = this.getDroolsController(controllerName); - for (final String session : drools.getSessionNames()) { - sessionCounts.put(session, drools.factCount(session)); - } - return Response.status(Response.Status.OK).entity(sessionCounts).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " not acceptable")).build(); - } - } - - @GET - @Path("engine/controllers/{controller}/drools/facts/{session}") - @ApiOperation(value = "Retrieves Fact Types (classnames) for a given controller and its count", - notes = "The fact types are the classnames of the objects inserted in the drools working memory", - responseContainer = "Map") - @ApiResponses( - value = {@ApiResponse(code = 404, message = "The controller or session cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response droolsFacts( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Drools Session Name", - required = true) @PathParam("session") String sessionName) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - return Response.status(Response.Status.OK).entity(drools.factClassNames(sessionName)).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error("entity not found")) - .build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + sessionName + " not acceptable")).build(); - } - } - - @GET - @Path("engine/controllers/{controller}/drools/facts/{session}/{factType}") - @ApiOperation( - value = "Retrieves fact objects of a given type in the drools working memory" - + "for a given controller and session", - notes = "The fact types are the classnames of the objects inserted in the drools working memory", - responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = 404, message = "The controller, session, or fact type cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response droolsFacts( - @ApiParam(value = "Fact count", - required = false) @DefaultValue("false") @QueryParam("count") boolean count, - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Drools Session Name", - required = true) @PathParam("session") String sessionName, - @ApiParam(value = "Drools Fact Type", - required = true) @PathParam("factType") String factType) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final List<Object> facts = drools.facts(sessionName, factType, false); - if (!count) - return Response.status(Response.Status.OK).entity(facts).build(); - else - return Response.status(Response.Status.OK).entity(facts.size()).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + sessionName + ":" + factType + " not found")) - .build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity( - new Error(controllerName + ":" + sessionName + ":" + factType + " not acceptable")) - .build(); - } - } - - @DELETE - @Path("engine/controllers/{controller}/drools/facts/{session}/{factType}") - @ApiOperation( - value = "Deletes all the fact objects of a given type from the drools working memory" - + "for a given controller and session. The objects retracted from the working " - + "memory are provided in the response.", - notes = "The fact types are the classnames of the objects inserted in the drools working memory", - responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = 404, message = "The controller, session, or fact type, cannot be found"), - @ApiResponse(code = 406, - message = "The system is an administrative state that prevents " - + "this request to be fulfilled"), - @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) - public Response droolsFactsDelete( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Drools Session Name", - required = true) @PathParam("session") String sessionName, - @ApiParam(value = "Drools Fact Type", - required = true) @PathParam("factType") String factType) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final List<Object> facts = drools.facts(sessionName, factType, true); - return Response.status(Response.Status.OK).entity(facts).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get: drools-controller {}, session {}, factType {}, because of {}", - this, controllerName, sessionName, factType, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + sessionName + ":" + factType + " not found")) - .build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get: drools-controller {}, session {}, factType {}, because of {}", - this, controllerName, sessionName, factType, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity( - new Error(controllerName + ":" + sessionName + ":" + factType + " not acceptable")) - .build(); - } catch (final Exception e) { - logger.debug("{}: cannot get: drools-controller {}, session {}, factType {}, because of {}", - this, controllerName, sessionName, factType, e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Error(e.getMessage())).build(); - } - } - - @GET - @Path("engine/controllers/{controller}/drools/facts/{session}/{query}/{queriedEntity}") - @ApiOperation( - value = "Gets all the fact objects returned by a DRL query with no parameters from the drools working memory" - + "for a given controller and session", - notes = "The DRL query must be defined in the DRL file", responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = 404, - message = "The controller, session, or query information, cannot be found"), - @ApiResponse(code = 406, - message = "The system is an administrative state that prevents " - + "this request to be fulfilled"), - @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) - public Response droolsFacts( - @ApiParam(value = "Fact count", - required = false) @DefaultValue("false") @QueryParam("count") boolean count, - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Drools Session Name", - required = true) @PathParam("session") String sessionName, - @ApiParam(value = "Query Name Present in DRL", - required = true) @PathParam("query") String queryName, - @ApiParam(value = "Query Identifier Present in the DRL Query", - required = true) @PathParam("queriedEntity") String queriedEntity) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final List<Object> facts = drools.factQuery(sessionName, queryName, queriedEntity, false); - if (!count) - return Response.status(Response.Status.OK).entity(facts).build(); - else - return Response.status(Response.Status.OK).entity(facts.size()).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}", - this, controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not found")) - .build(); - } catch (final IllegalStateException e) { - logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}", - this, controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not acceptable")) - .build(); - } catch (final Exception e) { - logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}", - this, controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Error(e.getMessage())).build(); - } - } - - @POST - @Path("engine/controllers/{controller}/drools/facts/{session}/{query}/{queriedEntity}") - @ApiOperation( - value = "Gets all the fact objects returned by a DRL query with parameters from the drools working memory" - + "for a given controller and session", - notes = "The DRL query with parameters must be defined in the DRL file", - responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = 404, - message = "The controller, session, or query information, cannot be found"), - @ApiResponse(code = 406, - message = "The system is an administrative state that prevents " - + "this request to be fulfilled"), - @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) - public Response droolsFacts( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Drools Session Name", - required = true) @PathParam("session") String sessionName, - @ApiParam(value = "Query Name Present in DRL", - required = true) @PathParam("query") String queryName, - @ApiParam(value = "Query Identifier Present in the DRL Query", - required = true) @PathParam("queriedEntity") String queriedEntity, - @ApiParam(value = "Query Parameter Values to pass in the DRL Query", - required = false) List<Object> queryParameters) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - List<Object> facts; - if (queryParameters == null || queryParameters.isEmpty()) - facts = drools.factQuery(sessionName, queryName, queriedEntity, false); - else - facts = drools.factQuery(sessionName, queryName, queriedEntity, false, - queryParameters.toArray()); - return Response.status(Response.Status.OK).entity(facts).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", - this, controllerName, sessionName, queryName, queriedEntity, queryParameters, - e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not found")) - .build(); - } catch (final IllegalStateException e) { - logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", - this, controllerName, sessionName, queryName, queriedEntity, queryParameters, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not acceptable")) - .build(); - } catch (final Exception e) { - logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", - this, controllerName, sessionName, queryName, queriedEntity, queryParameters, - e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Error(e.getMessage())).build(); - } - } - - @DELETE - @Path("engine/controllers/{controller}/drools/facts/{session}/{query}/{queriedEntity}") - @ApiOperation( - value = "Deletes all the fact objects returned by a DRL query with parameters from the drools working memory" - + "for a given controller and session", - notes = "The DRL query with parameters must be defined in the DRL file", - responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = 404, - message = "The controller, session, or query information, cannot be found"), - @ApiResponse(code = 406, - message = "The system is an administrative state that prevents " - + "this request to be fulfilled"), - @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) - public Response droolsFactsDelete( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Drools Session Name", - required = true) @PathParam("session") String sessionName, - @ApiParam(value = "Query Name Present in DRL", - required = true) @PathParam("query") String queryName, - @ApiParam(value = "Query Identifier Present in the DRL Query", - required = true) @PathParam("queriedEntity") String queriedEntity, - @ApiParam(value = "Query Parameter Values to pass in the DRL Query", - required = false) List<Object> queryParameters) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - List<Object> facts; - if (queryParameters == null || queryParameters.isEmpty()) - facts = drools.factQuery(sessionName, queryName, queriedEntity, true); - else - facts = drools.factQuery(sessionName, queryName, queriedEntity, true, - queryParameters.toArray()); - return Response.status(Response.Status.OK).entity(facts).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", - this, controllerName, sessionName, queryName, queriedEntity, queryParameters, - e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not found")) - .build(); - } catch (final IllegalStateException e) { - logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", - this, controllerName, sessionName, queryName, queriedEntity, queryParameters, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not acceptable")) - .build(); - } catch (final Exception e) { - logger.debug( - "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", - this, controllerName, sessionName, queryName, queriedEntity, queryParameters, - e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Error(e.getMessage())).build(); - } - } - - @POST - @Path("engine/controllers/tools/coders/decoders/filters/rules/{ruleName}") - @ApiOperation( - value = "Produces a Decoder Rule Filter in a format that the Policy Controller can understand", - notes = "The result can be used with other APIs to attach a filter to a decoder") - public Response rules( - @ApiParam(value = "Negate regex?", - required = true) @DefaultValue("false") @QueryParam("negate") boolean negate, - @ApiParam(value = "Rule Name", required = true) @PathParam("ruleName") String name, - @ApiParam(value = "Regex expression", required = true) String regex) { - String literalRegex = Pattern.quote(regex); - if (negate) - literalRegex = "^(?!" + literalRegex + "$).*"; - - return Response.status(Status.OK).entity(new JsonProtocolFilter.FilterRule(name, literalRegex)) - .build(); - } - - @GET - @Path("engine/controllers/{controller}/decoders") - @ApiOperation(value = "Gets all the decoders used by a controller", - notes = "A Policy Controller uses decoders to deserialize incoming network messages from " - + "subscribed network topics into specific (fact) objects. " - + "The deserialized (fact) object will typically be inserted in the drools working " - + " memory of the controlled drools application.", - responseContainer = "List", response = ProtocolCoderToolset.class) - @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decoders(@ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final List<ProtocolCoderToolset> decoders = - EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId()); - return Response.status(Response.Status.OK).entity(decoders).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, - controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, - controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " not acceptable")).build(); - } - } - - @GET - @Path("engine/controllers/{controller}/decoders/filters") - @ApiOperation(value = "Gets all the filters used by a controller", - notes = "A Policy Controller uses decoders to deserialize incoming network messages from " - + "subscribed network topics into specific (fact) objects. " - + "The deserialized (fact) object will typically be inserted in the drools working " - + " memory of the controlled drools application." - + "Acceptance filters are used to filter out undesired network messages for the given controller", - responseContainer = "List", response = CoderFilters.class) - @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decoderFilters(@ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final List<CoderFilters> filters = - EventProtocolCoder.manager.getDecoderFilters(drools.getGroupId(), drools.getArtifactId()); - return Response.status(Response.Status.OK).entity(filters).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, - controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, - controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " not acceptable")).build(); - } - } - - @GET - @Path("engine/controllers/{controller}/decoders/{topic}") - @ApiOperation(value = "Gets all the decoders in use by a controller for a networked topic", - notes = "A Policy Controller uses decoders to deserialize incoming network messages from " - + "subscribed network topics into specific (fact) objects. " - + "The deserialized (fact) object will typically be inserted in the drools working " - + " memory of the controlled drools application.", - responseContainer = "List", response = ProtocolCoderToolset.class) - @ApiResponses( - value = {@ApiResponse(code = 404, message = "The controller or topic cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decoder( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Networked Topic Name", required = true) @PathParam("topic") String topic) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = EventProtocolCoder.manager - .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); - return Response.status(Response.Status.OK).entity(decoder).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + " not acceptable")).build(); - } - } - - @GET - @Path("engine/controllers/{controller}/decoders/{topic}/filters") - @ApiOperation( - value = "Gets all filters attached to decoders for a given networked topic in use by a controller", - notes = "A Policy Controller uses decoders to deserialize incoming network messages from " - + "subscribed network topics into specific (fact) objects. " - + "The deserialized (fact) object will typically be inserted in the drools working " - + " memory of the controlled drools application." - + "Acceptance filters are used to filter out undesired network messages for the given controller", - responseContainer = "List", response = CoderFilters.class) - @ApiResponses( - value = {@ApiResponse(code = 404, message = "The controller or topic cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decoderFilter( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Networked Topic Name", required = true) @PathParam("topic") String topic) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = EventProtocolCoder.manager - .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); - if (decoder == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(topic + " does not exist")).build(); - else - return Response.status(Response.Status.OK).entity(decoder.getCoders()).build(); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + " not acceptable")).build(); - } - } - - @GET - @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}") - @ApiOperation( - value = "Gets all filters attached to decoders for a given subscribed networked topic " - + "and fact type", - notes = "Decoders are associated with networked topics. A Policy Controller manages " - + "multiple topics and therefore its attached decoders. " - + "A Policy Controller uses filters to further specify the fact mapping. " - + "Filters are applied on a per fact type (classname).", - responseContainer = "List", response = CoderFilters.class) - @ApiResponses(value = { - @ApiResponse(code = 404, message = "The controller, topic, or fact type cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decoderFilter( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Networked Topic Name", required = true) @PathParam("topic") String topic, - @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = EventProtocolCoder.manager - .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); - final CoderFilters filters = decoder.getCoder(factClass); - if (filters == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(topic + ":" + factClass + " does not exist")).build(); - else - return Response.status(Response.Status.OK).entity(filters).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", - this, controllerName, topic, factClass, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", - this, controllerName, topic, factClass, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")) - .build(); - } - } - - @PUT - @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}") - @ApiOperation( - value = "Attaches filters to the decoder for a given networked topic " + "and fact type", - notes = "Decoders are associated with networked topics. A Policy Controller manages " - + "multiple topics and therefore its attached decoders. " - + "A Policy Controller uses filters to further specify the fact mapping. " - + "Filters are applied on a per fact type (classname).", - responseContainer = "List", response = CoderFilters.class) - @ApiResponses(value = { - @ApiResponse(code = 404, - message = "The controller, topic, fact type, cannot be found, " - + "or a filter has not been provided"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decoderFilter( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, - @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass, - @ApiParam(value = "Configuration Filter", required = true) JsonProtocolFilter configFilters) { - - if (configFilters == null) { - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error("Configuration Filters not provided")).build(); - } - - try { - final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = EventProtocolCoder.manager - .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); - final CoderFilters filters = decoder.getCoder(factClass); - if (filters == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(topic + ":" + factClass + " does not exist")).build(); - filters.setFilter(configFilters); - return Response.status(Response.Status.OK).entity(filters).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} filters {} because of {}", - this, controllerName, topic, factClass, configFilters, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} filters {} because of {}", - this, controllerName, topic, factClass, configFilters, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")) - .build(); - } - } - - @GET - @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rules") - @ApiOperation(value = "Gets the filter rules attached to a topic decoder of a controller", - notes = "Decoders are associated with networked topics. A Policy Controller manages " - + "multiple topics and therefore its attached decoders. " - + "A Policy Controller uses filters to further specify the fact mapping. " - + "Filters are applied on a per fact type and are composed of field matching rules. ", - responseContainer = "List", response = FilterRule.class) - @ApiResponses(value = { - @ApiResponse(code = 404, message = "The controller, topic, or fact type cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decoderFilterRules( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, - @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = EventProtocolCoder.manager - .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); - - final CoderFilters filters = decoder.getCoder(factClass); - if (filters == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")) - .build(); - - final JsonProtocolFilter filter = filters.getFilter(); - if (filter == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")) - .build(); - - return Response.status(Response.Status.OK).entity(filter.getRules()).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", - this, controllerName, topic, factClass, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", - this, controllerName, topic, factClass, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")) - .build(); - } - } - - @GET - @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rules/{ruleName}") - @ApiOperation(value = "Gets a filter rule by name attached to a topic decoder of a controller", - notes = "Decoders are associated with networked topics. A Policy Controller manages " - + "multiple topics and therefore its attached decoders. " - + "A Policy Controller uses filters to further specify the fact mapping. " - + "Filters are applied on a per fact type and are composed of field matching rules. ", - responseContainer = "List", response = FilterRule.class) - @ApiResponses(value = { - @ApiResponse(code = 404, - message = "The controller, topic, fact type, or rule name cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decoderFilterRules( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, - @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass, - @ApiParam(value = "Rule Name", required = true) @PathParam("ruleName") String ruleName) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = EventProtocolCoder.manager - .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); - - final CoderFilters filters = decoder.getCoder(factClass); - if (filters == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")) - .build(); - - final JsonProtocolFilter filter = filters.getFilter(); - if (filter == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")) - .build(); - - return Response.status(Response.Status.OK).entity(filter.getRules(ruleName)).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} rule {} because of {}", - this, controllerName, topic, factClass, ruleName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error( - controllerName + ":" + topic + ":" + factClass + ": " + ruleName + " not found")) - .build(); - } catch (final IllegalStateException e) { - logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} rule {} because of {}", - this, controllerName, topic, factClass, ruleName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error( - controllerName + ":" + topic + ":" + factClass + ":" + ruleName + " not acceptable")) - .build(); - } - } - - @DELETE - @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rules/{ruleName}") - @ApiOperation(value = "Deletes a filter rule by name attached to a topic decoder of a controller", - notes = "Decoders are associated with networked topics. A Policy Controller manages " - + "multiple topics and therefore its attached decoders. " - + "A Policy Controller uses filters to further specify the fact mapping. " - + "Filters are applied on a per fact type and are composed of field matching rules. ", - responseContainer = "List", response = FilterRule.class) - @ApiResponses(value = { - @ApiResponse(code = 404, - message = "The controller, topic, fact type, or rule name cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decoderFilterRuleDelete( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, - @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass, - @ApiParam(value = "Rule Name", required = true) @PathParam("ruleName") String ruleName, - @ApiParam(value = "Filter Rule", required = true) FilterRule rule) { - - try { - final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = EventProtocolCoder.manager - .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); - - final CoderFilters filters = decoder.getCoder(factClass); - if (filters == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")) - .build(); - - final JsonProtocolFilter filter = filters.getFilter(); - if (filter == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")) - .build(); - - if (rule == null) { - filter.deleteRules(ruleName); - return Response.status(Response.Status.OK).entity(filter.getRules()).build(); - } - - if (rule.getName() == null || !rule.getName().equals(ruleName)) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + ":" + ruleName - + " rule name request inconsistencies (" + rule.getName() + ")")) - .build(); - - filter.deleteRule(ruleName, rule.getRegex()); - return Response.status(Response.Status.OK).entity(filter.getRules()).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} rule {} because of {}", - this, controllerName, topic, factClass, ruleName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error( - controllerName + ":" + topic + ":" + factClass + ": " + ruleName + " not found")) - .build(); - } catch (final IllegalStateException e) { - logger.debug( - "{}: cannot get decoder filters for policy-controller {} topic {} type {} rule {} because of {}", - this, controllerName, topic, factClass, ruleName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error( - controllerName + ":" + topic + ":" + factClass + ":" + ruleName + " not acceptable")) - .build(); - } - } - - @PUT - @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rules") - @ApiOperation(value = "Places a new filter rule in a topic decoder", - notes = "Decoders are associated with networked topics. A Policy Controller manages " - + "multiple topics and therefore its attached decoders. " - + "A Policy Controller uses filters to further specify the fact mapping. " - + "Filters are applied on a per fact type and are composed of field matching rules. ", - responseContainer = "List", response = FilterRule.class) - @ApiResponses(value = { - @ApiResponse(code = 404, message = "The controller, topic, or fact type cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decoderFilterRule( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, - @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass, - @ApiParam(value = "Rule Name", required = true) @PathParam("ruleName") String ruleName, - @ApiParam(value = "Filter Rule", required = true) FilterRule rule) { - - try { - final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = EventProtocolCoder.manager - .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); - - final CoderFilters filters = decoder.getCoder(factClass); - if (filters == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")) - .build(); - - final JsonProtocolFilter filter = filters.getFilter(); - if (filter == null) - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")) - .build(); - - if (rule.getName() == null) - return Response - .status(Response.Status.BAD_REQUEST).entity(new Error(controllerName + ":" + topic + ":" - + factClass + " rule name request inconsistencies (" + rule.getName() + ")")) - .build(); - - filter.addRule(rule.getName(), rule.getRegex()); - return Response.status(Response.Status.OK).entity(filter.getRules()).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - "{}: cannot access decoder filter rules for policy-controller {} topic {} type {} rule {} because of {}", - this, controllerName, topic, factClass, ruleName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug( - "{}: cannot access decoder filter rules for policy-controller {} topic {} type {} rule {} because of {}", - this, controllerName, topic, factClass, ruleName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")) - .build(); - } - } - - @POST - @Path("engine/controllers/{controller}/decoders/{topic}") - @Consumes(MediaType.TEXT_PLAIN) - @ApiOperation(value = "Decodes a string into a fact object, and encodes it back into a string", - notes = "Tests the decode/encode functions of a controller", response = CodingResult.class) - @ApiResponses(value = {@ApiResponse(code = 400, message = "Bad input has been provided"), - @ApiResponse(code = 404, message = "The controller cannot be found"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response decode( - @ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName, - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, - @ApiParam(value = "JSON String to decode", required = true) String json) { - - PolicyController policyController; - try { - policyController = PolicyController.factory.get(controllerName); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + " not found")).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + " not acceptable")).build(); - } - - final CodingResult result = new CodingResult(); - result.setDecoding(false); - result.setEncoding(false); - result.setJsonEncoding(null); - - Object event; - try { - event = EventProtocolCoder.manager.decode(policyController.getDrools().getGroupId(), - policyController.getDrools().getArtifactId(), topic, json); - result.setDecoding(true); - } catch (final Exception e) { - logger.debug("{}: cannot get policy-controller {} topic {} because of {}", this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.BAD_REQUEST).entity(new Error(e.getMessage())).build(); - } - - try { - result.setJsonEncoding(EventProtocolCoder.manager.encode(topic, event)); - result.setEncoding(true); - } catch (final Exception e) { - // continue so to propagate decoding results .. - logger.debug("{}: cannot encode for policy-controller {} topic {} because of {}", this, - controllerName, topic, e.getMessage(), e); - } - - return Response.status(Response.Status.OK).entity(result).build(); - } - - @GET - @Path("engine/controllers/{controller}/encoders") - @ApiOperation(value = "Retrieves the encoder filters of a controller", - notes = "The encoders serializes a fact object, typically for network transmission", - responseContainer = "List", response = CoderFilters.class) - @ApiResponses(value = {@ApiResponse(code = 400, message = "Bad input has been provided"), - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response encoderFilters(@ApiParam(value = "Policy Controller Name", - required = true) @PathParam("controller") String controllerName) { - List<CoderFilters> encoders; - try { - final PolicyController controller = PolicyController.factory.get(controllerName); - final DroolsController drools = controller.getDrools(); - encoders = - EventProtocolCoder.manager.getEncoderFilters(drools.getGroupId(), drools.getArtifactId()); - } catch (final IllegalArgumentException e) { - logger.debug("{}: cannot get encoder filters for policy-controller {} because of {}", this, - controllerName, e.getMessage(), e); - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + " not found: " + e.getMessage())).build(); - } catch (final IllegalStateException e) { - logger.debug("{}: cannot get encoder filters for policy-controller {} because of {}", this, - controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " is not accepting the request")).build(); - } - - return Response.status(Response.Status.OK).entity(encoders).build(); - } - - @GET - @Path("engine/topics") - @ApiOperation(value = "Retrieves the managed topics", notes = "Network Topics Aggregation", - response = TopicEndpoint.class) - public Response topics() { - return Response.status(Response.Status.OK).entity(TopicEndpoint.manager).build(); - } - - @GET - @Path("engine/topics/switches") - @ApiOperation(value = "Topics Control Switches", notes = "List of the Topic Control Switches", - responseContainer = "List") - public Response topicSwitches() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); - } - - @PUT - @Path("engine/topics/switches/lock") - @ApiOperation(value = "Locks all the managed topics", - notes = "The operation affects all managed sources and sinks", response = TopicEndpoint.class) - @ApiResponses(value = { - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response topicsLock() { - final boolean success = TopicEndpoint.manager.lock(); - if (success) - return Response.status(Status.OK).entity(TopicEndpoint.manager).build(); - else - return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")) - .build(); - } - - @DELETE - @Path("engine/topics/switches/lock") - @ApiOperation(value = "Unlocks all the managed topics", - notes = "The operation affects all managed sources and sinks", response = TopicEndpoint.class) - @ApiResponses(value = { - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response topicsUnlock() { - final boolean success = TopicEndpoint.manager.unlock(); - if (success) - return Response.status(Status.OK).entity(TopicEndpoint.manager).build(); - else - return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")) - .build(); - } - - @GET - @Path("engine/topics/sources") - @ApiOperation(value = "Retrieves the managed topic sources", - notes = "Network Topic Sources Agregation", responseContainer = "List", - response = TopicSource.class) - public Response sources() { - return Response.status(Response.Status.OK).entity(TopicEndpoint.manager.getTopicSources()) - .build(); - } - - @GET - @Path("engine/topics/sinks") - @ApiOperation(value = "Retrieves the managed topic sinks", - notes = "Network Topic Sinks Agregation", responseContainer = "List", - response = TopicSink.class) - public Response sinks() { - return Response.status(Response.Status.OK).entity(TopicEndpoint.manager.getTopicSinks()) - .build(); - } - - @GET - @Path("engine/topics/sources/ueb") - @ApiOperation(value = "Retrieves the UEB managed topic sources", - notes = "UEB Topic Sources Agregation", responseContainer = "List", - response = UebTopicSource.class) - public Response uebSources() { - return Response.status(Response.Status.OK).entity(TopicEndpoint.manager.getUebTopicSources()) - .build(); - } - - @GET - @Path("engine/topics/sinks/ueb") - @ApiOperation(value = "Retrieves the UEB managed topic sinks", - notes = "UEB Topic Sinks Agregation", responseContainer = "List", - response = UebTopicSink.class) - public Response uebSinks() { - return Response.status(Response.Status.OK).entity(TopicEndpoint.manager.getUebTopicSinks()) - .build(); - } - - @GET - @Path("engine/topics/sources/dmaap") - @ApiOperation(value = "Retrieves the DMaaP managed topic sources", - notes = "DMaaP Topic Sources Agregation", responseContainer = "List", - response = DmaapTopicSource.class) - public Response dmaapSources() { - return Response.status(Response.Status.OK).entity(TopicEndpoint.manager.getDmaapTopicSources()) - .build(); - } - - @GET - @Path("engine/topics/sinks/dmaap") - @ApiOperation(value = "Retrieves the DMaaP managed topic sinks", - notes = "DMaaP Topic Sinks Agregation", responseContainer = "List", - response = DmaapTopicSink.class) - public Response dmaapSinks() { - return Response.status(Response.Status.OK).entity(TopicEndpoint.manager.getDmaapTopicSinks()) - .build(); - } - - @GET - @Path("engine/topics/sources/ueb/{topic}") - @ApiOperation(value = "Retrieves an UEB managed topic source", - notes = "This is an UEB Network Communicaton Endpoint source of messages for the Engine", - response = UebTopicSource.class) - public Response uebSourceTopic( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - return Response.status(Response.Status.OK) - .entity(TopicEndpoint.manager.getUebTopicSource(topic)).build(); - } - - @GET - @Path("engine/topics/sinks/ueb/{topic}") - @ApiOperation(value = "Retrieves an UEB managed topic sink", - notes = "This is an UEB Network Communicaton Endpoint destination of messages from the Engine", - response = UebTopicSink.class) - public Response uebSinkTopic( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - return Response.status(Response.Status.OK).entity(TopicEndpoint.manager.getUebTopicSink(topic)) - .build(); - } - - @GET - @Path("engine/topics/sources/dmaap/{topic}") - @ApiOperation(value = "Retrieves a DMaaP managed topic source", - notes = "This is a DMaaP Network Communicaton Endpoint source of messages for the Engine", - response = DmaapTopicSource.class) - public Response dmaapSourceTopic( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - return Response.status(Response.Status.OK) - .entity(TopicEndpoint.manager.getDmaapTopicSource(topic)).build(); - } - - @GET - @Path("engine/topics/sinks/dmaap/{topic}") - @ApiOperation(value = "Retrieves a DMaaP managed topic sink", - notes = "This is a DMaaP Network Communicaton Endpoint destination of messages from the Engine", - response = DmaapTopicSink.class) - public Response dmaapSinkTopic( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - return Response.status(Response.Status.OK) - .entity(TopicEndpoint.manager.getDmaapTopicSink(topic)).build(); - } - - @GET - @Path("engine/topics/sources/ueb/{topic}/events") - @ApiOperation(value = "Retrieves the latest events received by an UEB topic", - notes = "This is a UEB Network Communicaton Endpoint source of messages for the Engine", - responseContainer = "List") - public Response uebSourceEvents( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - return Response.status(Status.OK) - .entity(Arrays.asList(TopicEndpoint.manager.getUebTopicSource(topic).getRecentEvents())) - .build(); - } - - @GET - @Path("engine/topics/sinks/ueb/{topic}/events") - @ApiOperation(value = "Retrieves the latest events sent from a topic", - notes = "This is a UEB Network Communicaton Endpoint sink of messages from the Engine", - responseContainer = "List") - public Response uebSinkEvents( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - return Response.status(Status.OK) - .entity(Arrays.asList(TopicEndpoint.manager.getUebTopicSink(topic).getRecentEvents())) - .build(); - } - - @GET - @Path("engine/topics/sources/dmaap/{topic}/events") - @ApiOperation(value = "Retrieves the latest events received by a DMaaP topic", - notes = "This is a DMaaP Network Communicaton Endpoint source of messages for the Engine", - responseContainer = "List") - public Response dmaapSourceEvents( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - return Response.status(Status.OK) - .entity(Arrays.asList(TopicEndpoint.manager.getDmaapTopicSource(topic).getRecentEvents())) - .build(); - } - - @GET - @Path("engine/topics/sinks/dmaap/{topic}/events") - @ApiOperation(value = "Retrieves the latest events send through a DMaaP topic", - notes = "This is a DMaaP Network Communicaton Endpoint destination of messages from the Engine", - responseContainer = "List") - public Response dmaapSinkEvents(@PathParam("topic") String topic) { - return Response.status(Status.OK) - .entity(Arrays.asList(TopicEndpoint.manager.getDmaapTopicSink(topic).getRecentEvents())) - .build(); - } - - @GET - @Path("engine/topics/sinks/noop") - @ApiOperation(value = "Retrieves the NOOP managed topic sinks", - notes = "NOOP Topic Sinks Agregation", responseContainer = "List", - response = NoopTopicSink.class) - public Response noopSinks() { - return Response.status(Response.Status.OK).entity(TopicEndpoint.manager.getNoopTopicSinks()) - .build(); - } - - @GET - @Path("engine/topics/sinks/noop/{topic}") - @ApiOperation(value = "Retrieves a NOOP managed topic sink", - notes = "NOOP is an dev/null Network Communicaton Sink", response = NoopTopicSink.class) - public Response noopSinkTopic( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - return Response.status(Response.Status.OK).entity(TopicEndpoint.manager.getNoopTopicSink(topic)) - .build(); - } - - @GET - @Path("engine/topics/sinks/noop/{topic}/events") - @ApiOperation(value = "Retrieves the latest events send through a NOOP topic", - notes = "NOOP is an dev/null Network Communicaton Sink", responseContainer = "List") - public Response noopSinkEvents(@PathParam("topic") String topic) { - return Response.status(Status.OK) - .entity(Arrays.asList(TopicEndpoint.manager.getNoopTopicSink(topic).getRecentEvents())) - .build(); - } - - @GET - @Path("engine/topics/sources/ueb/{topic}/switches") - @ApiOperation(value = "UEB Topic Control Switches", - notes = "List of the UEB Topic Control Switches", responseContainer = "List") - public Response uebTopicSwitches() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); - } - - @PUT - @Path("engine/topics/sources/ueb/{topic}/switches/lock") - @ApiOperation(value = "Locks an UEB Source topic", response = UebTopicSource.class) - @ApiResponses(value = { - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response uebTopicLock( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - final UebTopicSource source = TopicEndpoint.manager.getUebTopicSource(topic); - final boolean success = source.lock(); - if (success) - return Response.status(Status.OK).entity(source).build(); - else - return Response.status(Status.NOT_ACCEPTABLE) - .entity(makeTopicOperError(topic)).build(); - } - - @DELETE - @Path("engine/topics/sources/ueb/{topic}/switches/lock") - @ApiOperation(value = "Unlocks an UEB Source topic", response = UebTopicSource.class) - @ApiResponses(value = { - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response uebTopicUnlock( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - final UebTopicSource source = TopicEndpoint.manager.getUebTopicSource(topic); - final boolean success = source.unlock(); - if (success) - return Response.status(Status.OK).entity(source).build(); - else - return Response.status(Status.NOT_ACCEPTABLE) - .entity(makeTopicOperError(topic)).build(); - } - - private Error makeTopicOperError(String topic) { - return new Error("cannot perform operation on " + topic); - } - - @GET - @Path("engine/topics/sources/dmaap/{topic}/switches") - @ApiOperation(value = "DMaaP Topic Control Switches", - notes = "List of the DMaaP Topic Control Switches", responseContainer = "List") - public Response dmaapTopicSwitches() { - return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); - } - - @PUT - @Path("engine/topics/sources/dmaap/{topic}/switches/lock") - @ApiOperation(value = "Locks an DMaaP Source topic", response = DmaapTopicSource.class) - @ApiResponses(value = { - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response dmmapTopicLock( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - final DmaapTopicSource source = TopicEndpoint.manager.getDmaapTopicSource(topic); - final boolean success = source.lock(); - if (success) - return Response.status(Status.OK).entity(source).build(); - else - return Response.status(Status.NOT_ACCEPTABLE) - .entity(makeTopicOperError(topic)).build(); - } - - @DELETE - @Path("engine/topics/sources/dmaap/{topic}/switches/lock") - @ApiOperation(value = "Unlocks an DMaaP Source topic", response = DmaapTopicSource.class) - @ApiResponses(value = { - @ApiResponse(code = 406, message = "The system is an administrative state that prevents " - + "this request to be fulfilled")}) - public Response dmaapTopicUnlock( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { - final DmaapTopicSource source = TopicEndpoint.manager.getDmaapTopicSource(topic); - final boolean success = source.unlock(); - if (success) - return Response.status(Status.OK).entity(source).build(); - else - return Response.status(Status.SERVICE_UNAVAILABLE) - .entity(makeTopicOperError(topic)).build(); - } - - @PUT - @Path("engine/topics/sources/ueb/{topic}/events") - @Consumes(MediaType.TEXT_PLAIN) - @ApiOperation(value = "Offers an event to an UEB topic for internal processing by the engine", - notes = "The offered event is treated as it was incoming from the network", - responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = 404, message = "The topic information cannot be found"), - @ApiResponse(code = 406, - message = "The system is an administrative state that prevents " - + "this request to be fulfilled"), - @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) - public Response uebOffer( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, - @ApiParam(value = "Network Message", required = true) String json) { - try { - final UebTopicSource uebReader = TopicEndpoint.manager.getUebTopicSource(topic); - final boolean success = uebReader.offer(json); - if (success) - return Response.status(Status.OK) - .entity(Arrays.asList(TopicEndpoint.manager.getUebTopicSource(topic).getRecentEvents())) - .build(); - else - return Response.status(Status.NOT_ACCEPTABLE) - .entity(new Error("Failure to inject event over " + topic)).build(); - } catch (final IllegalArgumentException e) { - logNoUebEncoder(topic, e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(topic + " not found")) - .build(); - } catch (final IllegalStateException e) { - logNoUebEncoder(topic, e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(topic + " not acceptable due to current state")).build(); - } catch (final Exception e) { - logNoUebEncoder(topic, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Error(e.getMessage())).build(); - } - } - - private void logNoUebEncoder(String topic, Exception ex) { - logger.debug("{}: cannot offer for encoder ueb topic for {} because of {}", this, topic, - ex.getMessage(), ex); - } - - @PUT - @Path("engine/topics/sources/dmaap/{topic}/events") - @Consumes(MediaType.TEXT_PLAIN) - @ApiOperation(value = "Offers an event to a DMaaP topic for internal processing by the engine", - notes = "The offered event is treated as it was incoming from the network", - responseContainer = "List") - @ApiResponses(value = { - @ApiResponse(code = 404, message = "The topic information cannot be found"), - @ApiResponse(code = 406, - message = "The system is an administrative state that prevents " - + "this request to be fulfilled"), - @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) - public Response dmaapOffer( - @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, - @ApiParam(value = "Network Message", required = true) String json) { - try { - final DmaapTopicSource dmaapReader = TopicEndpoint.manager.getDmaapTopicSource(topic); - final boolean success = dmaapReader.offer(json); - if (success) - return Response.status(Status.OK) - .entity( - Arrays.asList(TopicEndpoint.manager.getDmaapTopicSource(topic).getRecentEvents())) - .build(); - else - return Response.status(Status.NOT_ACCEPTABLE) - .entity(new Error("Failure to inject event over " + topic)).build(); - } catch (final IllegalArgumentException e) { - logNoDmaapEncoder(topic, e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(topic + " not found")) - .build(); - } catch (final IllegalStateException e) { - logNoDmaapEncoder(topic, e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(topic + " not acceptable due to current state")).build(); - } catch (final Exception e) { - logNoDmaapEncoder(topic, e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(new Error(e.getMessage())).build(); - } - } - - private void logNoDmaapEncoder(String topic, Exception ex) { - logger.debug("{}: cannot offer for encoder dmaap topic for {} because of {}", this, topic, - ex.getMessage(), ex); - } - - @GET - @Path("engine/tools/uuid") - @ApiOperation(value = "Produces an UUID", notes = "UUID generation utility") - @Produces(MediaType.TEXT_PLAIN) - public Response uuid() { - return Response.status(Status.OK).entity(UUID.randomUUID().toString()).build(); - } - - @GET - @Path("engine/tools/loggers") - @ApiOperation(value = "all active loggers", responseContainer = "List") - @ApiResponses(value = {@ApiResponse(code = 500, message = "logging misconfiguration")}) - public Response loggers() { - final List<String> names = new ArrayList<>(); - if (!(LoggerFactory.getILoggerFactory() instanceof LoggerContext)) { - logger.warn("The SLF4J logger factory is not configured for logback"); - return Response.status(Status.INTERNAL_SERVER_ERROR).entity(names).build(); - } - - final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - for (final Logger lgr : context.getLoggerList()) { - names.add(lgr.getName()); - } - - return Response.status(Status.OK).entity(names).build(); - } - - @GET - @Path("engine/tools/loggers/{logger}") - @Produces(MediaType.TEXT_PLAIN) - @ApiOperation(value = "logging level of a logger") - @ApiResponses(value = {@ApiResponse(code = 500, message = "logging misconfiguration"), - @ApiResponse(code = 404, message = "logger not found")}) - public Response loggerName( - @ApiParam(value = "Logger Name", required = true) @PathParam("logger") String loggerName) { - if (!(LoggerFactory.getILoggerFactory() instanceof LoggerContext)) { - logger.warn("The SLF4J logger factory is not configured for logback"); - return Response.status(Status.INTERNAL_SERVER_ERROR).build(); - } - - final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - final ch.qos.logback.classic.Logger lgr = context.getLogger(loggerName); - if (lgr == null) { - return Response.status(Status.NOT_FOUND).build(); - } - - final String loggerLevel = (lgr.getLevel() != null) ? lgr.getLevel().toString() : ""; - return Response.status(Status.OK).entity(loggerLevel).build(); - } - - @PUT - @Path("engine/tools/loggers/{logger}/{level}") - @Produces(MediaType.TEXT_PLAIN) - @Consumes(MediaType.TEXT_PLAIN) - @ApiOperation(value = "sets the logger level", notes = "Please use the SLF4J logger levels") - @ApiResponses(value = {@ApiResponse(code = 500, message = "logging misconfiguration"), - @ApiResponse(code = 404, message = "logger not found")}) - public Response loggerName( - @ApiParam(value = "Logger Name", required = true) @PathParam("logger") String loggerName, - @ApiParam(value = "Logger Level", required = true) @PathParam("level") String loggerLevel) { - - String newLevel; - try { - newLevel = LoggerUtil.setLevel(loggerName, loggerLevel); - } catch (final IllegalArgumentException e) { - logger.warn("{}: no logger {}", this, loggerName, loggerLevel, e); - return Response.status(Status.NOT_FOUND).build(); - } catch (final IllegalStateException e) { - logger.warn("{}: logging framework unavailable for {} / {}", this, loggerName, loggerLevel, - e); - return Response.status(Status.INTERNAL_SERVER_ERROR).build(); - } - - return Response.status(Status.OK).entity(newLevel - - ).build(); - } - - /** - * gets the underlying drools controller from the named policy controller - * - * @param controllerName the policy controller name - * @return the underlying drools controller - * @throws IllegalArgumentException if an invalid controller name has been passed in - */ - protected DroolsController getDroolsController(String controllerName) { - final PolicyController controller = PolicyController.factory.get(controllerName); - if (controller == null) - throw new IllegalArgumentException(controllerName + " does not exist"); - - final DroolsController drools = controller.getDrools(); - if (drools == null) - throw new IllegalArgumentException(controllerName + " has no drools configuration"); - - return drools; - } - - /* - * Helper classes for aggregation of results - */ - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("rest-telemetry-api []"); - return builder.toString(); - } - - /** - * Coding/Encoding Results Aggregation Helper class - */ - public static class CodingResult { /** - * serialized output + * Logger */ + private static Logger logger = LoggerFactory.getLogger(RestManager.class); + + @GET + @Path("engine") + @ApiOperation(value = "Retrieves the Engine Operational Status", + notes = "Top-level abstraction. Provides a global view of resources", response = PolicyEngine.class) + public Response engine() { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); + } - private String jsonEncoding; - /** - * encoding result - */ + @DELETE + @Path("engine") + @ApiOperation(value = "Shuts down the Engine", + notes = "Deleting the engine, the top-level abstraction, equivalenty shuts it down", + response = PolicyEngine.class) + public Response engineShutdown() { + try { + PolicyEngine.manager.shutdown(); + } catch (final IllegalStateException e) { + logger.error("{}: cannot shutdown {} because of {}", this, PolicyEngine.manager, e.getMessage(), e); + return Response.status(Response.Status.BAD_REQUEST).entity(PolicyEngine.manager).build(); + } + + return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); + } - private Boolean encoding; + @GET + @Path("engine/features") + @ApiOperation(value = "Engine Features", + notes = "Provides the list of loaded features using the PolicyEngineFeatureAPI", responseContainer = "List") + public Response engineFeatures() { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatures()).build(); + } - /** - * decoding result - */ - private Boolean decoding; + @GET + @Path("engine/features/inventory") + @ApiOperation(value = "Engine Detailed Feature Inventory", + notes = "Provides detailed list of loaded features using the PolicyEngineFeatureAPI", + responseContainer = "List", response = PolicyEngineFeatureAPI.class) + public Response engineFeaturesInventory() { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatureProviders()).build(); + } + + @GET + @Path("engine/features/{featureName}") + @ApiOperation(value = "Engine Feature", notes = "Provides Details for a given feature Engine Provider", + response = PolicyEngineFeatureAPI.class) + @ApiResponses(value = {@ApiResponse(code = 404, message = "The feature cannot be found")}) + public Response engineFeature( + @ApiParam(value = "Feature Name", required = true) @PathParam("featureName") String featureName) { + try { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatureProvider(featureName)) + .build(); + } catch (final IllegalArgumentException iae) { + logger.debug("feature unavailable: {}", featureName, iae); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(iae.getMessage())).build(); + } + } + + @GET + @Path("engine/inputs") + @ApiOperation(value = "Engine Input Ports", notes = "List of input ports", responseContainer = "List") + public Response engineInputs() { + return Response.status(Response.Status.OK).entity(Arrays.asList(Inputs.values())).build(); + } + + @POST + @Path("engine/inputs/configuration") + @ApiOperation(value = "Engine Input Configuration Requests", + notes = "Feeds a configuration request input into the Engine") + @ApiResponses(value = {@ApiResponse(code = 406, message = "The configuration request cannot be honored")}) + public Response engineUpdate( + @ApiParam(value = "Configuration to apply", required = true) PdpdConfiguration configuration) { + final PolicyController controller = null; + boolean success = true; + try { + success = PolicyEngine.manager.configure(configuration); + } catch (final Exception e) { + success = false; + logger.info("{}: cannot configure {} because of {}", this, PolicyEngine.manager, e.getMessage(), e); + } + + if (!success) { + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")) + .build(); + } else { + return Response.status(Response.Status.OK).entity(controller).build(); + } + } + + @GET + @Path("engine/properties") + @ApiOperation(value = "Engine Configuration Properties", notes = "Used for booststrapping the engine", + response = Properties.class) + public Response engineProperties() { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getProperties()).build(); + } + + @GET + @Path("engine/environment") + @ApiOperation(value = "Engine Environment Properties", + notes = "Installation and OS environment properties used by the engine", response = Properties.class) + public Response engineEnvironment() { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getEnvironment()).build(); + } + + @GET + @Path("engine/environment/{envProperty}") + @Consumes(MediaType.TEXT_PLAIN) + @ApiOperation(value = "Gets an environment variable", response = String.class) + public Response engineEnvironment( + @ApiParam(value = "Environment Property", required = true) @PathParam("envProperty") String envProperty) { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getEnvironmentProperty(envProperty)) + .build(); + } + + @PUT + @Path("engine/environment/{envProperty}") + @Consumes(MediaType.TEXT_PLAIN) + @Produces(MediaType.TEXT_PLAIN) + @ApiOperation(value = "Adds a new environment value to the engine", response = String.class) + public Response engineEnvironmentAdd( + @ApiParam(value = "Environment Property", required = true) @PathParam("envProperty") String envProperty, + @ApiParam(value = "Environment Value", required = true) String envValue) { + final String previousValue = PolicyEngine.manager.setEnvironmentProperty(envProperty, envValue); + return Response.status(Response.Status.OK).entity(previousValue).build(); + } + + @GET + @Path("engine/switches") + @ApiOperation(value = "Engine Control Switches", notes = "List of the Engine Control Switches", + responseContainer = "List") + public Response engineSwitches() { + return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); + } + + @PUT + @Path("engine/switches/activation") + @ApiOperation(value = "Switches on the Engine Activation Switch", + notes = "Turns on Activation Switch on the Engine. This order entails that the engine " + + "and controllers are unlocked and started", + response = PolicyEngine.class) + public Response engineActivation() { + boolean success = true; + try { + PolicyEngine.manager.activate(); + } catch (final Exception e) { + success = false; + logger.info("{}: cannot activate {} because of {}", this, PolicyEngine.manager, e.getMessage(), e); + } + + if (!success) { + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")) + .build(); + } else { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); + } + } + + @DELETE + @Path("engine/switches/activation") + @ApiOperation(value = "Switches off Engine Activation Switch", + notes = "Turns off the Activation Switch on the Engine. This order entails that the engine " + + "and controllers are locked (with the exception of those resources defined as unmanaged)", + response = PolicyEngine.class) + public Response engineDeactivation() { + boolean success = true; + try { + PolicyEngine.manager.deactivate(); + } catch (final Exception e) { + success = false; + logger.info("{}: cannot deactivate {} because of {}", this, PolicyEngine.manager, e.getMessage(), e); + } + + if (!success) { + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")) + .build(); + } else { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager).build(); + } + } + + @PUT + @Path("engine/switches/lock") + @ApiOperation(value = "Switches on the Engine Lock Control", + notes = "This switch locks all the engine resources as a whole, except those that are defined unmanaged", + response = PolicyEngine.class) + @ApiResponses(value = {@ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response engineLock() { + final boolean success = PolicyEngine.manager.lock(); + if (success) { + return Response.status(Status.OK).entity(PolicyEngine.manager).build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")).build(); + } + } + + @DELETE + @Path("engine/switches/lock") + @ApiOperation(value = "Switches off the Lock control", + notes = "This switch locks all the engine resources as a whole, except those that are defined unmanaged", + response = PolicyEngine.class) + @ApiResponses(value = {@ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response engineUnlock() { + final boolean success = PolicyEngine.manager.unlock(); + if (success) { + return Response.status(Status.OK).entity(PolicyEngine.manager).build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")).build(); + } + } + + @GET + @Path("engine/controllers") + @ApiOperation(value = "Lists the Policy Controllers Names", notes = "Unique Policy Controller Identifiers", + responseContainer = "List") + public Response controllers() { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getPolicyControllerIds()).build(); + } + + @GET + @Path("engine/controllers/inventory") + @ApiOperation(value = "Lists the Policy Controllers", notes = "Detailed list of Policy Controllers", + responseContainer = "List", response = PolicyController.class) + public Response controllerInventory() { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getPolicyControllers()).build(); + } + + @POST + @Path("engine/controllers") + @ApiOperation(value = "Creates and starts a new Policy Controller", + notes = "Controller creation based on properties", response = PolicyController.class) + @ApiResponses(value = {@ApiResponse(code = 400, message = "Invalid configuration information has been provided"), + @ApiResponse(code = 304, message = "The controller already exists"), + @ApiResponse(code = 406, + message = "The administrative state of the system prevents it " + "from processing this request"), + @ApiResponse(code = 206, message = "The controller has been created " + "but cannot be started"), + @ApiResponse(code = 201, message = "The controller has been succesfully created and started")}) + public Response controllerAdd( + @ApiParam(value = "Configuration Properties to apply", required = true) Properties config) { + if (config == null) { + return Response.status(Response.Status.BAD_REQUEST).entity(new Error("A configuration must be provided")) + .build(); + } + + final String controllerName = config.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME); + if (controllerName == null || controllerName.isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error( + "Configuration must have an entry for " + DroolsProperties.PROPERTY_CONTROLLER_NAME)) + .build(); + } + + PolicyController controller; + try { + controller = PolicyController.factory.get(controllerName); + if (controller != null) { + return Response.status(Response.Status.NOT_MODIFIED).entity(controller).build(); + } + } catch (final IllegalArgumentException e) { + logger.trace("OK ", e); + // This is OK + } catch (final IllegalStateException e) { + logger.info("{}: cannot get policy-controller because of {}", this, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not found")) + .build(); + } + + try { + controller = PolicyEngine.manager + .createPolicyController(config.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME), config); + } catch (IllegalArgumentException | IllegalStateException e) { + logger.warn("{}: cannot create policy-controller because of {}", this, e.getMessage(), e); + return Response.status(Response.Status.BAD_REQUEST).entity(new Error(e.getMessage())).build(); + } + + try { + final boolean success = controller.start(); + if (!success) { + logger.info("{}: cannot start {}", this, controller); + return Response.status(Response.Status.PARTIAL_CONTENT) + .entity(new Error(controllerName + " can't be started")).build(); + } + } catch (final IllegalStateException e) { + logger.info("{}: cannot start {} because of {}", this, controller, e.getMessage(), e);; + return Response.status(Response.Status.PARTIAL_CONTENT).entity(controller).build(); + } + + return Response.status(Response.Status.CREATED).entity(controller).build(); + } + + @GET + @Path("engine/controllers/features") + @ApiOperation(value = "Lists of Feature Providers Identifiers", notes = "Unique Policy Controller Identifiers", + responseContainer = "List") + public Response controllerFeatures() { + return Response.status(Response.Status.OK).entity(PolicyEngine.manager.getFeatures()).build(); + } + + @GET + @Path("engine/controllers/features/inventory") + @ApiOperation(value = "Detailed Controllers Feature Inventory", + notes = "Provides detailed list of loaded features using the PolicyControllerFeatureAPI", + responseContainer = "List", response = PolicyControllerFeatureAPI.class) + public Response controllerFeaturesInventory() { + return Response.status(Response.Status.OK).entity(PolicyController.factory.getFeatureProviders()).build(); + } + + @GET + @Path("engine/controllers/features/{featureName}") + @ApiOperation(value = "Controller Feature", + notes = "Provides Details for a given Policy Controller feature provider", + response = PolicyControllerFeatureAPI.class) + @ApiResponses(value = {@ApiResponse(code = 404, message = "The feature cannot be found")}) + public Response controllerFeature( + @ApiParam(value = "Feature Name", required = true) @PathParam("featureName") String featureName) { + try { + return Response.status(Response.Status.OK).entity(PolicyController.factory.getFeatureProvider(featureName)) + .build(); + } catch (final IllegalArgumentException iae) { + logger.debug("{}: cannot feature {} because of {}", this, featureName, iae.getMessage(), iae); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(iae.getMessage())).build(); + } + } + + @GET + @Path("engine/controllers/{controller}") + @ApiOperation(value = "Retrieves a Policy Controller", + notes = "A Policy Controller is a concrete drools application abstraction. " + + "It aggregates networking, drools, and other resources," + + "as provides operational controls over drools applications", + response = PolicyController.class) + @ApiResponses( + value = {@ApiResponse(code = 404, message = "The controller cannot be found"), @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response controller(@ApiParam(value = "Policy Controller Name", + required = true) @PathParam("controller") String controllerName) { + try { + return Response.status(Response.Status.OK).entity(PolicyController.factory.get(controllerName)).build(); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) + .build(); + } + } + + @DELETE + @Path("engine/controllers/{controller}") + @ApiOperation(value = "Deletes a Policy Controller", + notes = "A Policy Controller is a concrete drools application abstraction. " + + "It aggregates networking, drools, and other resources," + + "as provides operational controls over drools applications", + response = PolicyController.class) + @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled"), + @ApiResponse(code = 500, message = "A problem has occurred while deleting the Policy Controller")}) + public Response controllerDelete(@ApiParam(value = "Policy Controller Name", + required = true) @PathParam("controller") String controllerName) { + + PolicyController controller; + try { + controller = PolicyController.factory.get(controllerName); + if (controller == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + " does not exist")).build(); + } + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + " not found: " + e.getMessage())).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) + .build(); + } + + try { + PolicyEngine.manager.removePolicyController(controllerName); + } catch (IllegalArgumentException | IllegalStateException e) { + logger.debug("{}: cannot remove policy-controller {} because of {}", this, controllerName, e.getMessage(), + e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); + } + + return Response.status(Response.Status.OK).entity(controller).build(); + } + + @GET + @Path("engine/controllers/{controller}/properties") + @ApiOperation(value = "Retrieves the configuration properties of a Policy Controller", + notes = "Configuration resources used by the controller if Properties format", + response = PolicyController.class) + @ApiResponses( + value = {@ApiResponse(code = 404, message = "The controller cannot be found"), @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response controllerProperties(@ApiParam(value = "Policy Controller Name", + required = true) @PathParam("controller") String controllerName) { + try { + final PolicyController controller = PolicyController.factory.get(controllerName); + return Response.status(Response.Status.OK).entity(controller.getProperties()).build(); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) + .build(); + } + } + + @GET + @Path("engine/controllers/{controller}/inputs") + @ApiOperation(value = "Policy Controller Input Ports", notes = "List of input ports", responseContainer = "List") + public Response controllerInputs() { + return Response.status(Response.Status.OK).entity(Arrays.asList(Inputs.values())).build(); + } + + @POST + @Path("engine/controllers/{controller}/inputs/configuration") + @ApiOperation(value = "Policy Controller Input Configuration Requests", + notes = "Feeds a configuration request input into the given Policy Controller") + @ApiResponses(value = {@ApiResponse(code = 400, message = "The configuration request is invalid"), + @ApiResponse(code = 406, message = "The configuration request cannot be honored")}) + public Response controllerUpdate( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Configuration to apply", + required = true) ControllerConfiguration controllerConfiguration) { + + if (controllerName == null || controllerName.isEmpty() || controllerConfiguration == null + || controllerConfiguration.getName().intern() != controllerName) { + return Response.status(Response.Status.BAD_REQUEST) + .entity("A valid or matching controller names must be provided").build(); + } + + PolicyController controller; + try { + controller = PolicyEngine.manager.updatePolicyController(controllerConfiguration); + if (controller == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + " does not exist")).build(); + } + } catch (final IllegalArgumentException e) { + logger.info("{}: cannot update policy-controller {} because of {}", this, controllerName, e.getMessage(), + e); + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + " not found: " + e.getMessage())).build(); + } catch (final Exception e) { + logger.info("{}: cannot update policy-controller {} because of {}", this, controllerName, e.getMessage(), + e); + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) + .build(); + } + + return Response.status(Response.Status.OK).entity(controller).build(); + } + + @GET + @Path("engine/controllers/{controller}/switches") + @ApiOperation(value = "Policy Controller Switches", notes = "List of the Policy Controller Switches", + responseContainer = "List") + public Response controllerSwitches() { + return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); + } + + @PUT + @Path("engine/controllers/{controller}/switches/lock") + @ApiOperation(value = "Switches on the Policy Controller Lock Control", + notes = "This action on the switch locks the Policy Controller", response = PolicyController.class) + @ApiResponses(value = {@ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response controllerLock(@ApiParam(value = "Policy Controller Name", + required = true) @PathParam("controller") String controllerName) { + final PolicyController policyController = PolicyController.factory.get(controllerName); + final boolean success = policyController.lock(); + if (success) { + return Response.status(Status.OK).entity(policyController).build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE) + .entity(new Error("Controller " + controllerName + " cannot be locked")).build(); + } + } + + @DELETE + @Path("engine/controllers/{controller}/switches/lock") + @ApiOperation(value = "Switches off the Policy Controller Lock Control", + notes = "This action on the switch unlocks the Policy Controller", response = PolicyController.class) + @ApiResponses(value = {@ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response controllerUnlock(@ApiParam(value = "Policy Controller Name", + required = true) @PathParam("controller") String controllerName) { + final PolicyController policyController = PolicyController.factory.get(controllerName); + final boolean success = policyController.unlock(); + if (success) { + return Response.status(Status.OK).entity(policyController).build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE) + .entity(new Error("Controller " + controllerName + " cannot be unlocked")).build(); + } + } + + @GET + @Path("engine/controllers/{controller}/drools") + @ApiOperation(value = "Retrieves the Drools Controller subcomponent of the Policy Controller", + notes = "The Drools Controller provides an abstraction over the Drools subsystem", + response = DroolsController.class) + @ApiResponses( + value = {@ApiResponse(code = 404, message = "The controller cannot be found"), @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response drools(@ApiParam(value = "Policy Controller Name", + required = true) @PathParam("controller") String controllerName) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + return Response.status(Response.Status.OK).entity(drools).build(); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) + .build(); + } + } + + @GET + @Path("engine/controllers/{controller}/drools/facts") + @ApiOperation(value = "Retrieves Facts Summary information for a given controller", + notes = "Provides the session names, and a count of fact object in the drools working memory", + responseContainer = "Map") + @ApiResponses( + value = {@ApiResponse(code = 404, message = "The controller cannot be found"), @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response droolsFacts(@ApiParam(value = "Policy Controller Name", + required = true) @PathParam("controller") String controllerName) { + try { + final Map<String, Long> sessionCounts = new HashMap<>(); + final DroolsController drools = this.getDroolsController(controllerName); + for (final String session : drools.getSessionNames()) { + sessionCounts.put(session, drools.factCount(session)); + } + return Response.status(Response.Status.OK).entity(sessionCounts).build(); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) + .build(); + } + } + + @GET + @Path("engine/controllers/{controller}/drools/facts/{session}") + @ApiOperation(value = "Retrieves Fact Types (classnames) for a given controller and its count", + notes = "The fact types are the classnames of the objects inserted in the drools working memory", + responseContainer = "Map") + @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller or session cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response droolsFacts( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + return Response.status(Response.Status.OK).entity(drools.factClassNames(sessionName)).build(); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error("entity not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get drools-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + ":" + sessionName + " not acceptable")).build(); + } + } + + @GET + @Path("engine/controllers/{controller}/drools/facts/{session}/{factType}") + @ApiOperation( + value = "Retrieves fact objects of a given type in the drools working memory" + + "for a given controller and session", + notes = "The fact types are the classnames of the objects inserted in the drools working memory", + responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller, session, or fact type cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response droolsFacts( + @ApiParam(value = "Fact count", required = false) @DefaultValue("false") @QueryParam("count") boolean count, + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName, + @ApiParam(value = "Drools Fact Type", required = true) @PathParam("factType") String factType) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + final List<Object> facts = drools.facts(sessionName, factType, false); + if (!count) { + return Response.status(Response.Status.OK).entity(facts).build(); + } else { + return Response.status(Response.Status.OK).entity(facts.size()).build(); + } + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + sessionName + ":" + factType + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get policy-controller {} because of {}", this, controllerName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + ":" + sessionName + ":" + factType + " not acceptable")).build(); + } + } + + @DELETE + @Path("engine/controllers/{controller}/drools/facts/{session}/{factType}") + @ApiOperation( + value = "Deletes all the fact objects of a given type from the drools working memory" + + "for a given controller and session. The objects retracted from the working " + + "memory are provided in the response.", + notes = "The fact types are the classnames of the objects inserted in the drools working memory", + responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller, session, or fact type, cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled"), + @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) + public Response droolsFactsDelete( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName, + @ApiParam(value = "Drools Fact Type", required = true) @PathParam("factType") String factType) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + final List<Object> facts = drools.facts(sessionName, factType, true); + return Response.status(Response.Status.OK).entity(facts).build(); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get: drools-controller {}, session {}, factType {}, because of {}", this, + controllerName, sessionName, factType, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + sessionName + ":" + factType + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get: drools-controller {}, session {}, factType {}, because of {}", this, + controllerName, sessionName, factType, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + ":" + sessionName + ":" + factType + " not acceptable")).build(); + } catch (final Exception e) { + logger.debug("{}: cannot get: drools-controller {}, session {}, factType {}, because of {}", this, + controllerName, sessionName, factType, e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); + } + } + + @GET + @Path("engine/controllers/{controller}/drools/facts/{session}/{query}/{queriedEntity}") + @ApiOperation( + value = "Gets all the fact objects returned by a DRL query with no parameters from the drools working memory" + + "for a given controller and session", + notes = "The DRL query must be defined in the DRL file", responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 404, message = "The controller, session, or query information, cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled"), + @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) + public Response droolsFacts( + @ApiParam(value = "Fact count", required = false) @DefaultValue("false") @QueryParam("count") boolean count, + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName, + @ApiParam(value = "Query Name Present in DRL", required = true) @PathParam("query") String queryName, + @ApiParam(value = "Query Identifier Present in the DRL Query", + required = true) @PathParam("queriedEntity") String queriedEntity) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + final List<Object> facts = drools.factQuery(sessionName, queryName, queriedEntity, false); + if (!count) { + return Response.status(Response.Status.OK).entity(facts).build(); + } else { + return Response.status(Response.Status.OK).entity(facts.size()).build(); + } + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}", this, + controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error( + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not found")) + .build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}", this, + controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error( + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not acceptable")) + .build(); + } catch (final Exception e) { + logger.debug("{}: cannot get: drools-controller {}, session {}, query {}, entity {} because of {}", this, + controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); + } + } + + @POST + @Path("engine/controllers/{controller}/drools/facts/{session}/{query}/{queriedEntity}") + @ApiOperation( + value = "Gets all the fact objects returned by a DRL query with parameters from the drools working memory" + + "for a given controller and session", + notes = "The DRL query with parameters must be defined in the DRL file", responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 404, message = "The controller, session, or query information, cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled"), + @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) + public Response droolsFacts( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName, + @ApiParam(value = "Query Name Present in DRL", required = true) @PathParam("query") String queryName, + @ApiParam(value = "Query Identifier Present in the DRL Query", + required = true) @PathParam("queriedEntity") String queriedEntity, + @ApiParam(value = "Query Parameter Values to pass in the DRL Query", + required = false) List<Object> queryParameters) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + List<Object> facts; + if (queryParameters == null || queryParameters.isEmpty()) { + facts = drools.factQuery(sessionName, queryName, queriedEntity, false); + } else { + facts = drools.factQuery(sessionName, queryName, queriedEntity, false, queryParameters.toArray()); + } + return Response.status(Response.Status.OK).entity(facts).build(); + } catch (final IllegalArgumentException e) { + logger.debug( + "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error( + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not found")) + .build(); + } catch (final IllegalStateException e) { + logger.debug( + "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error( + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not acceptable")) + .build(); + } catch (final Exception e) { + logger.debug( + "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); + } + } + + @DELETE + @Path("engine/controllers/{controller}/drools/facts/{session}/{query}/{queriedEntity}") + @ApiOperation( + value = "Deletes all the fact objects returned by a DRL query with parameters from the drools working memory" + + "for a given controller and session", + notes = "The DRL query with parameters must be defined in the DRL file", responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 404, message = "The controller, session, or query information, cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled"), + @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) + public Response droolsFactsDelete( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Drools Session Name", required = true) @PathParam("session") String sessionName, + @ApiParam(value = "Query Name Present in DRL", required = true) @PathParam("query") String queryName, + @ApiParam(value = "Query Identifier Present in the DRL Query", + required = true) @PathParam("queriedEntity") String queriedEntity, + @ApiParam(value = "Query Parameter Values to pass in the DRL Query", + required = false) List<Object> queryParameters) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + List<Object> facts; + if (queryParameters == null || queryParameters.isEmpty()) { + facts = drools.factQuery(sessionName, queryName, queriedEntity, true); + } else { + facts = drools.factQuery(sessionName, queryName, queriedEntity, true, queryParameters.toArray()); + } + return Response.status(Response.Status.OK).entity(facts).build(); + } catch (final IllegalArgumentException e) { + logger.debug( + "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error( + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not found")) + .build(); + } catch (final IllegalStateException e) { + logger.debug( + "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error( + controllerName + ":" + sessionName + ":" + queryName + queriedEntity + " not acceptable")) + .build(); + } catch (final Exception e) { + logger.debug( + "{}: cannot get: drools-controller {}, session {}, query {}, entity {}, params {} because of {}", + this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); + } + } + + @POST + @Path("engine/controllers/tools/coders/decoders/filters/rules/{ruleName}") + @ApiOperation(value = "Produces a Decoder Rule Filter in a format that the Policy Controller can understand", + notes = "The result can be used with other APIs to attach a filter to a decoder") + public Response rules( + @ApiParam(value = "Negate regex?", + required = true) @DefaultValue("false") @QueryParam("negate") boolean negate, + @ApiParam(value = "Rule Name", required = true) @PathParam("ruleName") String name, + @ApiParam(value = "Regex expression", required = true) String regex) { + String literalRegex = Pattern.quote(regex); + if (negate) { + literalRegex = "^(?!" + literalRegex + "$).*"; + } + + return Response.status(Status.OK).entity(new JsonProtocolFilter.FilterRule(name, literalRegex)).build(); + } + + @GET + @Path("engine/controllers/{controller}/decoders") + @ApiOperation(value = "Gets all the decoders used by a controller", + notes = "A Policy Controller uses decoders to deserialize incoming network messages from " + + "subscribed network topics into specific (fact) objects. " + + "The deserialized (fact) object will typically be inserted in the drools working " + + " memory of the controlled drools application.", + responseContainer = "List", response = ProtocolCoderToolset.class) + @ApiResponses( + value = {@ApiResponse(code = 404, message = "The controller cannot be found"), @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decoders(@ApiParam(value = "Policy Controller Name", + required = true) @PathParam("controller") String controllerName) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + final List<ProtocolCoderToolset> decoders = + EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId()); + return Response.status(Response.Status.OK).entity(decoders).build(); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, controllerName, + e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, controllerName, + e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) + .build(); + } + } + + @GET + @Path("engine/controllers/{controller}/decoders/filters") + @ApiOperation(value = "Gets all the filters used by a controller", + notes = "A Policy Controller uses decoders to deserialize incoming network messages from " + + "subscribed network topics into specific (fact) objects. " + + "The deserialized (fact) object will typically be inserted in the drools working " + + " memory of the controlled drools application." + + "Acceptance filters are used to filter out undesired network messages for the given controller", + responseContainer = "List", response = CoderFilters.class) + @ApiResponses( + value = {@ApiResponse(code = 404, message = "The controller cannot be found"), @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decoderFilters(@ApiParam(value = "Policy Controller Name", + required = true) @PathParam("controller") String controllerName) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + final List<CoderFilters> filters = + EventProtocolCoder.manager.getDecoderFilters(drools.getGroupId(), drools.getArtifactId()); + return Response.status(Response.Status.OK).entity(filters).build(); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, controllerName, + e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get decoders for policy-controller {} because of {}", this, controllerName, + e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(new Error(controllerName + " not acceptable")) + .build(); + } + } + + @GET + @Path("engine/controllers/{controller}/decoders/{topic}") + @ApiOperation(value = "Gets all the decoders in use by a controller for a networked topic", + notes = "A Policy Controller uses decoders to deserialize incoming network messages from " + + "subscribed network topics into specific (fact) objects. " + + "The deserialized (fact) object will typically be inserted in the drools working " + + " memory of the controlled drools application.", + responseContainer = "List", response = ProtocolCoderToolset.class) + @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller or topic cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decoder( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Networked Topic Name", required = true) @PathParam("topic") String topic) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + final ProtocolCoderToolset decoder = + EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + return Response.status(Response.Status.OK).entity(decoder).build(); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + controllerName, topic, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + topic + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + controllerName, topic, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + ":" + topic + " not acceptable")).build(); + } + } + + @GET + @Path("engine/controllers/{controller}/decoders/{topic}/filters") + @ApiOperation(value = "Gets all filters attached to decoders for a given networked topic in use by a controller", + notes = "A Policy Controller uses decoders to deserialize incoming network messages from " + + "subscribed network topics into specific (fact) objects. " + + "The deserialized (fact) object will typically be inserted in the drools working " + + " memory of the controlled drools application." + + "Acceptance filters are used to filter out undesired network messages for the given controller", + responseContainer = "List", response = CoderFilters.class) + @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller or topic cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decoderFilter( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Networked Topic Name", required = true) @PathParam("topic") String topic) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + final ProtocolCoderToolset decoder = + EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + if (decoder == null) { + return Response.status(Response.Status.BAD_REQUEST).entity(new Error(topic + " does not exist")) + .build(); + } else { + return Response.status(Response.Status.OK).entity(decoder.getCoders()).build(); + } + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + controllerName, topic, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + topic + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + controllerName, topic, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + ":" + topic + " not acceptable")).build(); + } + } + + @GET + @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}") + @ApiOperation( + value = "Gets all filters attached to decoders for a given subscribed networked topic " + "and fact type", + notes = "Decoders are associated with networked topics. A Policy Controller manages " + + "multiple topics and therefore its attached decoders. " + + "A Policy Controller uses filters to further specify the fact mapping. " + + "Filters are applied on a per fact type (classname).", + responseContainer = "List", response = CoderFilters.class) + @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller, topic, or fact type cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decoderFilter( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Networked Topic Name", required = true) @PathParam("topic") String topic, + @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + final ProtocolCoderToolset decoder = + EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + final CoderFilters filters = decoder.getCoder(factClass); + if (filters == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(topic + ":" + factClass + " does not exist")).build(); + } else { + return Response.status(Response.Status.OK).entity(filters).build(); + } + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", this, + controllerName, topic, factClass, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", this, + controllerName, topic, factClass, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")).build(); + } + } + + @PUT + @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}") + @ApiOperation(value = "Attaches filters to the decoder for a given networked topic " + "and fact type", + notes = "Decoders are associated with networked topics. A Policy Controller manages " + + "multiple topics and therefore its attached decoders. " + + "A Policy Controller uses filters to further specify the fact mapping. " + + "Filters are applied on a per fact type (classname).", + responseContainer = "List", response = CoderFilters.class) + @ApiResponses(value = { + @ApiResponse(code = 404, + message = "The controller, topic, fact type, cannot be found, " + + "or a filter has not been provided"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decoderFilter( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, + @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass, + @ApiParam(value = "Configuration Filter", required = true) JsonProtocolFilter configFilters) { + + if (configFilters == null) { + return Response.status(Response.Status.BAD_REQUEST).entity(new Error("Configuration Filters not provided")) + .build(); + } + + try { + final DroolsController drools = this.getDroolsController(controllerName); + final ProtocolCoderToolset decoder = + EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + final CoderFilters filters = decoder.getCoder(factClass); + if (filters == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(topic + ":" + factClass + " does not exist")).build(); + } + filters.setFilter(configFilters); + return Response.status(Response.Status.OK).entity(filters).build(); + } catch (final IllegalArgumentException e) { + logger.debug( + "{}: cannot get decoder filters for policy-controller {} topic {} type {} filters {} because of {}", + this, controllerName, topic, factClass, configFilters, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug( + "{}: cannot get decoder filters for policy-controller {} topic {} type {} filters {} because of {}", + this, controllerName, topic, factClass, configFilters, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")).build(); + } + } - public String getJsonEncoding() { - return jsonEncoding; + @GET + @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rules") + @ApiOperation(value = "Gets the filter rules attached to a topic decoder of a controller", + notes = "Decoders are associated with networked topics. A Policy Controller manages " + + "multiple topics and therefore its attached decoders. " + + "A Policy Controller uses filters to further specify the fact mapping. " + + "Filters are applied on a per fact type and are composed of field matching rules. ", + responseContainer = "List", response = FilterRule.class) + @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller, topic, or fact type cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decoderFilterRules( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, + @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + final ProtocolCoderToolset decoder = + EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + + final CoderFilters filters = decoder.getCoder(factClass); + if (filters == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")).build(); + } + + final JsonProtocolFilter filter = filters.getFilter(); + if (filter == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")).build(); + } + + return Response.status(Response.Status.OK).entity(filter.getRules()).build(); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", this, + controllerName, topic, factClass, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get decoder filters for policy-controller {} topic {} type {} because of {}", this, + controllerName, topic, factClass, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")).build(); + } } - public void setJsonEncoding(String jsonEncoding) { - this.jsonEncoding = jsonEncoding; + @GET + @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rules/{ruleName}") + @ApiOperation(value = "Gets a filter rule by name attached to a topic decoder of a controller", + notes = "Decoders are associated with networked topics. A Policy Controller manages " + + "multiple topics and therefore its attached decoders. " + + "A Policy Controller uses filters to further specify the fact mapping. " + + "Filters are applied on a per fact type and are composed of field matching rules. ", + responseContainer = "List", response = FilterRule.class) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "The controller, topic, fact type, or rule name cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decoderFilterRules( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, + @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass, + @ApiParam(value = "Rule Name", required = true) @PathParam("ruleName") String ruleName) { + try { + final DroolsController drools = this.getDroolsController(controllerName); + final ProtocolCoderToolset decoder = + EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + + final CoderFilters filters = decoder.getCoder(factClass); + if (filters == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")).build(); + } + + final JsonProtocolFilter filter = filters.getFilter(); + if (filter == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")).build(); + } + + return Response.status(Response.Status.OK).entity(filter.getRules(ruleName)).build(); + } catch (final IllegalArgumentException e) { + logger.debug( + "{}: cannot get decoder filters for policy-controller {} topic {} type {} rule {} because of {}", + this, controllerName, topic, factClass, ruleName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + ": " + ruleName + " not found")) + .build(); + } catch (final IllegalStateException e) { + logger.debug( + "{}: cannot get decoder filters for policy-controller {} topic {} type {} rule {} because of {}", + this, controllerName, topic, factClass, ruleName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error( + controllerName + ":" + topic + ":" + factClass + ":" + ruleName + " not acceptable")) + .build(); + } } - public Boolean getEncoding() { - return encoding; + @DELETE + @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rules/{ruleName}") + @ApiOperation(value = "Deletes a filter rule by name attached to a topic decoder of a controller", + notes = "Decoders are associated with networked topics. A Policy Controller manages " + + "multiple topics and therefore its attached decoders. " + + "A Policy Controller uses filters to further specify the fact mapping. " + + "Filters are applied on a per fact type and are composed of field matching rules. ", + responseContainer = "List", response = FilterRule.class) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "The controller, topic, fact type, or rule name cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decoderFilterRuleDelete( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, + @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass, + @ApiParam(value = "Rule Name", required = true) @PathParam("ruleName") String ruleName, + @ApiParam(value = "Filter Rule", required = true) FilterRule rule) { + + try { + final DroolsController drools = this.getDroolsController(controllerName); + final ProtocolCoderToolset decoder = + EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + + final CoderFilters filters = decoder.getCoder(factClass); + if (filters == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")).build(); + } + + final JsonProtocolFilter filter = filters.getFilter(); + if (filter == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")).build(); + } + + if (rule == null) { + filter.deleteRules(ruleName); + return Response.status(Response.Status.OK).entity(filter.getRules()).build(); + } + + if (rule.getName() == null || !rule.getName().equals(ruleName)) { + return Response.status(Response.Status.BAD_REQUEST).entity(new Error(controllerName + ":" + topic + ":" + + factClass + ":" + ruleName + " rule name request inconsistencies (" + rule.getName() + ")")) + .build(); + } + + filter.deleteRule(ruleName, rule.getRegex()); + return Response.status(Response.Status.OK).entity(filter.getRules()).build(); + } catch (final IllegalArgumentException e) { + logger.debug( + "{}: cannot get decoder filters for policy-controller {} topic {} type {} rule {} because of {}", + this, controllerName, topic, factClass, ruleName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + ": " + ruleName + " not found")) + .build(); + } catch (final IllegalStateException e) { + logger.debug( + "{}: cannot get decoder filters for policy-controller {} topic {} type {} rule {} because of {}", + this, controllerName, topic, factClass, ruleName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error( + controllerName + ":" + topic + ":" + factClass + ":" + ruleName + " not acceptable")) + .build(); + } } - public void setEncoding(Boolean encoding) { - this.encoding = encoding; + @PUT + @Path("engine/controllers/{controller}/decoders/{topic}/filters/{factType}/rules") + @ApiOperation(value = "Places a new filter rule in a topic decoder", + notes = "Decoders are associated with networked topics. A Policy Controller manages " + + "multiple topics and therefore its attached decoders. " + + "A Policy Controller uses filters to further specify the fact mapping. " + + "Filters are applied on a per fact type and are composed of field matching rules. ", + responseContainer = "List", response = FilterRule.class) + @ApiResponses(value = {@ApiResponse(code = 404, message = "The controller, topic, or fact type cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decoderFilterRule( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, + @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass, + @ApiParam(value = "Rule Name", required = true) @PathParam("ruleName") String ruleName, + @ApiParam(value = "Filter Rule", required = true) FilterRule rule) { + + try { + final DroolsController drools = this.getDroolsController(controllerName); + final ProtocolCoderToolset decoder = + EventProtocolCoder.manager.getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + + final CoderFilters filters = decoder.getCoder(factClass); + if (filters == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " does not exist")).build(); + } + + final JsonProtocolFilter filter = filters.getFilter(); + if (filter == null) { + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " no filters")).build(); + } + + if (rule.getName() == null) { + return Response.status(Response.Status.BAD_REQUEST).entity(new Error(controllerName + ":" + topic + ":" + + factClass + " rule name request inconsistencies (" + rule.getName() + ")")).build(); + } + + filter.addRule(rule.getName(), rule.getRegex()); + return Response.status(Response.Status.OK).entity(filter.getRules()).build(); + } catch (final IllegalArgumentException e) { + logger.debug( + "{}: cannot access decoder filter rules for policy-controller {} topic {} type {} rule {} because of {}", + this, controllerName, topic, factClass, ruleName, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug( + "{}: cannot access decoder filter rules for policy-controller {} topic {} type {} rule {} because of {}", + this, controllerName, topic, factClass, ruleName, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + ":" + topic + ":" + factClass + " not acceptable")).build(); + } } - public Boolean getDecoding() { - return decoding; + @POST + @Path("engine/controllers/{controller}/decoders/{topic}") + @Consumes(MediaType.TEXT_PLAIN) + @ApiOperation(value = "Decodes a string into a fact object, and encodes it back into a string", + notes = "Tests the decode/encode functions of a controller", response = CodingResult.class) + @ApiResponses(value = {@ApiResponse(code = 400, message = "Bad input has been provided"), + @ApiResponse(code = 404, message = "The controller cannot be found"), @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response decode( + @ApiParam(value = "Policy Controller Name", required = true) @PathParam("controller") String controllerName, + @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, + @ApiParam(value = "JSON String to decode", required = true) String json) { + + PolicyController policyController; + try { + policyController = PolicyController.factory.get(controllerName); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + controllerName, topic, e.getMessage(), e); + return Response.status(Response.Status.NOT_FOUND) + .entity(new Error(controllerName + ":" + topic + ":" + " not found")).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get decoders for policy-controller {} topic {} because of {}", this, + controllerName, topic, e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + ":" + topic + ":" + " not acceptable")).build(); + } + + final CodingResult result = new CodingResult(); + result.setDecoding(false); + result.setEncoding(false); + result.setJsonEncoding(null); + + Object event; + try { + event = EventProtocolCoder.manager.decode(policyController.getDrools().getGroupId(), + policyController.getDrools().getArtifactId(), topic, json); + result.setDecoding(true); + } catch (final Exception e) { + logger.debug("{}: cannot get policy-controller {} topic {} because of {}", this, controllerName, topic, + e.getMessage(), e); + return Response.status(Response.Status.BAD_REQUEST).entity(new Error(e.getMessage())).build(); + } + + try { + result.setJsonEncoding(EventProtocolCoder.manager.encode(topic, event)); + result.setEncoding(true); + } catch (final Exception e) { + // continue so to propagate decoding results .. + logger.debug("{}: cannot encode for policy-controller {} topic {} because of {}", this, controllerName, + topic, e.getMessage(), e); + } + + return Response.status(Response.Status.OK).entity(result).build(); } - public void setDecoding(Boolean decoding) { - this.decoding = decoding; + @GET + @Path("engine/controllers/{controller}/encoders") + @ApiOperation(value = "Retrieves the encoder filters of a controller", + notes = "The encoders serializes a fact object, typically for network transmission", + responseContainer = "List", response = CoderFilters.class) + @ApiResponses(value = {@ApiResponse(code = 400, message = "Bad input has been provided"), @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response encoderFilters(@ApiParam(value = "Policy Controller Name", + required = true) @PathParam("controller") String controllerName) { + List<CoderFilters> encoders; + try { + final PolicyController controller = PolicyController.factory.get(controllerName); + final DroolsController drools = controller.getDrools(); + encoders = EventProtocolCoder.manager.getEncoderFilters(drools.getGroupId(), drools.getArtifactId()); + } catch (final IllegalArgumentException e) { + logger.debug("{}: cannot get encoder filters for policy-controller {} because of {}", this, controllerName, + e.getMessage(), e); + return Response.status(Response.Status.BAD_REQUEST) + .entity(new Error(controllerName + " not found: " + e.getMessage())).build(); + } catch (final IllegalStateException e) { + logger.debug("{}: cannot get encoder filters for policy-controller {} because of {}", this, controllerName, + e.getMessage(), e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(controllerName + " is not accepting the request")).build(); + } + + return Response.status(Response.Status.OK).entity(encoders).build(); } - } - /** - * Generic Error Reporting class - */ - public static class Error { - private String msg; + @GET + @Path("engine/topics") + @ApiOperation(value = "Retrieves the managed topics", notes = "Network Topics Aggregation", + response = TopicEndpoint.class) + public Response topics() { + return Response.status(Response.Status.OK).entity(ProxyTopicEndpointManager.getInstance()).build(); + } + + @GET + @Path("engine/topics/switches") + @ApiOperation(value = "Topics Control Switches", notes = "List of the Topic Control Switches", + responseContainer = "List") + public Response topicSwitches() { + return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); + } + + @PUT + @Path("engine/topics/switches/lock") + @ApiOperation(value = "Locks all the managed topics", notes = "The operation affects all managed sources and sinks", + response = TopicEndpoint.class) + @ApiResponses(value = {@ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response topicsLock() { + final boolean success = ProxyTopicEndpointManager.getInstance().lock(); + if (success) { + return Response.status(Status.OK).entity(ProxyTopicEndpointManager.getInstance()).build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")).build(); + } + } + + @DELETE + @Path("engine/topics/switches/lock") + @ApiOperation(value = "Unlocks all the managed topics", + notes = "The operation affects all managed sources and sinks", response = TopicEndpoint.class) + @ApiResponses(value = {@ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response topicsUnlock() { + final boolean success = ProxyTopicEndpointManager.getInstance().unlock(); + if (success) { + return Response.status(Status.OK).entity(ProxyTopicEndpointManager.getInstance()).build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("cannot perform operation")).build(); + } + } + + @GET + @Path("engine/topics/sources") + @ApiOperation(value = "Retrieves the managed topic sources", notes = "Network Topic Sources Agregation", + responseContainer = "List", response = TopicSource.class) + public Response sources() { + return Response.status(Response.Status.OK).entity(ProxyTopicEndpointManager.getInstance().getTopicSources()) + .build(); + } + + @GET + @Path("engine/topics/sinks") + @ApiOperation(value = "Retrieves the managed topic sinks", notes = "Network Topic Sinks Agregation", + responseContainer = "List", response = TopicSink.class) + public Response sinks() { + return Response.status(Response.Status.OK).entity(ProxyTopicEndpointManager.getInstance().getTopicSinks()) + .build(); + } + + @GET + @Path("engine/topics/sources/ueb") + @ApiOperation(value = "Retrieves the UEB managed topic sources", notes = "UEB Topic Sources Agregation", + responseContainer = "List", response = UebTopicSource.class) + public Response uebSources() { + return Response.status(Response.Status.OK).entity(ProxyTopicEndpointManager.getInstance().getUebTopicSources()) + .build(); + } + + @GET + @Path("engine/topics/sinks/ueb") + @ApiOperation(value = "Retrieves the UEB managed topic sinks", notes = "UEB Topic Sinks Agregation", + responseContainer = "List", response = UebTopicSink.class) + public Response uebSinks() { + return Response.status(Response.Status.OK).entity(ProxyTopicEndpointManager.getInstance().getUebTopicSinks()) + .build(); + } + + @GET + @Path("engine/topics/sources/dmaap") + @ApiOperation(value = "Retrieves the DMaaP managed topic sources", notes = "DMaaP Topic Sources Agregation", + responseContainer = "List", response = DmaapTopicSource.class) + public Response dmaapSources() { + return Response.status(Response.Status.OK) + .entity(ProxyTopicEndpointManager.getInstance().getDmaapTopicSources()).build(); + } + + @GET + @Path("engine/topics/sinks/dmaap") + @ApiOperation(value = "Retrieves the DMaaP managed topic sinks", notes = "DMaaP Topic Sinks Agregation", + responseContainer = "List", response = DmaapTopicSink.class) + public Response dmaapSinks() { + return Response.status(Response.Status.OK).entity(ProxyTopicEndpointManager.getInstance().getDmaapTopicSinks()) + .build(); + } + + @GET + @Path("engine/topics/sources/ueb/{topic}") + @ApiOperation(value = "Retrieves an UEB managed topic source", + notes = "This is an UEB Network Communicaton Endpoint source of messages for the Engine", + response = UebTopicSource.class) + public Response uebSourceTopic(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + return Response.status(Response.Status.OK) + .entity(ProxyTopicEndpointManager.getInstance().getUebTopicSource(topic)).build(); + } + + @GET + @Path("engine/topics/sinks/ueb/{topic}") + @ApiOperation(value = "Retrieves an UEB managed topic sink", + notes = "This is an UEB Network Communicaton Endpoint destination of messages from the Engine", + response = UebTopicSink.class) + public Response uebSinkTopic(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + return Response.status(Response.Status.OK) + .entity(ProxyTopicEndpointManager.getInstance().getUebTopicSink(topic)).build(); + } + + @GET + @Path("engine/topics/sources/dmaap/{topic}") + @ApiOperation(value = "Retrieves a DMaaP managed topic source", + notes = "This is a DMaaP Network Communicaton Endpoint source of messages for the Engine", + response = DmaapTopicSource.class) + public Response dmaapSourceTopic( + @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + return Response.status(Response.Status.OK) + .entity(ProxyTopicEndpointManager.getInstance().getDmaapTopicSource(topic)).build(); + } + + @GET + @Path("engine/topics/sinks/dmaap/{topic}") + @ApiOperation(value = "Retrieves a DMaaP managed topic sink", + notes = "This is a DMaaP Network Communicaton Endpoint destination of messages from the Engine", + response = DmaapTopicSink.class) + public Response dmaapSinkTopic(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + return Response.status(Response.Status.OK) + .entity(ProxyTopicEndpointManager.getInstance().getDmaapTopicSink(topic)).build(); + } + + @GET + @Path("engine/topics/sources/ueb/{topic}/events") + @ApiOperation(value = "Retrieves the latest events received by an UEB topic", + notes = "This is a UEB Network Communicaton Endpoint source of messages for the Engine", + responseContainer = "List") + public Response uebSourceEvents(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + return Response.status(Status.OK) + .entity(Arrays + .asList(ProxyTopicEndpointManager.getInstance().getUebTopicSource(topic).getRecentEvents())) + .build(); + } + + @GET + @Path("engine/topics/sinks/ueb/{topic}/events") + @ApiOperation(value = "Retrieves the latest events sent from a topic", + notes = "This is a UEB Network Communicaton Endpoint sink of messages from the Engine", + responseContainer = "List") + public Response uebSinkEvents(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + return Response.status(Status.OK) + .entity(Arrays.asList(ProxyTopicEndpointManager.getInstance().getUebTopicSink(topic).getRecentEvents())) + .build(); + } + + @GET + @Path("engine/topics/sources/dmaap/{topic}/events") + @ApiOperation(value = "Retrieves the latest events received by a DMaaP topic", + notes = "This is a DMaaP Network Communicaton Endpoint source of messages for the Engine", + responseContainer = "List") + public Response dmaapSourceEvents( + @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + return Response.status(Status.OK) + .entity(Arrays + .asList(ProxyTopicEndpointManager.getInstance().getDmaapTopicSource(topic).getRecentEvents())) + .build(); + } - public Error(String msg) { - this.setError(msg); + @GET + @Path("engine/topics/sinks/dmaap/{topic}/events") + @ApiOperation(value = "Retrieves the latest events send through a DMaaP topic", + notes = "This is a DMaaP Network Communicaton Endpoint destination of messages from the Engine", + responseContainer = "List") + public Response dmaapSinkEvents(@PathParam("topic") String topic) { + return Response.status(Status.OK) + .entity(Arrays + .asList(ProxyTopicEndpointManager.getInstance().getDmaapTopicSink(topic).getRecentEvents())) + .build(); + } + + @GET + @Path("engine/topics/sinks/noop") + @ApiOperation(value = "Retrieves the NOOP managed topic sinks", notes = "NOOP Topic Sinks Agregation", + responseContainer = "List", response = NoopTopicSink.class) + public Response noopSinks() { + return Response.status(Response.Status.OK).entity(ProxyTopicEndpointManager.getInstance().getNoopTopicSinks()) + .build(); + } + + @GET + @Path("engine/topics/sinks/noop/{topic}") + @ApiOperation(value = "Retrieves a NOOP managed topic sink", + notes = "NOOP is an dev/null Network Communicaton Sink", response = NoopTopicSink.class) + public Response noopSinkTopic(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + return Response.status(Response.Status.OK) + .entity(ProxyTopicEndpointManager.getInstance().getNoopTopicSink(topic)).build(); + } + + @GET + @Path("engine/topics/sinks/noop/{topic}/events") + @ApiOperation(value = "Retrieves the latest events send through a NOOP topic", + notes = "NOOP is an dev/null Network Communicaton Sink", responseContainer = "List") + public Response noopSinkEvents(@PathParam("topic") String topic) { + return Response.status(Status.OK) + .entity(Arrays + .asList(ProxyTopicEndpointManager.getInstance().getNoopTopicSink(topic).getRecentEvents())) + .build(); + } + + @GET + @Path("engine/topics/sources/ueb/{topic}/switches") + @ApiOperation(value = "UEB Topic Control Switches", notes = "List of the UEB Topic Control Switches", + responseContainer = "List") + public Response uebTopicSwitches() { + return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); } - public String getError() { - return msg; + @PUT + @Path("engine/topics/sources/ueb/{topic}/switches/lock") + @ApiOperation(value = "Locks an UEB Source topic", response = UebTopicSource.class) + @ApiResponses(value = {@ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response uebTopicLock(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + final UebTopicSource source = ProxyTopicEndpointManager.getInstance().getUebTopicSource(topic); + final boolean success = source.lock(); + if (success) { + return Response.status(Status.OK).entity(source).build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE).entity(makeTopicOperError(topic)).build(); + } } - public void setError(String msg) { - this.msg = msg; + @DELETE + @Path("engine/topics/sources/ueb/{topic}/switches/lock") + @ApiOperation(value = "Unlocks an UEB Source topic", response = UebTopicSource.class) + @ApiResponses(value = {@ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response uebTopicUnlock(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + final UebTopicSource source = ProxyTopicEndpointManager.getInstance().getUebTopicSource(topic); + final boolean success = source.unlock(); + if (success) { + return Response.status(Status.OK).entity(source).build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE).entity(makeTopicOperError(topic)).build(); + } } - } - /** - * Feed Ports into Resources - */ - public enum Inputs { - configuration, - } + private Error makeTopicOperError(String topic) { + return new Error("cannot perform operation on " + topic); + } - /** - * Resource Toggles - */ - public enum Switches { - activation, lock, - } + @GET + @Path("engine/topics/sources/dmaap/{topic}/switches") + @ApiOperation(value = "DMaaP Topic Control Switches", notes = "List of the DMaaP Topic Control Switches", + responseContainer = "List") + public Response dmaapTopicSwitches() { + return Response.status(Response.Status.OK).entity(Arrays.asList(Switches.values())).build(); + } + + @PUT + @Path("engine/topics/sources/dmaap/{topic}/switches/lock") + @ApiOperation(value = "Locks an DMaaP Source topic", response = DmaapTopicSource.class) + @ApiResponses(value = {@ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response dmmapTopicLock(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + final DmaapTopicSource source = ProxyTopicEndpointManager.getInstance().getDmaapTopicSource(topic); + final boolean success = source.lock(); + if (success) { + return Response.status(Status.OK).entity(source).build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE).entity(makeTopicOperError(topic)).build(); + } + } + + @DELETE + @Path("engine/topics/sources/dmaap/{topic}/switches/lock") + @ApiOperation(value = "Unlocks an DMaaP Source topic", response = DmaapTopicSource.class) + @ApiResponses(value = {@ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled")}) + public Response dmaapTopicUnlock( + @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic) { + final DmaapTopicSource source = ProxyTopicEndpointManager.getInstance().getDmaapTopicSource(topic); + final boolean success = source.unlock(); + if (success) { + return Response.status(Status.OK).entity(source).build(); + } else { + return Response.status(Status.SERVICE_UNAVAILABLE).entity(makeTopicOperError(topic)).build(); + } + } + + @PUT + @Path("engine/topics/sources/ueb/{topic}/events") + @Consumes(MediaType.TEXT_PLAIN) + @ApiOperation(value = "Offers an event to an UEB topic for internal processing by the engine", + notes = "The offered event is treated as it was incoming from the network", responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 404, message = "The topic information cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled"), + @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) + public Response uebOffer(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, + @ApiParam(value = "Network Message", required = true) String json) { + try { + final UebTopicSource uebReader = ProxyTopicEndpointManager.getInstance().getUebTopicSource(topic); + final boolean success = uebReader.offer(json); + if (success) { + return Response.status(Status.OK) + .entity(Arrays.asList( + ProxyTopicEndpointManager.getInstance().getUebTopicSource(topic).getRecentEvents())) + .build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("Failure to inject event over " + topic)) + .build(); + } + } catch (final IllegalArgumentException e) { + logNoUebEncoder(topic, e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(topic + " not found")).build(); + } catch (final IllegalStateException e) { + logNoUebEncoder(topic, e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(topic + " not acceptable due to current state")).build(); + } catch (final Exception e) { + logNoUebEncoder(topic, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); + } + } + + private void logNoUebEncoder(String topic, Exception ex) { + logger.debug("{}: cannot offer for encoder ueb topic for {} because of {}", this, topic, ex.getMessage(), ex); + } + + @PUT + @Path("engine/topics/sources/dmaap/{topic}/events") + @Consumes(MediaType.TEXT_PLAIN) + @ApiOperation(value = "Offers an event to a DMaaP topic for internal processing by the engine", + notes = "The offered event is treated as it was incoming from the network", responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 404, message = "The topic information cannot be found"), + @ApiResponse(code = 406, + message = "The system is an administrative state that prevents " + "this request to be fulfilled"), + @ApiResponse(code = 500, message = "A server error has occurred processing this request")}) + public Response dmaapOffer(@ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, + @ApiParam(value = "Network Message", required = true) String json) { + try { + final DmaapTopicSource dmaapReader = ProxyTopicEndpointManager.getInstance().getDmaapTopicSource(topic); + final boolean success = dmaapReader.offer(json); + if (success) { + return Response.status(Status.OK) + .entity(Arrays.asList( + ProxyTopicEndpointManager.getInstance().getDmaapTopicSource(topic).getRecentEvents())) + .build(); + } else { + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("Failure to inject event over " + topic)) + .build(); + } + } catch (final IllegalArgumentException e) { + logNoDmaapEncoder(topic, e); + return Response.status(Response.Status.NOT_FOUND).entity(new Error(topic + " not found")).build(); + } catch (final IllegalStateException e) { + logNoDmaapEncoder(topic, e); + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(topic + " not acceptable due to current state")).build(); + } catch (final Exception e) { + logNoDmaapEncoder(topic, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); + } + } + + private void logNoDmaapEncoder(String topic, Exception ex) { + logger.debug("{}: cannot offer for encoder dmaap topic for {} because of {}", this, topic, ex.getMessage(), ex); + } + + @GET + @Path("engine/tools/uuid") + @ApiOperation(value = "Produces an UUID", notes = "UUID generation utility") + @Produces(MediaType.TEXT_PLAIN) + public Response uuid() { + return Response.status(Status.OK).entity(UUID.randomUUID().toString()).build(); + } + + @GET + @Path("engine/tools/loggers") + @ApiOperation(value = "all active loggers", responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 500, message = "logging misconfiguration")}) + public Response loggers() { + final List<String> names = new ArrayList<>(); + if (!(LoggerFactory.getILoggerFactory() instanceof LoggerContext)) { + logger.warn("The SLF4J logger factory is not configured for logback"); + return Response.status(Status.INTERNAL_SERVER_ERROR).entity(names).build(); + } + + final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + for (final Logger lgr : context.getLoggerList()) { + names.add(lgr.getName()); + } + + return Response.status(Status.OK).entity(names).build(); + } + + @GET + @Path("engine/tools/loggers/{logger}") + @Produces(MediaType.TEXT_PLAIN) + @ApiOperation(value = "logging level of a logger") + @ApiResponses(value = {@ApiResponse(code = 500, message = "logging misconfiguration"), + @ApiResponse(code = 404, message = "logger not found")}) + public Response loggerName( + @ApiParam(value = "Logger Name", required = true) @PathParam("logger") String loggerName) { + if (!(LoggerFactory.getILoggerFactory() instanceof LoggerContext)) { + logger.warn("The SLF4J logger factory is not configured for logback"); + return Response.status(Status.INTERNAL_SERVER_ERROR).build(); + } + + final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); + final ch.qos.logback.classic.Logger lgr = context.getLogger(loggerName); + if (lgr == null) { + return Response.status(Status.NOT_FOUND).build(); + } + + final String loggerLevel = (lgr.getLevel() != null) ? lgr.getLevel().toString() : ""; + return Response.status(Status.OK).entity(loggerLevel).build(); + } + + @PUT + @Path("engine/tools/loggers/{logger}/{level}") + @Produces(MediaType.TEXT_PLAIN) + @Consumes(MediaType.TEXT_PLAIN) + @ApiOperation(value = "sets the logger level", notes = "Please use the SLF4J logger levels") + @ApiResponses(value = {@ApiResponse(code = 500, message = "logging misconfiguration"), + @ApiResponse(code = 404, message = "logger not found")}) + public Response loggerName(@ApiParam(value = "Logger Name", required = true) @PathParam("logger") String loggerName, + @ApiParam(value = "Logger Level", required = true) @PathParam("level") String loggerLevel) { + + String newLevel; + try { + newLevel = LoggerUtil.setLevel(loggerName, loggerLevel); + } catch (final IllegalArgumentException e) { + logger.warn("{}: no logger {}", this, loggerName, loggerLevel, e); + return Response.status(Status.NOT_FOUND).build(); + } catch (final IllegalStateException e) { + logger.warn("{}: logging framework unavailable for {} / {}", this, loggerName, loggerLevel, e); + return Response.status(Status.INTERNAL_SERVER_ERROR).build(); + } + + return Response.status(Status.OK).entity(newLevel + + ).build(); + } + + /** + * gets the underlying drools controller from the named policy controller + * + * @param controllerName the policy controller name + * @return the underlying drools controller + * @throws IllegalArgumentException if an invalid controller name has been passed in + */ + protected DroolsController getDroolsController(String controllerName) { + final PolicyController controller = PolicyController.factory.get(controllerName); + if (controller == null) { + throw new IllegalArgumentException(controllerName + " does not exist"); + } + + final DroolsController drools = controller.getDrools(); + if (drools == null) { + throw new IllegalArgumentException(controllerName + " has no drools configuration"); + } + + return drools; + } + + /* + * Helper classes for aggregation of results + */ + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("rest-telemetry-api []"); + return builder.toString(); + } + + /** + * Coding/Encoding Results Aggregation Helper class + */ + public static class CodingResult { + /** + * serialized output + */ + + private String jsonEncoding; + /** + * encoding result + */ + + private Boolean encoding; + + /** + * decoding result + */ + private Boolean decoding; + + public String getJsonEncoding() { + return jsonEncoding; + } + + public void setJsonEncoding(String jsonEncoding) { + this.jsonEncoding = jsonEncoding; + } + + public Boolean getEncoding() { + return encoding; + } + + public void setEncoding(Boolean encoding) { + this.encoding = encoding; + } + + public Boolean getDecoding() { + return decoding; + } + + public void setDecoding(Boolean decoding) { + this.decoding = decoding; + } + } + + /** + * Generic Error Reporting class + */ + public static class Error { + private String msg; + + public Error(String msg) { + this.setError(msg); + } + + public String getError() { + return msg; + } + + public void setError(String msg) { + this.msg = msg; + } + } + + /** + * Feed Ports into Resources + */ + public enum Inputs { + configuration, + } + + /** + * Resource Toggles + */ + public enum Switches { + activation, lock, + } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/Main.java b/policy-management/src/main/java/org/onap/policy/drools/system/Main.java index 43216000..c8956839 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/Main.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/Main.java @@ -25,7 +25,7 @@ import java.nio.file.Paths; import java.util.Properties; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.drools.properties.DroolsProperties; import org.onap.policy.drools.utils.logging.LoggerUtil; import org.onap.policy.drools.utils.logging.MDCTransaction; import org.slf4j.Logger; @@ -134,7 +134,7 @@ public class Main { for (final Properties controllerProperties : SystemPersistence.manager .getControllerProperties()) { final String controllerName = - controllerProperties.getProperty(PolicyProperties.PROPERTY_CONTROLLER_NAME); + controllerProperties.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME); try { trans = MDCTransaction.newTransaction(null, null).setServiceName(Main.class.getSimpleName()). diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyController.java b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyController.java index 5324937e..9e01634b 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyController.java @@ -23,86 +23,82 @@ package org.onap.policy.drools.system; import java.util.List; import java.util.Properties; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.capabilities.Lockable; +import org.onap.policy.common.capabilities.Startable; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; import org.onap.policy.drools.controller.DroolsController; -import org.onap.policy.drools.event.comm.TopicSource; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.properties.Lockable; -import org.onap.policy.drools.properties.Startable; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; /** - * A Policy Controller is the higher level unit of control. It corresponds to - * the ncomp equivalent of a controller. It provides management of underlying - * resources associated with the policy controller, which is a) communication - * infrastructure, and b) policy-core (drools) session infrastructure + * A Policy Controller is the higher level unit of control. It corresponds to the ncomp equivalent + * of a controller. It provides management of underlying resources associated with the policy + * controller, which is a) communication infrastructure, and b) policy-core (drools) session + * infrastructure * */ public interface PolicyController extends Startable, Lockable { - - /** - * Factory that tracks and manages Policy Controllers - */ - public static PolicyControllerFactory factory = - new IndexedPolicyControllerFactory(); - - /** - * name of this Policy Controller - */ - public String getName(); - - /** - * Get the topic readers of interest for this controller - */ - public List<? extends TopicSource> getTopicSources(); - - /** - * Get the topic readers of interest for this controller - */ - public List<? extends TopicSink> getTopicSinks(); - - /** - * Get the Drools Controller - */ - public DroolsController getDrools(); - - /** - * update maven configuration - * - * @param newDroolsConfiguration new drools configuration - * @return true if the update was successful, false otherwise - */ - public boolean updateDrools(DroolsConfiguration newDroolsConfiguration); - - /** - * Get the Properties - */ - public Properties getProperties(); - - /** - * Attempts delivering of an String over communication - * infrastructure "busType" - * - * @param eventBus Communication infrastructure identifier - * @param topic topic - * @param event the event object to send - * - * @return true if successful, false if a failure has occurred. - * @throws IllegalArgumentException when invalid or insufficient - * properties are provided - * @throws IllegalStateException when the engine is in a state where - * this operation is not permitted (ie. locked or stopped). - * @throws UnsupportedOperationException when the engine cannot deliver due - * to the functionality missing (ie. communication infrastructure - * not supported. - */ - public boolean deliver(CommInfrastructure busType, String topic, - Object event); - - /** - * halts and permanently releases all resources - * @throws IllegalStateException - */ - public void halt(); - + + /** + * Factory that tracks and manages Policy Controllers + */ + public static PolicyControllerFactory factory = new IndexedPolicyControllerFactory(); + + /** + * name of this Policy Controller + */ + public String getName(); + + /** + * Get the topic readers of interest for this controller + */ + public List<? extends TopicSource> getTopicSources(); + + /** + * Get the topic readers of interest for this controller + */ + public List<? extends TopicSink> getTopicSinks(); + + /** + * Get the Drools Controller + */ + public DroolsController getDrools(); + + /** + * update maven configuration + * + * @param newDroolsConfiguration new drools configuration + * @return true if the update was successful, false otherwise + */ + public boolean updateDrools(DroolsConfiguration newDroolsConfiguration); + + /** + * Get the Properties + */ + public Properties getProperties(); + + /** + * Attempts delivering of an String over communication infrastructure "busType" + * + * @param eventBus Communication infrastructure identifier + * @param topic topic + * @param event the event object to send + * + * @return true if successful, false if a failure has occurred. + * @throws IllegalArgumentException when invalid or insufficient properties are provided + * @throws IllegalStateException when the engine is in a state where this operation is not + * permitted (ie. locked or stopped). + * @throws UnsupportedOperationException when the engine cannot deliver due to the functionality + * missing (ie. communication infrastructure not supported. + */ + public boolean deliver(CommInfrastructure busType, String topic, Object event); + + /** + * halts and permanently releases all resources + * + * @throws IllegalStateException + */ + public void halt(); + } diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngine.java b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngine.java index d7275578..71c509c2 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngine.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngine.java @@ -20,26 +20,33 @@ package org.onap.policy.drools.system; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + import java.util.ArrayList; import java.util.List; import java.util.Properties; +import org.onap.policy.common.capabilities.Lockable; +import org.onap.policy.common.capabilities.Startable; +import org.onap.policy.common.endpoints.event.comm.Topic; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; +import org.onap.policy.common.endpoints.event.comm.impl.ProxyTopicEndpointManager; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.http.server.impl.IndexedHttpServletServerFactory; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.core.PolicyContainer; import org.onap.policy.drools.core.jmx.PdpJmxListener; -import org.onap.policy.drools.event.comm.Topic; -import org.onap.policy.drools.event.comm.Topic.CommInfrastructure; -import org.onap.policy.drools.event.comm.TopicEndpoint; -import org.onap.policy.drools.event.comm.TopicListener; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.TopicSource; import org.onap.policy.drools.features.PolicyControllerFeatureAPI; import org.onap.policy.drools.features.PolicyEngineFeatureAPI; -import org.onap.policy.drools.http.server.HttpServletServer; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.Lockable; -import org.onap.policy.drools.properties.PolicyProperties; -import org.onap.policy.drools.properties.Startable; +import org.onap.policy.drools.properties.DroolsProperties; import org.onap.policy.drools.protocol.coders.EventProtocolCoder; import org.onap.policy.drools.protocol.configuration.ControllerConfiguration; import org.onap.policy.drools.protocol.configuration.PdpdConfiguration; @@ -49,292 +56,285 @@ import org.onap.policy.drools.utils.logging.MDCTransaction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - /** * Policy Engine, the top abstraction for the Drools PDP Policy Engine. It abstracts away a Drools * PDP Engine from management purposes. This is the best place to looking at the code from a top * down approach. Other managed entities can be obtained from the PolicyEngine, hierarchically. <br> * PolicyEngine 1 --- * PolicyController 1 --- 1 DroolsController 1 --- 1 PolicyContainer 1 --- * - * PolicySession <br> - * PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicReader 1 --- 1 UebTopicReader <br> - * PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicReader 1 --- 1 DmaapTopicReader <br> - * PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicWriter 1 --- 1 DmaapTopicWriter <br> - * PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicReader 1 --- 1 RestTopicReader <br> - * PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicWriter 1 --- 1 RestTopicWriter <br> - * PolicyEngine 1 --- 1 ManagementServer + * PolicySession <br> PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicReader 1 --- 1 + * UebTopicReader <br> PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicReader 1 --- 1 + * DmaapTopicReader <br> PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicWriter 1 --- 1 + * DmaapTopicWriter <br> PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicReader 1 --- 1 + * RestTopicReader <br> PolicyEngine 1 --- 1 TopicEndpointManager 1 -- * TopicWriter 1 --- 1 + * RestTopicWriter <br> PolicyEngine 1 --- 1 ManagementServer */ public interface PolicyEngine extends Startable, Lockable, TopicListener { - /** - * Policy Engine Manager - */ - public static final PolicyEngine manager = new PolicyEngineManager(); - - /** - * Default Telemetry Server Port - */ - public static final int TELEMETRY_SERVER_DEFAULT_PORT = 9696; - - /** - * Default Telemetry Server Hostname - */ - public static final String TELEMETRY_SERVER_DEFAULT_HOST = "localhost"; - - /** - * Default Telemetry Server Name - */ - public static final String TELEMETRY_SERVER_DEFAULT_NAME = "TELEMETRY"; - - /** - * Boot the engine - * - * @param cliArgs command line arguments - */ - public void boot(String[] cliArgs); - - /** - * configure the policy engine according to the given properties - * - * @param properties Policy Engine properties - * @throws IllegalArgumentException when invalid or insufficient properties are provided - */ - public void configure(Properties properties); - - /** - * configure the engine's environment. General lab installation configuration is made available to - * the Engine. Typically, custom lab installation that may be needed by arbitrary drools - * applications are made available, for example network component and database host addresses. - * Multiple environments can be passed in and tracked by the engine. - * - * @param properties an environment properties - */ - public void setEnvironment(Properties properties); - - /** - * gets the engine's environment - * - * @return - */ - public Properties getEnvironment(); - - /** - * gets an environment's value, by 1) first from the engine's environment, and 2) from the OS - * environment - * - * @param key environment key - * @return environment value or null if absent - */ - public String getEnvironmentProperty(String key); - - /** - * sets an engine's environment property - * - * @param key - * @param value - * @return - */ - public String setEnvironmentProperty(String key, String value); - - /** - * registers a new Policy Controller with the Policy Engine initialized per properties. - * - * @param properties properties to initialize the Policy Controller - * @throws IllegalArgumentException when invalid or insufficient properties are provided - * @throws IllegalStateException when the engine is in a state where this operation is not - * permitted. - * @return the newly instantiated Policy Controller - */ - public PolicyController createPolicyController(String name, Properties properties); - - /** - * updates the Policy Engine with the given configuration - * - * @param configuration the configuration - * @return success or failure - * @throws IllegalArgumentException if invalid argument provided - * @throws IllegalStateException if the system is in an invalid state - */ - public boolean configure(PdpdConfiguration configuration); - - /** - * updates a set of Policy Controllers with configuration information - * - * @param configuration - * @return - * @throws IllegalArgumentException - * @throws IllegalStateException - */ - public List<PolicyController> updatePolicyControllers( - List<ControllerConfiguration> configuration); - - /** - * updates an already existing Policy Controller with configuration information - * - * @param configuration configuration - * - * @return the updated Policy Controller - * @throws IllegalArgumentException in the configuration is invalid - * @throws IllegalStateException if the controller is in a bad state - * @throws Exception any other reason - */ - public PolicyController updatePolicyController(ControllerConfiguration configuration); - - /** - * removes the Policy Controller identified by its name from the Policy Engine - * - * @param name name of the Policy Controller - * @return the removed Policy Controller - */ - public void removePolicyController(String name); - - /** - * removes a Policy Controller from the Policy Engine - * - * @param controller the Policy Controller to remove from the Policy Engine - */ - public void removePolicyController(PolicyController controller); - - /** - * returns a list of the available Policy Controllers - * - * @return list of Policy Controllers - */ - public List<PolicyController> getPolicyControllers(); - - - /** - * get policy controller names - * - * @return list of controller names - */ - public List<String> getPolicyControllerIds(); - - /** - * get unmanaged sources - * - * @return unmanaged sources - */ - public List<TopicSource> getSources(); - - /** - * get unmanaged sinks - * - * @return unmanaged sinks - */ - public List<TopicSink> getSinks(); - - /** - * get unmmanaged http servers list - * - * @return http servers - */ - public List<HttpServletServer> getHttpServers(); - - /** - * get properties configuration - * - * @return properties objects - */ - public Properties getProperties(); - - /** - * get features attached to the Policy Engine - * - * @return list of features - */ - public List<PolicyEngineFeatureAPI> getFeatureProviders(); - - /** - * get named feature attached to the Policy Engine - * - * @return the feature - */ - public PolicyEngineFeatureAPI getFeatureProvider(String featureName); - - /** - * get features attached to the Policy Engine - * - * @return list of features - */ - public List<String> getFeatures(); - - /** - * Attempts the dispatching of an "event" object - * - * @param topic topic - * @param event the event object to send - * - * @return true if successful, false if a failure has occurred. - * @throws IllegalArgumentException when invalid or insufficient properties are provided - * @throws IllegalStateException when the engine is in a state where this operation is not - * permitted (ie. locked or stopped). - */ - public boolean deliver(String topic, Object event); - - /** - * Attempts the dispatching of an "event" object over communication infrastructure "busType" - * - * @param topic topic - * @param event the event object to send - * - * @return true if successful, false if a failure has occurred. - * @throws IllegalArgumentException when invalid or insufficient properties are provided - * @throws IllegalStateException when the engine is in a state where this operation is not - * permitted (ie. locked or stopped). - * @throws UnsupportedOperationException when the engine cannot deliver due to the functionality - * missing (ie. communication infrastructure not supported. - */ - public boolean deliver(String busType, String topic, Object event); - - /** - * Attempts the dispatching of an "event" object over communication infrastructure "busType" - * - * @param topic topic - * @param event the event object to send - * - * @return true if successful, false if a failure has occurred. - * @throws IllegalArgumentException when invalid or insufficient properties are provided - * @throws IllegalStateException when the engine is in a state where this operation is not - * permitted (ie. locked or stopped). - * @throws UnsupportedOperationException when the engine cannot deliver due to the functionality - * missing (ie. communication infrastructure not supported. - */ - public boolean deliver(CommInfrastructure busType, String topic, Object event); - - /** - * Attempts delivering of an String over communication infrastructure "busType" - * - * @param topic topic - * @param event the event object to send - * - * @return true if successful, false if a failure has occurred. - * @throws IllegalArgumentException when invalid or insufficient properties are provided - * @throws IllegalStateException when the engine is in a state where this operation is not - * permitted (ie. locked or stopped). - * @throws UnsupportedOperationException when the engine cannot deliver due to the functionality - * missing (ie. communication infrastructure not supported. - */ - public boolean deliver(CommInfrastructure busType, String topic, String event); - - /** - * Invoked when the host goes into the active state. - */ - public void activate(); - - /** - * Invoked when the host goes into the standby state. - */ - public void deactivate(); - - /** - * produces a default telemetry configuration - * - * @return policy engine configuration - */ - public Properties defaultTelemetryConfig(); + /** + * Policy Engine Manager + */ + public static final PolicyEngine manager = new PolicyEngineManager(); + + /** + * Default Telemetry Server Port + */ + public static final int TELEMETRY_SERVER_DEFAULT_PORT = 9696; + + /** + * Default Telemetry Server Hostname + */ + public static final String TELEMETRY_SERVER_DEFAULT_HOST = "localhost"; + + /** + * Default Telemetry Server Name + */ + public static final String TELEMETRY_SERVER_DEFAULT_NAME = "TELEMETRY"; + + /** + * Boot the engine + * + * @param cliArgs command line arguments + */ + public void boot(String[] cliArgs); + + /** + * configure the policy engine according to the given properties + * + * @param properties Policy Engine properties + * @throws IllegalArgumentException when invalid or insufficient properties are provided + */ + public void configure(Properties properties); + + /** + * configure the engine's environment. General lab installation configuration is made available + * to the Engine. Typically, custom lab installation that may be needed by arbitrary drools + * applications are made available, for example network component and database host addresses. + * Multiple environments can be passed in and tracked by the engine. + * + * @param properties an environment properties + */ + public void setEnvironment(Properties properties); + + /** + * gets the engine's environment + * + * @return + */ + public Properties getEnvironment(); + + /** + * gets an environment's value, by 1) first from the engine's environment, and 2) from the OS + * environment + * + * @param key environment key + * @return environment value or null if absent + */ + public String getEnvironmentProperty(String key); + + /** + * sets an engine's environment property + * + * @param key + * @param value + * @return + */ + public String setEnvironmentProperty(String key, String value); + + /** + * registers a new Policy Controller with the Policy Engine initialized per properties. + * + * @param properties properties to initialize the Policy Controller + * @throws IllegalArgumentException when invalid or insufficient properties are provided + * @throws IllegalStateException when the engine is in a state where this operation is not + * permitted. + * @return the newly instantiated Policy Controller + */ + public PolicyController createPolicyController(String name, Properties properties); + + /** + * updates the Policy Engine with the given configuration + * + * @param configuration the configuration + * @return success or failure + * @throws IllegalArgumentException if invalid argument provided + * @throws IllegalStateException if the system is in an invalid state + */ + public boolean configure(PdpdConfiguration configuration); + + /** + * updates a set of Policy Controllers with configuration information + * + * @param configuration + * @return + * @throws IllegalArgumentException + * @throws IllegalStateException + */ + public List<PolicyController> updatePolicyControllers(List<ControllerConfiguration> configuration); + + /** + * updates an already existing Policy Controller with configuration information + * + * @param configuration configuration + * + * @return the updated Policy Controller + * @throws IllegalArgumentException in the configuration is invalid + * @throws IllegalStateException if the controller is in a bad state + * @throws Exception any other reason + */ + public PolicyController updatePolicyController(ControllerConfiguration configuration); + + /** + * removes the Policy Controller identified by its name from the Policy Engine + * + * @param name name of the Policy Controller + * @return the removed Policy Controller + */ + public void removePolicyController(String name); + + /** + * removes a Policy Controller from the Policy Engine + * + * @param controller the Policy Controller to remove from the Policy Engine + */ + public void removePolicyController(PolicyController controller); + + /** + * returns a list of the available Policy Controllers + * + * @return list of Policy Controllers + */ + public List<PolicyController> getPolicyControllers(); + + + /** + * get policy controller names + * + * @return list of controller names + */ + public List<String> getPolicyControllerIds(); + + /** + * get unmanaged sources + * + * @return unmanaged sources + */ + public List<TopicSource> getSources(); + + /** + * get unmanaged sinks + * + * @return unmanaged sinks + */ + public List<TopicSink> getSinks(); + + /** + * get unmmanaged http servers list + * + * @return http servers + */ + public List<HttpServletServer> getHttpServers(); + + /** + * get properties configuration + * + * @return properties objects + */ + public Properties getProperties(); + + /** + * get features attached to the Policy Engine + * + * @return list of features + */ + public List<PolicyEngineFeatureAPI> getFeatureProviders(); + + /** + * get named feature attached to the Policy Engine + * + * @return the feature + */ + public PolicyEngineFeatureAPI getFeatureProvider(String featureName); + + /** + * get features attached to the Policy Engine + * + * @return list of features + */ + public List<String> getFeatures(); + + /** + * Attempts the dispatching of an "event" object + * + * @param topic topic + * @param event the event object to send + * + * @return true if successful, false if a failure has occurred. + * @throws IllegalArgumentException when invalid or insufficient properties are provided + * @throws IllegalStateException when the engine is in a state where this operation is not + * permitted (ie. locked or stopped). + */ + public boolean deliver(String topic, Object event); + + /** + * Attempts the dispatching of an "event" object over communication infrastructure "busType" + * + * @param topic topic + * @param event the event object to send + * + * @return true if successful, false if a failure has occurred. + * @throws IllegalArgumentException when invalid or insufficient properties are provided + * @throws IllegalStateException when the engine is in a state where this operation is not + * permitted (ie. locked or stopped). + * @throws UnsupportedOperationException when the engine cannot deliver due to the functionality + * missing (ie. communication infrastructure not supported. + */ + public boolean deliver(String busType, String topic, Object event); + + /** + * Attempts the dispatching of an "event" object over communication infrastructure "busType" + * + * @param topic topic + * @param event the event object to send + * + * @return true if successful, false if a failure has occurred. + * @throws IllegalArgumentException when invalid or insufficient properties are provided + * @throws IllegalStateException when the engine is in a state where this operation is not + * permitted (ie. locked or stopped). + * @throws UnsupportedOperationException when the engine cannot deliver due to the functionality + * missing (ie. communication infrastructure not supported. + */ + public boolean deliver(CommInfrastructure busType, String topic, Object event); + + /** + * Attempts delivering of an String over communication infrastructure "busType" + * + * @param topic topic + * @param event the event object to send + * + * @return true if successful, false if a failure has occurred. + * @throws IllegalArgumentException when invalid or insufficient properties are provided + * @throws IllegalStateException when the engine is in a state where this operation is not + * permitted (ie. locked or stopped). + * @throws UnsupportedOperationException when the engine cannot deliver due to the functionality + * missing (ie. communication infrastructure not supported. + */ + public boolean deliver(CommInfrastructure busType, String topic, String event); + + /** + * Invoked when the host goes into the active state. + */ + public void activate(); + + /** + * Invoked when the host goes into the standby state. + */ + public void deactivate(); + + /** + * produces a default telemetry configuration + * + * @return policy engine configuration + */ + public Properties defaultTelemetryConfig(); } @@ -342,1128 +342,1168 @@ public interface PolicyEngine extends Startable, Lockable, TopicListener { * Policy Engine Manager Implementation */ class PolicyEngineManager implements PolicyEngine { - private static final String INVALID_TOPIC_MSG = "Invalid Topic"; + private static final String INVALID_TOPIC_MSG = "Invalid Topic"; -private static final String INVALID_EVENT_MSG = "Invalid Event"; + private static final String INVALID_EVENT_MSG = "Invalid Event"; -private static final String ENGINE_STOPPED_MSG = "Policy Engine is stopped"; + private static final String ENGINE_STOPPED_MSG = "Policy Engine is stopped"; -private static final String ENGINE_LOCKED_MSG = "Policy Engine is locked"; + private static final String ENGINE_LOCKED_MSG = "Policy Engine is locked"; -/** - * logger - */ - private static final Logger logger = LoggerFactory.getLogger(PolicyEngineManager.class); - - /** - * Is the Policy Engine running? - */ - protected volatile boolean alive = false; - - /** - * Is the engine locked? - */ - protected volatile boolean locked = false; - - /** - * Properties used to initialize the engine - */ - protected Properties properties; - - /** - * Environment Properties - */ - protected final Properties environment = new Properties(); - - /** - * Policy Engine Sources - */ - protected List<? extends TopicSource> sources = new ArrayList<>(); - - /** - * Policy Engine Sinks - */ - protected List<? extends TopicSink> sinks = new ArrayList<>(); - - /** - * Policy Engine HTTP Servers - */ - protected List<HttpServletServer> httpServers = new ArrayList<>(); - - /** - * gson parser to decode configuration requests - */ - protected final Gson decoder = new GsonBuilder().disableHtmlEscaping().create(); - - - @Override - public synchronized void boot(String[] cliArgs) { - - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.beforeBoot(this, cliArgs)) - return; - } catch (final Exception e) { - logger.error("{}: feature {} before-boot failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } - } + /** + * logger + */ + private static final Logger logger = LoggerFactory.getLogger(PolicyEngineManager.class); - try { - PolicyContainer.globalInit(cliArgs); - } catch (final Exception e) { - logger.error("{}: cannot init policy-container because of {}", this, e.getMessage(), e); - } + /** + * Is the Policy Engine running? + */ + protected volatile boolean alive = false; - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.afterBoot(this)) - return; - } catch (final Exception e) { - logger.error("{}: feature {} after-boot failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } - } - } - - @Override - public synchronized void setEnvironment(Properties properties) { - this.environment.putAll(properties); - } - - @JsonIgnore - @Override - public synchronized Properties getEnvironment() { - return this.environment; - } - - @Override - public synchronized String getEnvironmentProperty(String envKey) { - String value = this.environment.getProperty(envKey); - if (value == null) - value = System.getenv(envKey); - return value; - } - - @Override - public synchronized String setEnvironmentProperty(String envKey, String envValue) { - return (String) this.environment.setProperty(envKey, envValue); - } - - @Override - public final Properties defaultTelemetryConfig() { - final Properties defaultConfig = new Properties(); - - defaultConfig.put(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES, "TELEMETRY"); - defaultConfig.put(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + TELEMETRY_SERVER_DEFAULT_NAME + PolicyProperties.PROPERTY_HTTP_HOST_SUFFIX, - TELEMETRY_SERVER_DEFAULT_HOST); - defaultConfig.put(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + TELEMETRY_SERVER_DEFAULT_NAME + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX, - "" + Integer.toString(TELEMETRY_SERVER_DEFAULT_PORT)); - defaultConfig.put( - PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME - + PolicyProperties.PROPERTY_HTTP_REST_PACKAGES_SUFFIX, - RestManager.class.getPackage().getName()); - defaultConfig.put(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + TELEMETRY_SERVER_DEFAULT_NAME + PolicyProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, - "" + Boolean.TRUE); - defaultConfig.put(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + TELEMETRY_SERVER_DEFAULT_NAME + PolicyProperties.PROPERTY_MANAGED_SUFFIX, - "" + Boolean.FALSE); - - return defaultConfig; - } - - @Override - public synchronized void configure(Properties properties) { - - if (properties == null) { - logger.warn("No properties provided"); - throw new IllegalArgumentException("No properties provided"); - } + /** + * Is the engine locked? + */ + protected volatile boolean locked = false; + + /** + * Properties used to initialize the engine + */ + protected Properties properties; + + /** + * Environment Properties + */ + protected final Properties environment = new Properties(); + + /** + * Policy Engine Sources + */ + protected List<? extends TopicSource> sources = new ArrayList<>(); - /* policy-engine dispatch pre configure hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.beforeConfigure(this, properties)) - return; - } catch (final Exception e) { - logger.error("{}: feature {} before-configure failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + /** + * Policy Engine Sinks + */ + protected List<? extends TopicSink> sinks = new ArrayList<>(); + + /** + * Policy Engine HTTP Servers + */ + protected List<HttpServletServer> httpServers = new ArrayList<>(); + + /** + * gson parser to decode configuration requests + */ + protected final Gson decoder = new GsonBuilder().disableHtmlEscaping().create(); + + + @Override + public synchronized void boot(String[] cliArgs) { + + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.beforeBoot(this, cliArgs)) { + return; + } + } catch (final Exception e) { + logger.error("{}: feature {} before-boot failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + try { + PolicyContainer.globalInit(cliArgs); + } catch (final Exception e) { + logger.error("{}: cannot init policy-container because of {}", this, e.getMessage(), e); + } + + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.afterBoot(this)) { + return; + } + } catch (final Exception e) { + logger.error("{}: feature {} after-boot failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } } - this.properties = properties; + @Override + public synchronized void setEnvironment(Properties properties) { + this.environment.putAll(properties); + } - try { - this.sources = TopicEndpoint.manager.addTopicSources(properties); - for (final TopicSource source : this.sources) { - source.register(this); - } - } catch (final Exception e) { - logger.error("{}: add-sources failed", this, e); + @JsonIgnore + @Override + public synchronized Properties getEnvironment() { + return this.environment; } - try { - this.sinks = TopicEndpoint.manager.addTopicSinks(properties); - } catch (final IllegalArgumentException e) { - logger.error("{}: add-sinks failed", this, e); + @Override + public synchronized String getEnvironmentProperty(String envKey) { + String value = this.environment.getProperty(envKey); + if (value == null) { + value = System.getenv(envKey); + } + return value; } - try { - this.httpServers = HttpServletServer.factory.build(properties); - } catch (final IllegalArgumentException e) { - logger.error("{}: add-http-servers failed", this, e); + @Override + public synchronized String setEnvironmentProperty(String envKey, String envValue) { + return (String) this.environment.setProperty(envKey, envValue); } - /* policy-engine dispatch post configure hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.afterConfigure(this)) - return; - } catch (final Exception e) { - logger.error("{}: feature {} after-configure failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + @Override + public final Properties defaultTelemetryConfig() { + final Properties defaultConfig = new Properties(); + + defaultConfig.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, "TELEMETRY"); + defaultConfig.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME + + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, TELEMETRY_SERVER_DEFAULT_HOST); + defaultConfig.put( + PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME + + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, + "" + Integer.toString(TELEMETRY_SERVER_DEFAULT_PORT)); + defaultConfig.put( + PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME + + PolicyEndPointProperties.PROPERTY_HTTP_REST_PACKAGES_SUFFIX, + RestManager.class.getPackage().getName()); + defaultConfig.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME + + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "" + Boolean.TRUE); + defaultConfig.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME + + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "" + Boolean.FALSE); + + return defaultConfig; } - return; - } + @Override + public synchronized void configure(Properties properties) { + + if (properties == null) { + logger.warn("No properties provided"); + throw new IllegalArgumentException("No properties provided"); + } + + /* policy-engine dispatch pre configure hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.beforeConfigure(this, properties)) { + return; + } + } catch (final Exception e) { + logger.error("{}: feature {} before-configure failure because of {}", this, + feature.getClass().getName(), e.getMessage(), e); + } + } - @Override - public synchronized PolicyController createPolicyController(String name, Properties properties) { + this.properties = properties; - String tempName = name; - // check if a PROPERTY_CONTROLLER_NAME property is present - // if so, override the given name + try { + this.sources = ProxyTopicEndpointManager.getInstance().addTopicSources(properties); + for (final TopicSource source : this.sources) { + source.register(this); + } + } catch (final Exception e) { + logger.error("{}: add-sources failed", this, e); + } - final String propertyControllerName = - properties.getProperty(PolicyProperties.PROPERTY_CONTROLLER_NAME); - if (propertyControllerName != null && !propertyControllerName.isEmpty()) { - if (!propertyControllerName.equals(tempName)) { - throw new IllegalStateException("Proposed name (" + tempName + ") and properties name (" - + propertyControllerName + ") don't match"); - } - tempName = propertyControllerName; - } + try { + this.sinks = ProxyTopicEndpointManager.getInstance().addTopicSinks(properties); + } catch (final IllegalArgumentException e) { + logger.error("{}: add-sinks failed", this, e); + } - PolicyController controller; - for (final PolicyControllerFeatureAPI controllerFeature : PolicyControllerFeatureAPI.providers - .getList()) { - try { - controller = controllerFeature.beforeCreate(tempName, properties); - if (controller != null) - return controller; - } catch (final Exception e) { - logger.error("{}: feature {} before-controller-create failure because of {}", this, - controllerFeature.getClass().getName(), e.getMessage(), e); - } - } + try { + this.httpServers = IndexedHttpServletServerFactory.getInstance().build(properties); + } catch (final IllegalArgumentException e) { + logger.error("{}: add-http-servers failed", this, e); + } - controller = PolicyController.factory.build(tempName, properties); - if (this.isLocked()) - controller.lock(); - - // feature hook - for (final PolicyControllerFeatureAPI controllerFeature : PolicyControllerFeatureAPI.providers - .getList()) { - try { - if (controllerFeature.afterCreate(controller)) - return controller; - } catch (final Exception e) { - logger.error("{}: feature {} after-controller-create failure because of {}", this, - controllerFeature.getClass().getName(), e.getMessage(), e); - } + /* policy-engine dispatch post configure hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.afterConfigure(this)) { + return; + } + } catch (final Exception e) { + logger.error("{}: feature {} after-configure failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + return; } - return controller; - } + @Override + public synchronized PolicyController createPolicyController(String name, Properties properties) { + String tempName = name; + // check if a PROPERTY_CONTROLLER_NAME property is present + // if so, override the given name - @Override - public boolean configure(PdpdConfiguration config) { + final String propertyControllerName = properties.getProperty(DroolsProperties.PROPERTY_CONTROLLER_NAME); + if (propertyControllerName != null && !propertyControllerName.isEmpty()) { + if (!propertyControllerName.equals(tempName)) { + throw new IllegalStateException("Proposed name (" + tempName + ") and properties name (" + + propertyControllerName + ") don't match"); + } + tempName = propertyControllerName; + } - if (config == null) - throw new IllegalArgumentException("No configuration provided"); + PolicyController controller; + for (final PolicyControllerFeatureAPI controllerFeature : PolicyControllerFeatureAPI.providers.getList()) { + try { + controller = controllerFeature.beforeCreate(tempName, properties); + if (controller != null) { + return controller; + } + } catch (final Exception e) { + logger.error("{}: feature {} before-controller-create failure because of {}", this, + controllerFeature.getClass().getName(), e.getMessage(), e); + } + } - final String entity = config.getEntity(); + controller = PolicyController.factory.build(tempName, properties); + if (this.isLocked()) { + controller.lock(); + } - MDCTransaction mdcTrans = MDCTransaction.newTransaction(config.getRequestID(), "brmsgw"); - if (this.getSources().size() == 1) { - Topic topic = this.getSources().get(0); - mdcTrans.setServiceName(topic.getTopic()).setRemoteHost(topic.getServers().toString()). - setTargetEntity(config.getEntity()); - } + // feature hook + for (final PolicyControllerFeatureAPI controllerFeature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (controllerFeature.afterCreate(controller)) { + return controller; + } + } catch (final Exception e) { + logger.error("{}: feature {} after-controller-create failure because of {}", this, + controllerFeature.getClass().getName(), e.getMessage(), e); + } + } - switch (entity) { - case PdpdConfiguration.CONFIG_ENTITY_CONTROLLER: - boolean success = controllerConfig(config); - mdcTrans.resetSubTransaction().setStatusCode(success).transaction(); - return success; - default: - final String msg = "Configuration Entity is not supported: " + entity; - mdcTrans.resetSubTransaction().setStatusCode(false).setResponseDescription(msg).flush(); - logger.warn(LoggerUtil.TRANSACTION_LOG_MARKER_NAME, msg); - throw new IllegalArgumentException(msg); + return controller; } - } - @Override - public List<PolicyController> updatePolicyControllers( - List<ControllerConfiguration> configControllers) { - final List<PolicyController> policyControllers = new ArrayList<>(); - if (configControllers == null || configControllers.isEmpty()) { - if (logger.isInfoEnabled()) - logger.info("No controller configuration provided: " + configControllers); - return policyControllers; + @Override + public boolean configure(PdpdConfiguration config) { + + if (config == null) { + throw new IllegalArgumentException("No configuration provided"); + } + + final String entity = config.getEntity(); + + MDCTransaction mdcTrans = MDCTransaction.newTransaction(config.getRequestID(), "brmsgw"); + if (this.getSources().size() == 1) { + Topic topic = this.getSources().get(0); + mdcTrans.setServiceName(topic.getTopic()).setRemoteHost(topic.getServers().toString()) + .setTargetEntity(config.getEntity()); + } + + switch (entity) { + case PdpdConfiguration.CONFIG_ENTITY_CONTROLLER: + boolean success = controllerConfig(config); + mdcTrans.resetSubTransaction().setStatusCode(success).transaction(); + return success; + default: + final String msg = "Configuration Entity is not supported: " + entity; + mdcTrans.resetSubTransaction().setStatusCode(false).setResponseDescription(msg).flush(); + logger.warn(LoggerUtil.TRANSACTION_LOG_MARKER_NAME, msg); + throw new IllegalArgumentException(msg); + } } - for (final ControllerConfiguration configController : configControllers) { - MDCTransaction mdcTrans = - MDCTransaction.newSubTransaction(null).setTargetEntity(configController.getName()). - setTargetServiceName(configController.getOperation()). - setTargetVirtualEntity(configController.getDrools().toString()); - try { - final PolicyController policyController = this.updatePolicyController(configController); - policyControllers.add(policyController); - mdcTrans.setStatusCode(true).transaction(); - } catch (final Exception e) { - mdcTrans.setStatusCode(false).setResponseCode(e.getClass().getName()). - setResponseDescription(e.getMessage()).flush(); - logger.error(LoggerUtil.TRANSACTION_LOG_MARKER_NAME, "{}: cannot update-policy-controllers because of {}", this, e.getMessage(), e); - } + @Override + public List<PolicyController> updatePolicyControllers(List<ControllerConfiguration> configControllers) { + + final List<PolicyController> policyControllers = new ArrayList<>(); + if (configControllers == null || configControllers.isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("No controller configuration provided: " + configControllers); + } + return policyControllers; + } + + for (final ControllerConfiguration configController : configControllers) { + MDCTransaction mdcTrans = MDCTransaction.newSubTransaction(null).setTargetEntity(configController.getName()) + .setTargetServiceName(configController.getOperation()) + .setTargetVirtualEntity(configController.getDrools().toString()); + try { + final PolicyController policyController = this.updatePolicyController(configController); + policyControllers.add(policyController); + mdcTrans.setStatusCode(true).transaction(); + } catch (final Exception e) { + mdcTrans.setStatusCode(false).setResponseCode(e.getClass().getName()) + .setResponseDescription(e.getMessage()).flush(); + logger.error(LoggerUtil.TRANSACTION_LOG_MARKER_NAME, + "{}: cannot update-policy-controllers because of {}", this, e.getMessage(), e); + } + } + + return policyControllers; } - return policyControllers; - } + @Override + public synchronized PolicyController updatePolicyController(ControllerConfiguration configController) { + + if (configController == null) { + throw new IllegalArgumentException("No controller configuration has been provided"); + } + + final String controllerName = configController.getName(); + if (controllerName == null || controllerName.isEmpty()) { + logger.warn("controller-name must be provided"); + throw new IllegalArgumentException("No controller configuration has been provided"); + } + + PolicyController policyController = null; + try { + final String operation = configController.getOperation(); + if (operation == null || operation.isEmpty()) { + logger.warn("operation must be provided"); + throw new IllegalArgumentException("operation must be provided"); + } + + try { + policyController = PolicyController.factory.get(controllerName); + } catch (final IllegalArgumentException e) { + // not found + logger.warn("Policy Controller " + controllerName + " not found", e); + } + + if (policyController == null) { + + if (operation.equalsIgnoreCase(ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_LOCK) + || operation.equalsIgnoreCase(ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UNLOCK)) { + throw new IllegalArgumentException(controllerName + " is not available for operation " + operation); + } + + /* Recovery case */ + + logger.warn("controller " + controllerName + " does not exist. " + "Attempting recovery from disk"); + + final Properties controllerProperties = + SystemPersistence.manager.getControllerProperties(controllerName); + + /* + * returned properties cannot be null (per implementation) assert (properties != + * null) + */ + + if (controllerProperties == null) { + throw new IllegalArgumentException(controllerName + " is invalid"); + } - @Override - public synchronized PolicyController updatePolicyController(ControllerConfiguration configController) { + logger.warn("controller " + controllerName + " being recovered. " + + "Reset controller's bad maven coordinates to brainless"); - if (configController == null) - throw new IllegalArgumentException("No controller configuration has been provided"); + /* + * try to bring up bad controller in brainless mode, after having it working, apply + * the new create/update operation. + */ + controllerProperties.setProperty(DroolsProperties.RULES_GROUPID, DroolsController.NO_GROUP_ID); + controllerProperties.setProperty(DroolsProperties.RULES_ARTIFACTID, DroolsController.NO_ARTIFACT_ID); + controllerProperties.setProperty(DroolsProperties.RULES_VERSION, DroolsController.NO_VERSION); - final String controllerName = configController.getName(); - if (controllerName == null || controllerName.isEmpty()) { - logger.warn("controller-name must be provided"); - throw new IllegalArgumentException("No controller configuration has been provided"); + policyController = PolicyEngine.manager.createPolicyController(controllerName, controllerProperties); + + /* fall through to do brain update operation */ + } + + switch (operation) { + case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_CREATE: + PolicyController.factory.patch(policyController, configController.getDrools()); + break; + case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UPDATE: + policyController.unlock(); + PolicyController.factory.patch(policyController, configController.getDrools()); + break; + case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_LOCK: + policyController.lock(); + break; + case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UNLOCK: + policyController.unlock(); + break; + default: + final String msg = "Controller Operation Configuration is not supported: " + operation + " for " + + controllerName; + logger.warn(msg); + throw new IllegalArgumentException(msg); + } + + return policyController; + } catch (final Exception e) { + logger.error("{}: cannot update-policy-controller because of {}", this, e.getMessage(), e); + throw e; + } catch (final LinkageError e) { + logger.error("{}: cannot update-policy-controllers (rules) because of {}", this, e.getMessage(), e); + throw new IllegalStateException(e); + } } - PolicyController policyController = null; - try { - final String operation = configController.getOperation(); - if (operation == null || operation.isEmpty()) { - logger.warn("operation must be provided"); - throw new IllegalArgumentException("operation must be provided"); - } + @Override + public synchronized boolean start() { + + /* policy-engine dispatch pre start hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.beforeStart(this)) { + return true; + } + } catch (final Exception e) { + logger.error("{}: feature {} before-start failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + boolean success = true; + if (this.locked) { + throw new IllegalStateException(ENGINE_LOCKED_MSG); + } - try { - policyController = PolicyController.factory.get(controllerName); - } catch (final IllegalArgumentException e) { - // not found - logger.warn("Policy Controller " + controllerName + " not found", e); - } + this.alive = true; - if (policyController == null) { + /* Start Policy Engine exclusively-owned (unmanaged) http servers */ - if (operation.equalsIgnoreCase(ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_LOCK) - || operation - .equalsIgnoreCase(ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UNLOCK)) { - throw new IllegalArgumentException( - controllerName + " is not available for operation " + operation); + for (final HttpServletServer httpServer : this.httpServers) { + try { + if (!httpServer.waitedStart(10 * 1000L)) { + success = false; + } + } catch (final Exception e) { + logger.error("{}: cannot start http-server {} because of {}", this, httpServer, e.getMessage(), e); + } } - /* Recovery case */ + /* Start Policy Engine exclusively-owned (unmanaged) sources */ - logger.warn("controller " + controllerName + " does not exist. " - + "Attempting recovery from disk"); + for (final TopicSource source : this.sources) { + try { + if (!source.start()) { + success = false; + } + } catch (final Exception e) { + logger.error("{}: cannot start topic-source {} because of {}", this, source, e.getMessage(), e); + } + } - final Properties controllerProperties = - SystemPersistence.manager.getControllerProperties(controllerName); + /* Start Policy Engine owned (unmanaged) sinks */ - /* - * returned properties cannot be null (per implementation) assert (properties != null) - */ + for (final TopicSink sink : this.sinks) { + try { + if (!sink.start()) { + success = false; + } + } catch (final Exception e) { + logger.error("{}: cannot start topic-sink {} because of {}", this, sink, e.getMessage(), e); + } + } - if (controllerProperties == null) { - throw new IllegalArgumentException(controllerName + " is invalid"); + /* Start Policy Controllers */ + + final List<PolicyController> controllers = PolicyController.factory.inventory(); + for (final PolicyController controller : controllers) { + try { + if (!controller.start()) { + success = false; + } + } catch (final Exception e) { + logger.error("{}: cannot start policy-controller {} because of {}", this, controller, e.getMessage(), + e); + success = false; + } } - logger.warn("controller " + controllerName + " being recovered. " - + "Reset controller's bad maven coordinates to brainless"); + /* Start managed Topic Endpoints */ - /* - * try to bring up bad controller in brainless mode, after having it working, apply the new - * create/update operation. - */ - controllerProperties.setProperty(PolicyProperties.RULES_GROUPID, DroolsController.NO_GROUP_ID); - controllerProperties.setProperty(PolicyProperties.RULES_ARTIFACTID, DroolsController.NO_ARTIFACT_ID); - controllerProperties.setProperty(PolicyProperties.RULES_VERSION, DroolsController.NO_VERSION); - - policyController = PolicyEngine.manager.createPolicyController(controllerName, controllerProperties); - - /* fall through to do brain update operation */ - } - - switch (operation) { - case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_CREATE: - PolicyController.factory.patch(policyController, configController.getDrools()); - break; - case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UPDATE: - policyController.unlock(); - PolicyController.factory.patch(policyController, configController.getDrools()); - break; - case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_LOCK: - policyController.lock(); - break; - case ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UNLOCK: - policyController.unlock(); - break; - default: - final String msg = "Controller Operation Configuration is not supported: " + operation - + " for " + controllerName; - logger.warn(msg); - throw new IllegalArgumentException(msg); - } - - return policyController; - } catch (final Exception e) { - logger.error("{}: cannot update-policy-controller because of {}", this, e.getMessage(), e); - throw e; - } catch (final LinkageError e) { - logger.error("{}: cannot update-policy-controllers (rules) because of {}", this, - e.getMessage(), e); - throw new IllegalStateException(e); - } - } - - @Override - public synchronized boolean start() { - - /* policy-engine dispatch pre start hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.beforeStart(this)) - return true; - } catch (final Exception e) { - logger.error("{}: feature {} before-start failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } - } + try { + if (!ProxyTopicEndpointManager.getInstance().start()) { + success = false; + } + } catch (final IllegalStateException e) { + logger.warn("{}: Topic Endpoint Manager is in an invalid state because of {}", this, e.getMessage(), e); + } - boolean success = true; - if (this.locked) - throw new IllegalStateException(ENGINE_LOCKED_MSG); - this.alive = true; + // Start the JMX listener - /* Start Policy Engine exclusively-owned (unmanaged) http servers */ + PdpJmxListener.start(); - for (final HttpServletServer httpServer : this.httpServers) { - try { - if (!httpServer.waitedStart(10 * 1000L)) - success = false; - } catch (final Exception e) { - logger.error("{}: cannot start http-server {} because of {}", this, httpServer, - e.getMessage(), e); - } + /* policy-engine dispatch after start hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.afterStart(this)) { + return success; + } + } catch (final Exception e) { + logger.error("{}: feature {} after-start failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + return success; } - /* Start Policy Engine exclusively-owned (unmanaged) sources */ + @Override + public synchronized boolean stop() { - for (final TopicSource source : this.sources) { - try { - if (!source.start()) - success = false; - } catch (final Exception e) { - logger.error("{}: cannot start topic-source {} because of {}", this, source, e.getMessage(), - e); - } - } + /* policy-engine dispatch pre stop hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.beforeStop(this)) { + return true; + } + } catch (final Exception e) { + logger.error("{}: feature {} before-stop failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } - /* Start Policy Engine owned (unmanaged) sinks */ + /* stop regardless of the lock state */ - for (final TopicSink sink : this.sinks) { - try { - if (!sink.start()) - success = false; - } catch (final Exception e) { - logger.error("{}: cannot start topic-sink {} because of {}", this, sink, e.getMessage(), e); - } - } + boolean success = true; + if (!this.alive) { + return true; + } - /* Start Policy Controllers */ - - final List<PolicyController> controllers = PolicyController.factory.inventory(); - for (final PolicyController controller : controllers) { - try { - if (!controller.start()) - success = false; - } catch (final Exception e) { - logger.error("{}: cannot start policy-controller {} because of {}", this, controller, - e.getMessage(), e); - success = false; - } - } + this.alive = false; - /* Start managed Topic Endpoints */ + final List<PolicyController> controllers = PolicyController.factory.inventory(); + for (final PolicyController controller : controllers) { + try { + if (!controller.stop()) { + success = false; + } + } catch (final Exception e) { + logger.error("{}: cannot stop policy-controller {} because of {}", this, controller, e.getMessage(), e); + success = false; + } + } - try { - if (!TopicEndpoint.manager.start()) - success = false; - } catch (final IllegalStateException e) { - logger.warn("{}: Topic Endpoint Manager is in an invalid state because of {}", this, - e.getMessage(), e); - } + /* Stop Policy Engine owned (unmanaged) sources */ + for (final TopicSource source : this.sources) { + try { + if (!source.stop()) { + success = false; + } + } catch (final Exception e) { + logger.error("{}: cannot start topic-source {} because of {}", this, source, e.getMessage(), e); + } + } + /* Stop Policy Engine owned (unmanaged) sinks */ + for (final TopicSink sink : this.sinks) { + try { + if (!sink.stop()) { + success = false; + } + } catch (final Exception e) { + logger.error("{}: cannot start topic-sink {} because of {}", this, sink, e.getMessage(), e); + } + } - // Start the JMX listener + /* stop all managed topics sources and sinks */ + if (!ProxyTopicEndpointManager.getInstance().stop()) { + success = false; + } - PdpJmxListener.start(); + /* stop all unmanaged http servers */ + for (final HttpServletServer httpServer : this.httpServers) { + try { + if (!httpServer.stop()) { + success = false; + } + } catch (final Exception e) { + logger.error("{}: cannot start http-server {} because of {}", this, httpServer, e.getMessage(), e); + } + } - /* policy-engine dispatch after start hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.afterStart(this)) - return success; - } catch (final Exception e) { - logger.error("{}: feature {} after-start failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } - } + /* policy-engine dispatch pre stop hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.afterStop(this)) { + return success; + } + } catch (final Exception e) { + logger.error("{}: feature {} after-stop failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } - return success; - } - - @Override - public synchronized boolean stop() { - - /* policy-engine dispatch pre stop hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.beforeStop(this)) - return true; - } catch (final Exception e) { - logger.error("{}: feature {} before-stop failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + return success; } - /* stop regardless of the lock state */ + @Override + public synchronized void shutdown() { - boolean success = true; - if (!this.alive) - return true; + /* + * shutdown activity even when underlying subcomponents (features, controllers, topics, etc + * ..) are stuck + */ - this.alive = false; + Thread exitThread = new Thread(new Runnable() { + private static final long SHUTDOWN_MAX_GRACE_TIME = 30000L; + + @Override + public void run() { + try { + Thread.sleep(SHUTDOWN_MAX_GRACE_TIME); + logger.warn("{}: abnormal termination - shutdown graceful time period expiration", + PolicyEngineManager.this); + } catch (final InterruptedException e) { + /* courtesy to shutdown() to allow it to return */ + synchronized (PolicyEngineManager.this) { + } + logger.info("{}: finishing a graceful shutdown ", PolicyEngineManager.this, e); + } finally { + /* + * shut down the Policy Engine owned http servers as the very last thing + */ + for (final HttpServletServer httpServer : PolicyEngineManager.this.getHttpServers()) { + try { + httpServer.shutdown(); + } catch (final Exception e) { + logger.error("{}: cannot shutdown http-server {} because of {}", PolicyEngineManager.this, + httpServer, e.getMessage(), e); + } + } + + logger.info("{}: exit", PolicyEngineManager.this); + System.exit(0); + } + } + }); + exitThread.start(); - final List<PolicyController> controllers = PolicyController.factory.inventory(); - for (final PolicyController controller : controllers) { - try { - if (!controller.stop()) - success = false; - } catch (final Exception e) { - logger.error("{}: cannot stop policy-controller {} because of {}", this, controller, - e.getMessage(), e); - success = false; - } - } + /* policy-engine dispatch pre shutdown hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.beforeShutdown(this)) { + return; + } + } catch (final Exception e) { + logger.error("{}: feature {} before-shutdown failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } - /* Stop Policy Engine owned (unmanaged) sources */ - for (final TopicSource source : this.sources) { - try { - if (!source.stop()) - success = false; - } catch (final Exception e) { - logger.error("{}: cannot start topic-source {} because of {}", this, source, e.getMessage(), - e); - } - } + this.alive = false; - /* Stop Policy Engine owned (unmanaged) sinks */ - for (final TopicSink sink : this.sinks) { - try { - if (!sink.stop()) - success = false; - } catch (final Exception e) { - logger.error("{}: cannot start topic-sink {} because of {}", this, sink, e.getMessage(), e); - } - } + /* Shutdown Policy Engine owned (unmanaged) sources */ + for (final TopicSource source : this.sources) { + try { + source.shutdown(); + } catch (final Exception e) { + logger.error("{}: cannot shutdown topic-source {} because of {}", this, source, e.getMessage(), e); + } + } - /* stop all managed topics sources and sinks */ - if (!TopicEndpoint.manager.stop()) - success = false; - - /* stop all unmanaged http servers */ - for (final HttpServletServer httpServer : this.httpServers) { - try { - if (!httpServer.stop()) - success = false; - } catch (final Exception e) { - logger.error("{}: cannot start http-server {} because of {}", this, httpServer, - e.getMessage(), e); - } + /* Shutdown Policy Engine owned (unmanaged) sinks */ + for (final TopicSink sink : this.sinks) { + try { + sink.shutdown(); + } catch (final Exception e) { + logger.error("{}: cannot shutdown topic-sink {} because of {}", this, sink, e.getMessage(), e); + } + } + + /* Shutdown managed resources */ + PolicyController.factory.shutdown(); + ProxyTopicEndpointManager.getInstance().shutdown(); + IndexedHttpServletServerFactory.getInstance().destroy(); + + // Stop the JMX listener + + PdpJmxListener.stop(); + + /* policy-engine dispatch post shutdown hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.afterShutdown(this)) { + return; + } + } catch (final Exception e) { + logger.error("{}: feature {} after-shutdown failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + exitThread.interrupt(); + logger.info("{}: normal termination", this); } - /* policy-engine dispatch pre stop hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.afterStop(this)) - return success; - } catch (final Exception e) { - logger.error("{}: feature {} after-stop failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + @Override + public boolean isAlive() { + return this.alive; } - return success; - } + @Override + public synchronized boolean lock() { - @Override - public synchronized void shutdown() { - - /* - * shutdown activity even when underlying subcomponents - * (features, controllers, topics, etc ..) are stuck - */ - - Thread exitThread = new Thread(new Runnable() { - private static final long SHUTDOWN_MAX_GRACE_TIME = 30000L; - - @Override - public void run() { - try { - Thread.sleep(SHUTDOWN_MAX_GRACE_TIME); - logger.warn("{}: abnormal termination - shutdown graceful time period expiration", - PolicyEngineManager.this); - } catch (final InterruptedException e) { - /* courtesy to shutdown() to allow it to return */ - synchronized(PolicyEngineManager.this) {} - logger.info("{}: finishing a graceful shutdown ", - PolicyEngineManager.this, e); - } finally { - /* - * shut down the Policy Engine owned http servers as the very last thing - */ - for (final HttpServletServer httpServer : PolicyEngineManager.this.getHttpServers()) { + /* policy-engine dispatch pre lock hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { try { - httpServer.shutdown(); + if (feature.beforeLock(this)) { + return true; + } } catch (final Exception e) { - logger.error("{}: cannot shutdown http-server {} because of {}", - PolicyEngineManager.this, httpServer, e.getMessage(), e); + logger.error("{}: feature {} before-lock failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); } - } - - logger.info("{}: exit" , PolicyEngineManager.this); - System.exit(0); - } - } - }); - exitThread.start(); - - /* policy-engine dispatch pre shutdown hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.beforeShutdown(this)) - return; - } catch (final Exception e) { - logger.error("{}: feature {} before-shutdown failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } - } + } - this.alive = false; + if (this.locked) { + return true; + } - /* Shutdown Policy Engine owned (unmanaged) sources */ - for (final TopicSource source : this.sources) { - try { - source.shutdown(); - } catch (final Exception e) { - logger.error("{}: cannot shutdown topic-source {} because of {}", this, source, - e.getMessage(), e); - } - } + this.locked = true; - /* Shutdown Policy Engine owned (unmanaged) sinks */ - for (final TopicSink sink : this.sinks) { - try { - sink.shutdown(); - } catch (final Exception e) { - logger.error("{}: cannot shutdown topic-sink {} because of {}", this, sink, e.getMessage(), - e); - } + boolean success = true; + final List<PolicyController> controllers = PolicyController.factory.inventory(); + for (final PolicyController controller : controllers) { + try { + success = controller.lock() && success; + } catch (final Exception e) { + logger.error("{}: cannot lock policy-controller {} because of {}", this, controller, e.getMessage(), e); + success = false; + } + } + + success = ProxyTopicEndpointManager.getInstance().lock() && success; + + /* policy-engine dispatch post lock hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.afterLock(this)) { + return success; + } + } catch (final Exception e) { + logger.error("{}: feature {} after-lock failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + return success; } - /* Shutdown managed resources */ - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - HttpServletServer.factory.destroy(); + @Override + public synchronized boolean unlock() { - // Stop the JMX listener + /* policy-engine dispatch pre unlock hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.beforeUnlock(this)) { + return true; + } + } catch (final Exception e) { + logger.error("{}: feature {} before-unlock failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + if (!this.locked) { + return true; + } - PdpJmxListener.stop(); + this.locked = false; - /* policy-engine dispatch post shutdown hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.afterShutdown(this)) - return; - } catch (final Exception e) { - logger.error("{}: feature {} after-shutdown failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } - } - - exitThread.interrupt(); - logger.info("{}: normal termination" , this); - } - - @Override - public boolean isAlive() { - return this.alive; - } - - @Override - public synchronized boolean lock() { - - /* policy-engine dispatch pre lock hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.beforeLock(this)) - return true; - } catch (final Exception e) { - logger.error("{}: feature {} before-lock failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + boolean success = true; + final List<PolicyController> controllers = PolicyController.factory.inventory(); + for (final PolicyController controller : controllers) { + try { + success = controller.unlock() && success; + } catch (final Exception e) { + logger.error("{}: cannot unlock policy-controller {} because of {}", this, controller, e.getMessage(), + e); + success = false; + } + } + + success = ProxyTopicEndpointManager.getInstance().unlock() && success; + + /* policy-engine dispatch after unlock hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.afterUnlock(this)) { + return success; + } + } catch (final Exception e) { + logger.error("{}: feature {} after-unlock failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + return success; } - if (this.locked) - return true; - - this.locked = true; - - boolean success = true; - final List<PolicyController> controllers = PolicyController.factory.inventory(); - for (final PolicyController controller : controllers) { - try { - success = controller.lock() && success; - } catch (final Exception e) { - logger.error("{}: cannot lock policy-controller {} because of {}", this, controller, - e.getMessage(), e); - success = false; - } + @Override + public boolean isLocked() { + return this.locked; } - success = TopicEndpoint.manager.lock() && success; - - /* policy-engine dispatch post lock hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.afterLock(this)) - return success; - } catch (final Exception e) { - logger.error("{}: feature {} after-lock failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + @Override + public void removePolicyController(String name) { + PolicyController.factory.destroy(name); } - return success; - } - - @Override - public synchronized boolean unlock() { - - /* policy-engine dispatch pre unlock hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.beforeUnlock(this)) - return true; - } catch (final Exception e) { - logger.error("{}: feature {} before-unlock failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + @Override + public void removePolicyController(PolicyController controller) { + PolicyController.factory.destroy(controller); } - if (!this.locked) - return true; - - this.locked = false; - - boolean success = true; - final List<PolicyController> controllers = PolicyController.factory.inventory(); - for (final PolicyController controller : controllers) { - try { - success = controller.unlock() && success; - } catch (final Exception e) { - logger.error("{}: cannot unlock policy-controller {} because of {}", this, controller, - e.getMessage(), e); - success = false; - } + @JsonIgnore + @Override + public List<PolicyController> getPolicyControllers() { + return PolicyController.factory.inventory(); } - success = TopicEndpoint.manager.unlock() && success; - - /* policy-engine dispatch after unlock hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.afterUnlock(this)) - return success; - } catch (final Exception e) { - logger.error("{}: feature {} after-unlock failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + @JsonProperty("controllers") + @Override + public List<String> getPolicyControllerIds() { + final List<String> controllerNames = new ArrayList<>(); + for (final PolicyController controller : PolicyController.factory.inventory()) { + controllerNames.add(controller.getName()); + } + return controllerNames; } - return success; - } - - @Override - public boolean isLocked() { - return this.locked; - } - - @Override - public void removePolicyController(String name) { - PolicyController.factory.destroy(name); - } - - @Override - public void removePolicyController(PolicyController controller) { - PolicyController.factory.destroy(controller); - } - - @JsonIgnore - @Override - public List<PolicyController> getPolicyControllers() { - return PolicyController.factory.inventory(); - } - - @JsonProperty("controllers") - @Override - public List<String> getPolicyControllerIds() { - final List<String> controllerNames = new ArrayList<>(); - for (final PolicyController controller : PolicyController.factory.inventory()) { - controllerNames.add(controller.getName()); + @Override + @JsonIgnore + public Properties getProperties() { + return this.properties; } - return controllerNames; - } - - @Override - @JsonIgnore - public Properties getProperties() { - return this.properties; - } - - - @SuppressWarnings("unchecked") - @Override - public List<TopicSource> getSources() { - return (List<TopicSource>) this.sources; - } - - @SuppressWarnings("unchecked") - @Override - public List<TopicSink> getSinks() { - return (List<TopicSink>) this.sinks; - } - - @Override - public List<HttpServletServer> getHttpServers() { - return this.httpServers; - } - - @Override - public List<String> getFeatures() { - final List<String> features = new ArrayList<>(); - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - features.add(feature.getName()); + + + @SuppressWarnings("unchecked") + @Override + public List<TopicSource> getSources() { + return (List<TopicSource>) this.sources; } - return features; - } - - @JsonIgnore - @Override - public List<PolicyEngineFeatureAPI> getFeatureProviders() { - return PolicyEngineFeatureAPI.providers.getList(); - } - - @Override - public PolicyEngineFeatureAPI getFeatureProvider(String featureName) { - if (featureName == null || featureName.isEmpty()) - throw new IllegalArgumentException("A feature name must be provided"); - - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - if (feature.getName().equals(featureName)) - return feature; + + @SuppressWarnings("unchecked") + @Override + public List<TopicSink> getSinks() { + return (List<TopicSink>) this.sinks; } - throw new IllegalArgumentException("Invalid Feature Name: " + featureName); - } - - @Override - public void onTopicEvent(CommInfrastructure commType, String topic, String event) { - /* configuration request */ - try { - final PdpdConfiguration configuration = this.decoder.fromJson(event, PdpdConfiguration.class); - this.configure(configuration); - } catch (final Exception e) { - logger.error("{}: configuration-error due to {} because of {}", this, event, e.getMessage(), - e); + @Override + public List<HttpServletServer> getHttpServers() { + return this.httpServers; } - } - @Override - public boolean deliver(String topic, Object event) { + @Override + public List<String> getFeatures() { + final List<String> features = new ArrayList<>(); + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + features.add(feature.getName()); + } + return features; + } - /* - * Note this entry point is usually from the DRL - */ + @JsonIgnore + @Override + public List<PolicyEngineFeatureAPI> getFeatureProviders() { + return PolicyEngineFeatureAPI.providers.getList(); + } - if (topic == null || topic.isEmpty()) - throw new IllegalArgumentException(INVALID_TOPIC_MSG); + @Override + public PolicyEngineFeatureAPI getFeatureProvider(String featureName) { + if (featureName == null || featureName.isEmpty()) { + throw new IllegalArgumentException("A feature name must be provided"); + } - if (event == null) - throw new IllegalArgumentException(INVALID_EVENT_MSG); + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + if (feature.getName().equals(featureName)) { + return feature; + } + } - if (!this.isAlive()) - throw new IllegalStateException(ENGINE_STOPPED_MSG); + throw new IllegalArgumentException("Invalid Feature Name: " + featureName); + } - if (this.isLocked()) - throw new IllegalStateException(ENGINE_LOCKED_MSG); + @Override + public void onTopicEvent(CommInfrastructure commType, String topic, String event) { + /* configuration request */ + try { + final PdpdConfiguration configuration = this.decoder.fromJson(event, PdpdConfiguration.class); + this.configure(configuration); + } catch (final Exception e) { + logger.error("{}: configuration-error due to {} because of {}", this, event, e.getMessage(), e); + } + } - final List<? extends TopicSink> topicSinks = TopicEndpoint.manager.getTopicSinks(topic); - if (topicSinks == null || topicSinks.isEmpty() || topicSinks.size() > 1) - throw new IllegalStateException( - "Cannot ensure correct delivery on topic " + topic + ": " + topicSinks); + @Override + public boolean deliver(String topic, Object event) { - return this.deliver(topicSinks.get(0).getTopicCommInfrastructure(), topic, event); - } + /* + * Note this entry point is usually from the DRL + */ - @Override - public boolean deliver(String busType, String topic, Object event) { + if (topic == null || topic.isEmpty()) { + throw new IllegalArgumentException(INVALID_TOPIC_MSG); + } - /* - * Note this entry point is usually from the DRL (one of the reasons busType is String. - */ + if (event == null) { + throw new IllegalArgumentException(INVALID_EVENT_MSG); + } - if (busType == null || busType.isEmpty()) - throw new IllegalArgumentException("Invalid Communication Infrastructure"); + if (!this.isAlive()) { + throw new IllegalStateException(ENGINE_STOPPED_MSG); + } - if (topic == null || topic.isEmpty()) - throw new IllegalArgumentException(INVALID_TOPIC_MSG); + if (this.isLocked()) { + throw new IllegalStateException(ENGINE_LOCKED_MSG); + } - if (event == null) - throw new IllegalArgumentException(INVALID_EVENT_MSG); + final List<? extends TopicSink> topicSinks = ProxyTopicEndpointManager.getInstance().getTopicSinks(topic); + if (topicSinks == null || topicSinks.isEmpty() || topicSinks.size() > 1) { + throw new IllegalStateException("Cannot ensure correct delivery on topic " + topic + ": " + topicSinks); + } - boolean valid = false; - for (final Topic.CommInfrastructure comm : Topic.CommInfrastructure.values()) { - if (comm.name().equals(busType)) { - valid = true; - } + return this.deliver(topicSinks.get(0).getTopicCommInfrastructure(), topic, event); } - if (!valid) - throw new IllegalArgumentException("Invalid Communication Infrastructure: " + busType); + @Override + public boolean deliver(String busType, String topic, Object event) { + /* + * Note this entry point is usually from the DRL (one of the reasons busType is String. + */ - if (!this.isAlive()) - throw new IllegalStateException(ENGINE_STOPPED_MSG); + if (busType == null || busType.isEmpty()) { + throw new IllegalArgumentException("Invalid Communication Infrastructure"); + } - if (this.isLocked()) - throw new IllegalStateException(ENGINE_LOCKED_MSG); + if (topic == null || topic.isEmpty()) { + throw new IllegalArgumentException(INVALID_TOPIC_MSG); + } + if (event == null) { + throw new IllegalArgumentException(INVALID_EVENT_MSG); + } - return this.deliver(Topic.CommInfrastructure.valueOf(busType), topic, event); - } + boolean valid = false; + for (final Topic.CommInfrastructure comm : Topic.CommInfrastructure.values()) { + if (comm.name().equals(busType)) { + valid = true; + } + } - @Override - public boolean deliver(Topic.CommInfrastructure busType, String topic, Object event) { + if (!valid) { + throw new IllegalArgumentException("Invalid Communication Infrastructure: " + busType); + } - if (topic == null || topic.isEmpty()) - throw new IllegalArgumentException(INVALID_TOPIC_MSG); - if (event == null) - throw new IllegalArgumentException(INVALID_EVENT_MSG); + if (!this.isAlive()) { + throw new IllegalStateException(ENGINE_STOPPED_MSG); + } - if (!this.isAlive()) - throw new IllegalStateException(ENGINE_STOPPED_MSG); + if (this.isLocked()) { + throw new IllegalStateException(ENGINE_LOCKED_MSG); + } - if (this.isLocked()) - throw new IllegalStateException(ENGINE_LOCKED_MSG); - /* - * Try to send through the controller, this is the preferred way, since it may want to apply - * additional processing - */ - try { - final DroolsController droolsController = - EventProtocolCoder.manager.getDroolsController(topic, event); - final PolicyController controller = PolicyController.factory.get(droolsController); - if (controller != null) - return controller.deliver(busType, topic, event); - } catch (final Exception e) { - logger.warn("{}: cannot find policy-controller to deliver {} over {}:{} because of {}", this, - event, busType, topic, e.getMessage(), e); - - /* continue (try without routing through the controller) */ + return this.deliver(Topic.CommInfrastructure.valueOf(busType), topic, event); } - /* - * cannot route through the controller, send directly through the topic sink - */ - try { - final String json = EventProtocolCoder.manager.encode(topic, event); - return this.deliver(busType, topic, json); - - } catch (final Exception e) { - logger.warn("{}: cannot deliver {} over {}:{} because of {}", this, event, busType, topic, - e.getMessage(), e); - throw e; + @Override + public boolean deliver(Topic.CommInfrastructure busType, String topic, Object event) { + + if (topic == null || topic.isEmpty()) { + throw new IllegalArgumentException(INVALID_TOPIC_MSG); + } + + if (event == null) { + throw new IllegalArgumentException(INVALID_EVENT_MSG); + } + + if (!this.isAlive()) { + throw new IllegalStateException(ENGINE_STOPPED_MSG); + } + + if (this.isLocked()) { + throw new IllegalStateException(ENGINE_LOCKED_MSG); + } + + /* + * Try to send through the controller, this is the preferred way, since it may want to apply + * additional processing + */ + try { + final DroolsController droolsController = EventProtocolCoder.manager.getDroolsController(topic, event); + final PolicyController controller = PolicyController.factory.get(droolsController); + if (controller != null) { + return controller.deliver(busType, topic, event); + } + } catch (final Exception e) { + logger.warn("{}: cannot find policy-controller to deliver {} over {}:{} because of {}", this, event, + busType, topic, e.getMessage(), e); + + /* continue (try without routing through the controller) */ + } + + /* + * cannot route through the controller, send directly through the topic sink + */ + try { + final String json = EventProtocolCoder.manager.encode(topic, event); + return this.deliver(busType, topic, json); + + } catch (final Exception e) { + logger.warn("{}: cannot deliver {} over {}:{} because of {}", this, event, busType, topic, e.getMessage(), + e); + throw e; + } } - } - @Override - public boolean deliver(Topic.CommInfrastructure busType, String topic, String event) { + @Override + public boolean deliver(Topic.CommInfrastructure busType, String topic, String event) { - if (topic == null || topic.isEmpty()) - throw new IllegalArgumentException(INVALID_TOPIC_MSG); + if (topic == null || topic.isEmpty()) { + throw new IllegalArgumentException(INVALID_TOPIC_MSG); + } - if (event == null || event.isEmpty()) - throw new IllegalArgumentException(INVALID_EVENT_MSG); + if (event == null || event.isEmpty()) { + throw new IllegalArgumentException(INVALID_EVENT_MSG); + } - if (!this.isAlive()) - throw new IllegalStateException(ENGINE_STOPPED_MSG); + if (!this.isAlive()) { + throw new IllegalStateException(ENGINE_STOPPED_MSG); + } - if (this.isLocked()) - throw new IllegalStateException(ENGINE_LOCKED_MSG); + if (this.isLocked()) { + throw new IllegalStateException(ENGINE_LOCKED_MSG); + } - try { - final TopicSink sink = TopicEndpoint.manager.getTopicSink(busType, topic); + try { + final TopicSink sink = ProxyTopicEndpointManager.getInstance().getTopicSink(busType, topic); - if (sink == null) - throw new IllegalStateException("Inconsistent State: " + this); + if (sink == null) { + throw new IllegalStateException("Inconsistent State: " + this); + } - return sink.send(event); + return sink.send(event); - } catch (final Exception e) { - logger.warn("{}: cannot deliver {} over {}:{} because of {}", this, event, busType, topic, - e.getMessage(), e); - throw e; - } - } - - @Override - public synchronized void activate() { - - /* policy-engine dispatch pre activate hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.beforeActivate(this)) - return; - } catch (final Exception e) { - logger.error("{}: feature {} before-activate failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + } catch (final Exception e) { + logger.warn("{}: cannot deliver {} over {}:{} because of {}", this, event, busType, topic, e.getMessage(), + e); + throw e; + } } - // activate 'policy-management' - for (final PolicyController policyController : this.getPolicyControllers()) { - try { - policyController.unlock(); - policyController.start(); - } catch (final Exception e) { - logger.error("{}: cannot activate of policy-controller {} because of {}", this, - policyController, e.getMessage(), e); - } catch (final LinkageError e) { - logger.error( - "{}: cannot activate (rules compilation) of policy-controller {} because of {}", this, - policyController, e.getMessage(), e); - } - } + @Override + public synchronized void activate() { - this.unlock(); - - /* policy-engine dispatch post activate hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.afterActivate(this)) - return; - } catch (final Exception e) { - logger.error("{}: feature {} after-activate failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + /* policy-engine dispatch pre activate hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.beforeActivate(this)) { + return; + } + } catch (final Exception e) { + logger.error("{}: feature {} before-activate failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + // activate 'policy-management' + for (final PolicyController policyController : this.getPolicyControllers()) { + try { + policyController.unlock(); + policyController.start(); + } catch (final Exception e) { + logger.error("{}: cannot activate of policy-controller {} because of {}", this, policyController, + e.getMessage(), e); + } catch (final LinkageError e) { + logger.error("{}: cannot activate (rules compilation) of policy-controller {} because of {}", this, + policyController, e.getMessage(), e); + } + } + + this.unlock(); + + /* policy-engine dispatch post activate hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.afterActivate(this)) { + return; + } + } catch (final Exception e) { + logger.error("{}: feature {} after-activate failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } } - } - - @Override - public synchronized void deactivate() { - - /* policy-engine dispatch pre deactivate hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.beforeDeactivate(this)) - return; - } catch (final Exception e) { - logger.error("{}: feature {} before-deactivate failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + + @Override + public synchronized void deactivate() { + + /* policy-engine dispatch pre deactivate hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.beforeDeactivate(this)) { + return; + } + } catch (final Exception e) { + logger.error("{}: feature {} before-deactivate failure because of {}", this, + feature.getClass().getName(), e.getMessage(), e); + } + } + + this.lock(); + + for (final PolicyController policyController : this.getPolicyControllers()) { + try { + policyController.stop(); + } catch (final Exception | LinkageError e) { + logger.error("{}: cannot deactivate (stop) policy-controller {} because of {}", this, policyController, + e.getMessage(), e); + } + } + + /* policy-engine dispatch post deactivate hook */ + for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { + try { + if (feature.afterDeactivate(this)) { + return; + } + } catch (final Exception e) { + logger.error("{}: feature {} after-deactivate failure because of {}", this, + feature.getClass().getName(), e.getMessage(), e); + } + } } - this.lock(); + public boolean controllerConfig(PdpdConfiguration config) { + /* only this one supported for now */ + final List<ControllerConfiguration> configControllers = config.getControllers(); + if (configControllers == null || configControllers.isEmpty()) { + logger.info("No controller configuration provided: {}" + config); + return false; + } + + final List<PolicyController> policyControllers = this.updatePolicyControllers(config.getControllers()); + + boolean success; - for (final PolicyController policyController : this.getPolicyControllers()) { - try { - policyController.stop(); - } catch (final Exception | LinkageError e) { - logger.error("{}: cannot deactivate (stop) policy-controller {} because of {}", this, - policyController, e.getMessage(), e); - } + if (policyControllers == null || policyControllers.isEmpty()) { + success = false; + } else if (policyControllers.size() == configControllers.size()) { + success = true; + } else { + success = false; + } + + return success; } - /* policy-engine dispatch post deactivate hook */ - for (final PolicyEngineFeatureAPI feature : PolicyEngineFeatureAPI.providers.getList()) { - try { - if (feature.afterDeactivate(this)) - return; - } catch (final Exception e) { - logger.error("{}: feature {} after-deactivate failure because of {}", this, - feature.getClass().getName(), e.getMessage(), e); - } + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("PolicyEngineManager [alive=").append(this.alive).append(", locked=").append(this.locked) + .append("]"); + return builder.toString(); } - } - - public boolean controllerConfig(PdpdConfiguration config) { - /* only this one supported for now */ - final List<ControllerConfiguration> configControllers = config.getControllers(); - if (configControllers == null || configControllers.isEmpty()) { - logger.info("No controller configuration provided: {}" + config); - return false; - } - - final List<PolicyController> policyControllers = this.updatePolicyControllers(config.getControllers()); - - boolean success; - - if (policyControllers == null || policyControllers.isEmpty()) { - success = false; - } else if (policyControllers.size() == configControllers.size()) { - success = true; - } else { - success = false; - } - - return success; - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("PolicyEngineManager [alive=").append(this.alive).append(", locked=") - .append(this.locked).append("]"); - return builder.toString(); - } } diff --git a/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java b/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java index ea631fae..41408258 100644 --- a/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java +++ b/policy-management/src/main/java/org/onap/policy/drools/system/internal/AggregatedPolicyController.java @@ -20,604 +20,624 @@ package org.onap.policy.drools.system.internal; +import com.fasterxml.jackson.annotation.JsonIgnore; + import java.util.HashMap; import java.util.List; import java.util.Properties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.onap.policy.common.endpoints.event.comm.Topic; +import org.onap.policy.common.endpoints.event.comm.TopicListener; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; +import org.onap.policy.common.endpoints.event.comm.impl.ProxyTopicEndpointManager; import org.onap.policy.drools.controller.DroolsController; -import org.onap.policy.drools.event.comm.Topic; -import org.onap.policy.drools.event.comm.TopicEndpoint; -import org.onap.policy.drools.event.comm.TopicListener; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.TopicSource; import org.onap.policy.drools.features.PolicyControllerFeatureAPI; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.drools.properties.DroolsProperties; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; import org.onap.policy.drools.system.PolicyController; - -import com.fasterxml.jackson.annotation.JsonIgnore; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * This implementation of the Policy Controller merely aggregates and tracks for - * management purposes all underlying resources that this controller depends upon. + * This implementation of the Policy Controller merely aggregates and tracks for management purposes + * all underlying resources that this controller depends upon. */ -public class AggregatedPolicyController implements PolicyController, - TopicListener { - - /** - * Logger - */ - private static Logger logger = LoggerFactory.getLogger(AggregatedPolicyController.class); - - /** - * identifier for this policy controller - */ - protected final String name; - - /** - * Abstracted Event Sources List regardless communication - * technology - */ - protected final List<? extends TopicSource> sources; - - /** - * Abstracted Event Sinks List regardless communication - * technology - */ - protected final List<? extends TopicSink> sinks; - - /** - * Mapping topics to sinks - */ - @JsonIgnore - protected final HashMap<String, TopicSink> topic2Sinks = - new HashMap<>(); - - /** - * Is this Policy Controller running (alive) ? - * reflects invocation of start()/stop() only - */ - protected volatile boolean alive; - - /** - * Is this Policy Controller locked ? - * reflects if i/o controller related operations and start - * are permitted, - * more specifically: start(), deliver() and onTopicEvent(). - * It does not affect the ability to stop the - * underlying drools infrastructure - */ - protected volatile boolean locked; - - /** - * Policy Drools Controller - */ - protected volatile DroolsController droolsController; - - /** - * Properties used to initialize controller - */ - protected final Properties properties; - - /** - * Constructor version mainly used for bootstrapping at initialization time - * a policy engine controller - * - * @param name controller name - * @param properties - * - * @throws IllegalArgumentException when invalid arguments are provided - */ - public AggregatedPolicyController(String name, Properties properties) { - - this.name = name; - - /* - * 1. Register read topics with network infrastructure (ueb, dmaap, rest) - * 2. Register write topics with network infrastructure (ueb, dmaap, rest) - * 3. Register with drools infrastructure - */ - - // Create/Reuse Readers/Writers for all event sources endpoints - - this.sources = TopicEndpoint.manager.addTopicSources(properties); - this.sinks = TopicEndpoint.manager.addTopicSinks(properties); - - initDrools(properties); - initSinks(); - - /* persist new properties */ - SystemPersistence.manager.storeController(name, properties); - this.properties = properties; - } - - /** - * initialize drools layer - * @throws IllegalArgumentException if invalid parameters are passed in - */ - protected void initDrools(Properties properties) { - try { - // Register with drools infrastructure - this.droolsController = DroolsController.factory.build(properties, sources, sinks); - } catch (Exception | LinkageError e) { - logger.error("{}: cannot init-drools because of {}", this, e.getMessage(), e); - throw new IllegalArgumentException(e); - } - } - - /** - * initialize sinks - * @throws IllegalArgumentException if invalid parameters are passed in - */ - protected void initSinks() { - this.topic2Sinks.clear(); - for (TopicSink sink: sinks) { - this.topic2Sinks.put(sink.getTopic(), sink); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean updateDrools(DroolsConfiguration newDroolsConfiguration) { - - DroolsConfiguration oldDroolsConfiguration = - new DroolsConfiguration(this.droolsController.getArtifactId(), - this.droolsController.getGroupId(), - this.droolsController.getVersion()); - - if (oldDroolsConfiguration.getGroupId().equalsIgnoreCase(newDroolsConfiguration.getGroupId()) && - oldDroolsConfiguration.getArtifactId().equalsIgnoreCase(newDroolsConfiguration.getArtifactId()) && - oldDroolsConfiguration.getVersion().equalsIgnoreCase(newDroolsConfiguration.getVersion())) { - logger.warn("{}: cannot update-drools: identical configuration {} vs {}", - this, oldDroolsConfiguration, newDroolsConfiguration); - return true; - } - - try { - /* Drools Controller created, update initialization properties for restarts */ - - this.properties.setProperty(PolicyProperties.RULES_GROUPID, newDroolsConfiguration.getGroupId()); - this.properties.setProperty(PolicyProperties.RULES_ARTIFACTID, newDroolsConfiguration.getArtifactId()); - this.properties.setProperty(PolicyProperties.RULES_VERSION, newDroolsConfiguration.getVersion()); - - SystemPersistence.manager.storeController(name, this.properties); - - this.initDrools(this.properties); - - /* set drools controller to current locked status */ - - if (this.isLocked()) - this.droolsController.lock(); - else - this.droolsController.unlock(); - - /* set drools controller to current alive status */ - - if (this.isAlive()) - this.droolsController.start(); - else - this.droolsController.stop(); - - } catch (IllegalArgumentException e) { - logger.error("{}: cannot update-drools because of {}", this, e.getMessage(), e); - return false; - } - - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public String getName() { - return this.name; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean start() { - logger.info("{}: start", this); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.beforeStart(this)) - return true; - } catch (Exception e) { - logger.error("{}: feature {} before-start failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - if (this.isLocked()) - throw new IllegalStateException("Policy Controller " + name + " is locked"); - - synchronized(this) { - if (this.alive) - return true; - - this.alive = true; - } - - boolean success = this.droolsController.start(); - - // register for events - - for (TopicSource source: sources) { - source.register(this); - } - - for (TopicSink sink: sinks) { - try { - sink.start(); - } catch (Exception e) { - logger.error("{}: cannot start {} because of {}", - this, sink, e.getMessage(), e); - } - } - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.afterStart(this)) - return true; - } catch (Exception e) { - logger.error("{}: feature {} after-start failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - return success; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean stop() { - logger.info("{}: stop", this); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.beforeStop(this)) - return true; - } catch (Exception e) { - logger.error("{}: feature {} before-stop failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - /* stop regardless locked state */ - - synchronized(this) { - if (!this.alive) - return true; - - this.alive = false; - } - - // 1. Stop registration - - for (TopicSource source: sources) { - source.unregister(this); - } - - boolean success = this.droolsController.stop(); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.afterStop(this)) - return true; - } catch (Exception e) { - logger.error("{}: feature {} after-stop failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - return success; - } - - /** - * {@inheritDoc} - */ - @Override - public void shutdown() { - logger.info("{}: shutdown", this); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.beforeShutdown(this)) - return; - } catch (Exception e) { - logger.error("{}: feature {} before-shutdown failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - this.stop(); - - DroolsController.factory.shutdown(this.droolsController); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.afterShutdown(this)) - return; - } catch (Exception e) { - logger.error("{}: feature {} after-shutdown failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void halt() { - logger.info("{}: halt", this); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.beforeHalt(this)) - return; - } catch (Exception e) { - logger.error("{}: feature {} before-halt failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - this.stop(); - DroolsController.factory.destroy(this.droolsController); - SystemPersistence.manager.deleteController(this.name); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.afterHalt(this)) - return; - } catch (Exception e) { - logger.error("{}: feature {} after-halt failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void onTopicEvent(Topic.CommInfrastructure commType, - String topic, String event) { - - if (logger.isDebugEnabled()) - logger.debug("{}: event offered from {}:{}: {}", this, commType, topic, event); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.beforeOffer(this, commType, topic, event)) - return; - } catch (Exception e) { - logger.error("{}: feature {} before-offer failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - if (this.locked) - return; - - if (!this.alive) - return; - - boolean success = this.droolsController.offer(topic, event); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.afterOffer(this, commType, topic, event, success)) - return; - } catch (Exception e) { - logger.error("{}: feature {} after-offer failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean deliver(Topic.CommInfrastructure commType, - String topic, Object event) { - - if (logger.isDebugEnabled()) - logger.debug("{}: deliver event to {}:{}: {}", this, commType, topic, event); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.beforeDeliver(this, commType, topic, event)) - return true; - } catch (Exception e) { - logger.error("{}: feature {} before-deliver failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - if (topic == null || topic.isEmpty()) - throw new IllegalArgumentException("Invalid Topic"); - - if (event == null) - throw new IllegalArgumentException("Invalid Event"); - - if (!this.isAlive()) - throw new IllegalStateException("Policy Engine is stopped"); - - if (this.isLocked()) - throw new IllegalStateException("Policy Engine is locked"); - - if (!this.topic2Sinks.containsKey(topic)) { - logger.warn("{}: cannot deliver event because the sink {}:{} is not registered: {}", - this, commType, topic, event); - throw new IllegalArgumentException("Unsuported topic " + topic + " for delivery"); - } - - boolean success = this.droolsController.deliver(this.topic2Sinks.get(topic), event); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.afterDeliver(this, commType, topic, event, success)) - return success; - } catch (Exception e) { - logger.error("{}: feature {} after-deliver failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - return success; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isAlive() { - return this.alive; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean lock() { - logger.info("{}: lock", this); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.beforeLock(this)) - return true; - } catch (Exception e) { - logger.error("{}: feature {} before-lock failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - synchronized(this) { - if (this.locked) - return true; - - this.locked = true; - } - - // it does not affect associated sources/sinks, they are - // autonomous entities - - boolean success = this.droolsController.lock(); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.afterLock(this)) - return true; - } catch (Exception e) { - logger.error("{}: feature {} after-lock failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - return success; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean unlock() { - - logger.info("{}: unlock", this); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.beforeUnlock(this)) - return true; - } catch (Exception e) { - logger.error("{}: feature {} before-unlock failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - synchronized(this) { - if (!this.locked) - return true; - - this.locked = false; - } - - boolean success = this.droolsController.unlock(); - - for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { - try { - if (feature.afterUnlock(this)) - return true; - } catch (Exception e) { - logger.error("{}: feature {} after-unlock failure because of {}", - this, feature.getClass().getName(), e.getMessage(), e); - } - } - - return success; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isLocked() { - return this.locked; - } - - /** - * {@inheritDoc} - */ - @Override - public List<? extends TopicSource> getTopicSources() { - return this.sources; - } - - /** - * {@inheritDoc} - */ - @Override - public List<? extends TopicSink> getTopicSinks() { - return this.sinks; - } - - /** - * {@inheritDoc} - */ - @Override - public DroolsController getDrools() { - return this.droolsController; - } - - - /** - * {@inheritDoc} - */ - @Override - @JsonIgnore - public Properties getProperties() { - return this.properties; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("AggregatedPolicyController [name=").append(name).append(", alive=").append(alive).append(", locked=").append(locked) - .append(", droolsController=").append(droolsController).append("]"); - return builder.toString(); - } +public class AggregatedPolicyController implements PolicyController, TopicListener { + + /** + * Logger + */ + private static Logger logger = LoggerFactory.getLogger(AggregatedPolicyController.class); + + /** + * identifier for this policy controller + */ + protected final String name; + + /** + * Abstracted Event Sources List regardless communication technology + */ + protected final List<? extends TopicSource> sources; + + /** + * Abstracted Event Sinks List regardless communication technology + */ + protected final List<? extends TopicSink> sinks; + + /** + * Mapping topics to sinks + */ + @JsonIgnore + protected final HashMap<String, TopicSink> topic2Sinks = new HashMap<>(); + + /** + * Is this Policy Controller running (alive) ? reflects invocation of start()/stop() only + */ + protected volatile boolean alive; + + /** + * Is this Policy Controller locked ? reflects if i/o controller related operations and start + * are permitted, more specifically: start(), deliver() and onTopicEvent(). It does not affect + * the ability to stop the underlying drools infrastructure + */ + protected volatile boolean locked; + + /** + * Policy Drools Controller + */ + protected volatile DroolsController droolsController; + + /** + * Properties used to initialize controller + */ + protected final Properties properties; + + /** + * Constructor version mainly used for bootstrapping at initialization time a policy engine + * controller + * + * @param name controller name + * @param properties + * + * @throws IllegalArgumentException when invalid arguments are provided + */ + public AggregatedPolicyController(String name, Properties properties) { + + this.name = name; + + /* + * 1. Register read topics with network infrastructure (ueb, dmaap, rest) 2. Register write + * topics with network infrastructure (ueb, dmaap, rest) 3. Register with drools + * infrastructure + */ + + // Create/Reuse Readers/Writers for all event sources endpoints + + this.sources = ProxyTopicEndpointManager.getInstance().addTopicSources(properties); + this.sinks = ProxyTopicEndpointManager.getInstance().addTopicSinks(properties); + + initDrools(properties); + initSinks(); + + /* persist new properties */ + SystemPersistence.manager.storeController(name, properties); + this.properties = properties; + } + + /** + * initialize drools layer + * + * @throws IllegalArgumentException if invalid parameters are passed in + */ + protected void initDrools(Properties properties) { + try { + // Register with drools infrastructure + this.droolsController = DroolsController.factory.build(properties, sources, sinks); + } catch (Exception | LinkageError e) { + logger.error("{}: cannot init-drools because of {}", this, e.getMessage(), e); + throw new IllegalArgumentException(e); + } + } + + /** + * initialize sinks + * + * @throws IllegalArgumentException if invalid parameters are passed in + */ + protected void initSinks() { + this.topic2Sinks.clear(); + for (TopicSink sink : sinks) { + this.topic2Sinks.put(sink.getTopic(), sink); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean updateDrools(DroolsConfiguration newDroolsConfiguration) { + + DroolsConfiguration oldDroolsConfiguration = new DroolsConfiguration(this.droolsController.getArtifactId(), + this.droolsController.getGroupId(), this.droolsController.getVersion()); + + if (oldDroolsConfiguration.getGroupId().equalsIgnoreCase(newDroolsConfiguration.getGroupId()) + && oldDroolsConfiguration.getArtifactId().equalsIgnoreCase(newDroolsConfiguration.getArtifactId()) + && oldDroolsConfiguration.getVersion().equalsIgnoreCase(newDroolsConfiguration.getVersion())) { + logger.warn("{}: cannot update-drools: identical configuration {} vs {}", this, oldDroolsConfiguration, + newDroolsConfiguration); + return true; + } + + try { + /* Drools Controller created, update initialization properties for restarts */ + + this.properties.setProperty(DroolsProperties.RULES_GROUPID, newDroolsConfiguration.getGroupId()); + this.properties.setProperty(DroolsProperties.RULES_ARTIFACTID, newDroolsConfiguration.getArtifactId()); + this.properties.setProperty(DroolsProperties.RULES_VERSION, newDroolsConfiguration.getVersion()); + + SystemPersistence.manager.storeController(name, this.properties); + + this.initDrools(this.properties); + + /* set drools controller to current locked status */ + + if (this.isLocked()) { + this.droolsController.lock(); + } else { + this.droolsController.unlock(); + } + + /* set drools controller to current alive status */ + + if (this.isAlive()) { + this.droolsController.start(); + } else { + this.droolsController.stop(); + } + + } catch (IllegalArgumentException e) { + logger.error("{}: cannot update-drools because of {}", this, e.getMessage(), e); + return false; + } + + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return this.name; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean start() { + logger.info("{}: start", this); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.beforeStart(this)) { + return true; + } + } catch (Exception e) { + logger.error("{}: feature {} before-start failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + if (this.isLocked()) { + throw new IllegalStateException("Policy Controller " + name + " is locked"); + } + + synchronized (this) { + if (this.alive) { + return true; + } + + this.alive = true; + } + + boolean success = this.droolsController.start(); + + // register for events + + for (TopicSource source : sources) { + source.register(this); + } + + for (TopicSink sink : sinks) { + try { + sink.start(); + } catch (Exception e) { + logger.error("{}: cannot start {} because of {}", this, sink, e.getMessage(), e); + } + } + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.afterStart(this)) { + return true; + } + } catch (Exception e) { + logger.error("{}: feature {} after-start failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + return success; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean stop() { + logger.info("{}: stop", this); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.beforeStop(this)) { + return true; + } + } catch (Exception e) { + logger.error("{}: feature {} before-stop failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + /* stop regardless locked state */ + + synchronized (this) { + if (!this.alive) { + return true; + } + + this.alive = false; + } + + // 1. Stop registration + + for (TopicSource source : sources) { + source.unregister(this); + } + + boolean success = this.droolsController.stop(); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.afterStop(this)) { + return true; + } + } catch (Exception e) { + logger.error("{}: feature {} after-stop failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + return success; + } + + /** + * {@inheritDoc} + */ + @Override + public void shutdown() { + logger.info("{}: shutdown", this); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.beforeShutdown(this)) { + return; + } + } catch (Exception e) { + logger.error("{}: feature {} before-shutdown failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + this.stop(); + + DroolsController.factory.shutdown(this.droolsController); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.afterShutdown(this)) { + return; + } + } catch (Exception e) { + logger.error("{}: feature {} after-shutdown failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void halt() { + logger.info("{}: halt", this); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.beforeHalt(this)) { + return; + } + } catch (Exception e) { + logger.error("{}: feature {} before-halt failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + this.stop(); + DroolsController.factory.destroy(this.droolsController); + SystemPersistence.manager.deleteController(this.name); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.afterHalt(this)) { + return; + } + } catch (Exception e) { + logger.error("{}: feature {} after-halt failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void onTopicEvent(Topic.CommInfrastructure commType, String topic, String event) { + + if (logger.isDebugEnabled()) { + logger.debug("{}: event offered from {}:{}: {}", this, commType, topic, event); + } + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.beforeOffer(this, commType, topic, event)) { + return; + } + } catch (Exception e) { + logger.error("{}: feature {} before-offer failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + if (this.locked) { + return; + } + + if (!this.alive) { + return; + } + + boolean success = this.droolsController.offer(topic, event); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.afterOffer(this, commType, topic, event, success)) { + return; + } + } catch (Exception e) { + logger.error("{}: feature {} after-offer failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean deliver(Topic.CommInfrastructure commType, String topic, Object event) { + + if (logger.isDebugEnabled()) { + logger.debug("{}: deliver event to {}:{}: {}", this, commType, topic, event); + } + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.beforeDeliver(this, commType, topic, event)) { + return true; + } + } catch (Exception e) { + logger.error("{}: feature {} before-deliver failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + if (topic == null || topic.isEmpty()) { + throw new IllegalArgumentException("Invalid Topic"); + } + + if (event == null) { + throw new IllegalArgumentException("Invalid Event"); + } + + if (!this.isAlive()) { + throw new IllegalStateException("Policy Engine is stopped"); + } + + if (this.isLocked()) { + throw new IllegalStateException("Policy Engine is locked"); + } + + if (!this.topic2Sinks.containsKey(topic)) { + logger.warn("{}: cannot deliver event because the sink {}:{} is not registered: {}", this, commType, topic, + event); + throw new IllegalArgumentException("Unsuported topic " + topic + " for delivery"); + } + + boolean success = this.droolsController.deliver(this.topic2Sinks.get(topic), event); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.afterDeliver(this, commType, topic, event, success)) { + return success; + } + } catch (Exception e) { + logger.error("{}: feature {} after-deliver failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + return success; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isAlive() { + return this.alive; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean lock() { + logger.info("{}: lock", this); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.beforeLock(this)) { + return true; + } + } catch (Exception e) { + logger.error("{}: feature {} before-lock failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + synchronized (this) { + if (this.locked) { + return true; + } + + this.locked = true; + } + + // it does not affect associated sources/sinks, they are + // autonomous entities + + boolean success = this.droolsController.lock(); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.afterLock(this)) { + return true; + } + } catch (Exception e) { + logger.error("{}: feature {} after-lock failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + return success; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean unlock() { + + logger.info("{}: unlock", this); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.beforeUnlock(this)) { + return true; + } + } catch (Exception e) { + logger.error("{}: feature {} before-unlock failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + synchronized (this) { + if (!this.locked) { + return true; + } + + this.locked = false; + } + + boolean success = this.droolsController.unlock(); + + for (PolicyControllerFeatureAPI feature : PolicyControllerFeatureAPI.providers.getList()) { + try { + if (feature.afterUnlock(this)) { + return true; + } + } catch (Exception e) { + logger.error("{}: feature {} after-unlock failure because of {}", this, feature.getClass().getName(), + e.getMessage(), e); + } + } + + return success; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isLocked() { + return this.locked; + } + + /** + * {@inheritDoc} + */ + @Override + public List<? extends TopicSource> getTopicSources() { + return this.sources; + } + + /** + * {@inheritDoc} + */ + @Override + public List<? extends TopicSink> getTopicSinks() { + return this.sinks; + } + + /** + * {@inheritDoc} + */ + @Override + public DroolsController getDrools() { + return this.droolsController; + } + + + /** + * {@inheritDoc} + */ + @Override + @JsonIgnore + public Properties getProperties() { + return this.properties; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("AggregatedPolicyController [name=").append(name).append(", alive=").append(alive) + .append(", locked=").append(locked).append(", droolsController=").append(droolsController).append("]"); + return builder.toString(); + } } diff --git a/policy-management/src/test/java/org/onap/policy/drools/persistence/test/SystemPersistenceTest.java b/policy-management/src/test/java/org/onap/policy/drools/persistence/test/SystemPersistenceTest.java index 56fab7fd..9b2e6161 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/persistence/test/SystemPersistenceTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/persistence/test/SystemPersistenceTest.java @@ -38,7 +38,7 @@ import org.junit.Test; import org.junit.runners.MethodSorters; import org.onap.policy.drools.persistence.FileSystemPersistence; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.drools.properties.DroolsProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -149,7 +149,7 @@ public class SystemPersistenceTest { assertTrue(Files.notExists(controllerBakPath)); Properties properties = new Properties(); - properties.put(PolicyProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME); + properties.put(DroolsProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME); SystemPersistence.manager.storeController(TEST_CONTROLLER_NAME, properties); assertTrue(Files.exists(controllerPath)); diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java index a56bb5f2..a23820cf 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/EventProtocolCoderTest.java @@ -25,10 +25,9 @@ import static org.junit.Assert.assertTrue; import java.util.Properties; - import org.junit.Test; -import org.onap.policy.drools.event.comm.TopicEndpoint; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.common.endpoints.event.comm.impl.ProxyTopicEndpointManager; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; /** @@ -81,16 +80,16 @@ public class EventProtocolCoderTest { public void test() { final Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, NOOP_TOPIC); + noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, NOOP_TOPIC); - TopicEndpoint.manager.addTopicSinks(noopSinkProperties); + ProxyTopicEndpointManager.getInstance().addTopicSinks(noopSinkProperties); EventProtocolCoder.manager.addEncoder(ENCODER_GROUP, ENCODER_ARTIFACT, NOOP_TOPIC, - DroolsConfiguration.class.getCanonicalName(), new JsonProtocolFilter(), null, null, - DroolsConfiguration.class.getName().hashCode()); + DroolsConfiguration.class.getCanonicalName(), new JsonProtocolFilter(), null, null, + DroolsConfiguration.class.getName().hashCode()); final String json = EventProtocolCoder.manager.encode(NOOP_TOPIC, - new DroolsConfiguration(ENCODER_GROUP, ENCODER_ARTIFACT, ENCODER_VERSION)); + new DroolsConfiguration(ENCODER_GROUP, ENCODER_ARTIFACT, ENCODER_VERSION)); assertTrue(json.contains(ENCODER_GROUP)); assertTrue(json.contains(ENCODER_ARTIFACT)); diff --git a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java index c7113cd4..02b09bb1 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/protocol/coders/ProtocolCoderToolsetTest.java @@ -20,6 +20,11 @@ package org.onap.policy.drools.protocol.coders; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; @@ -31,11 +36,12 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.kie.api.builder.ReleaseId; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.impl.ProxyTopicEndpointManager; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.controller.internal.MavenDroolsControllerTest; -import org.onap.policy.drools.event.comm.TopicEndpoint; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.drools.properties.DroolsProperties; import org.onap.policy.drools.protocol.coders.EventProtocolCoder.CoderFilters; import org.onap.policy.drools.protocol.coders.JsonProtocolFilter.FilterRule; import org.onap.policy.drools.protocol.coders.TopicCoderFilterConfiguration.CustomGsonCoder; @@ -44,11 +50,6 @@ import org.onap.policy.drools.utils.Triple; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - /** * ProtocolCoder Toolset JUNITs */ @@ -57,8 +58,7 @@ public class ProtocolCoderToolsetTest { public static final String JUNIT_PROTOCOL_CODER_TOPIC = JUNIT_PROTOCOL_CODER_ARTIFACT_ID; public static final String CONTROLLER_ID = "blah"; public static final String ARTIFACT_ID_ECHO = "echo"; - public static final String ARTIFACT_ID_POM_LINE = - "<artifactId>" + ARTIFACT_ID_ECHO + "</artifactId>"; + public static final String ARTIFACT_ID_POM_LINE = "<artifactId>" + ARTIFACT_ID_ECHO + "</artifactId>"; private static Logger logger = LoggerFactory.getLogger(ProtocolCoderToolset.class); @@ -68,26 +68,23 @@ public class ProtocolCoderToolsetTest { @Before public void setUp() throws IOException { - if (releaseId != null) + if (releaseId != null) { return; + } - String pom = new String(Files.readAllBytes - (Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_POM_PATH))); + String pom = new String(Files.readAllBytes(Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_POM_PATH))); - if (!pom.contains(ARTIFACT_ID_POM_LINE)) + if (!pom.contains(ARTIFACT_ID_POM_LINE)) { throw new IllegalArgumentException("unexpected junit test pom"); + } - String newPom = pom.replace(ARTIFACT_ID_ECHO, JUNIT_PROTOCOL_CODER_ARTIFACT_ID); + String newPom = pom.replace(ARTIFACT_ID_ECHO, JUNIT_PROTOCOL_CODER_ARTIFACT_ID); - String kmodule = new String(Files.readAllBytes - (Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_PATH))); + String kmodule = new String(Files.readAllBytes(Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_PATH))); - String drl = new String(Files.readAllBytes - (Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_DRL_PATH))); + String drl = new String(Files.readAllBytes(Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_DRL_PATH))); - releaseId = - KieUtils.installArtifact(kmodule, newPom, - MavenDroolsControllerTest.JUNIT_ECHO_KJAR_DRL_PATH, drl); + releaseId = KieUtils.installArtifact(kmodule, newPom, MavenDroolsControllerTest.JUNIT_ECHO_KJAR_DRL_PATH, drl); } @Test @@ -98,15 +95,9 @@ public class ProtocolCoderToolsetTest { } public void testGsonToolset(JsonProtocolFilter protocolFilter) { - GsonProtocolCoderToolset gsonToolset = - new GsonProtocolCoderToolset(JUNIT_PROTOCOL_CODER_TOPIC, - CONTROLLER_ID, - this.releaseId.getGroupId(), - this.releaseId.getArtifactId(), - Triple.class.getCanonicalName(), - protocolFilter, - null, - 12345678); + GsonProtocolCoderToolset gsonToolset = new GsonProtocolCoderToolset(JUNIT_PROTOCOL_CODER_TOPIC, CONTROLLER_ID, + this.releaseId.getGroupId(), this.releaseId.getArtifactId(), Triple.class.getCanonicalName(), + protocolFilter, null, 12345678); Assert.assertNotNull(gsonToolset.getEncoder()); Assert.assertNotNull(gsonToolset.getDecoder()); @@ -114,8 +105,7 @@ public class ProtocolCoderToolsetTest { testToolset(protocolFilter, gsonToolset); Triple<String, String, String> triple = createTriple(); - gsonToolset.setCustomCoder(new CustomGsonCoder(this.getClass().getCanonicalName(), - "customCoder")); + gsonToolset.setCustomCoder(new CustomGsonCoder(this.getClass().getCanonicalName(), "customCoder")); String tripleEncoded = encode(gsonToolset, triple); decode(protocolFilter, gsonToolset, triple, tripleEncoded); } @@ -125,15 +115,9 @@ public class ProtocolCoderToolsetTest { } public void testJacksonToolset(JsonProtocolFilter protocolFilter) { - JacksonProtocolCoderToolset jacksonToolset = - new JacksonProtocolCoderToolset(JUNIT_PROTOCOL_CODER_TOPIC, - CONTROLLER_ID, - this.releaseId.getGroupId(), - this.releaseId.getArtifactId(), - Triple.class.getCanonicalName(), - protocolFilter, - null, - 12345678); + JacksonProtocolCoderToolset jacksonToolset = new JacksonProtocolCoderToolset(JUNIT_PROTOCOL_CODER_TOPIC, + CONTROLLER_ID, this.releaseId.getGroupId(), this.releaseId.getArtifactId(), + Triple.class.getCanonicalName(), protocolFilter, null, 12345678); jacksonToolset.getEncoder().setVisibility(PropertyAccessor.FIELD, Visibility.ANY); jacksonToolset.getDecoder().setVisibility(PropertyAccessor.FIELD, Visibility.ANY); @@ -160,14 +144,13 @@ public class ProtocolCoderToolsetTest { } @SuppressWarnings("unchecked") - private void decode(JsonProtocolFilter protocolFilter, ProtocolCoderToolset coderToolset, - Triple<String, String, String> triple, String tripleEncoded) { + private void decode(JsonProtocolFilter protocolFilter, ProtocolCoderToolset coderToolset, + Triple<String, String, String> triple, String tripleEncoded) { Triple<String, String, String> tripleDecoded = null; try { - tripleDecoded = - (Triple<String, String, String>) coderToolset.decode(tripleEncoded); - } catch(UnsupportedOperationException e){ + tripleDecoded = (Triple<String, String, String>) coderToolset.decode(tripleEncoded); + } catch (UnsupportedOperationException e) { /* OK */ logger.trace("Junit expected exception - decode does not pass filtering", e); } @@ -181,8 +164,7 @@ public class ProtocolCoderToolsetTest { coderFilters.getFilter().getRules("second").get(0).setRegex("^v2$"); coderFilters.getFilter().getRules("third").get(0).setRegex(".*v3.*"); - tripleDecoded = - (Triple<String, String, String>) coderToolset.decode(tripleEncoded); + tripleDecoded = (Triple<String, String, String>) coderToolset.decode(tripleEncoded); Assert.assertTrue(tripleDecoded.first().equals(triple.first())); Assert.assertTrue(tripleDecoded.second().equals(triple.second())); @@ -191,8 +173,7 @@ public class ProtocolCoderToolsetTest { coderFilters.getFilter().deleteRules("third"); Assert.assertTrue(coderFilters.getFilter().getRules("third").isEmpty()); - tripleDecoded = - (Triple<String, String, String>) coderToolset.decode(tripleEncoded); + tripleDecoded = (Triple<String, String, String>) coderToolset.decode(tripleEncoded); Assert.assertTrue(tripleDecoded.first().equals(triple.first())); Assert.assertTrue(tripleDecoded.second().equals(triple.second())); @@ -211,7 +192,7 @@ public class ProtocolCoderToolsetTest { List<FilterRule> filters = new ArrayList<>(); filters.add(new FilterRule("second", ".*")); - coderToolset.addCoder(this.getClass().getCanonicalName(), new JsonProtocolFilter(filters),654321); + coderToolset.addCoder(this.getClass().getCanonicalName(), new JsonProtocolFilter(filters), 654321); Assert.assertTrue(coderToolset.getCoders().size() == 2); coderToolset.removeCoders(this.getClass().getCanonicalName()); @@ -221,26 +202,20 @@ public class ProtocolCoderToolsetTest { private void updateCoderFilterRule(ProtocolCoderToolset coderToolset) { List<FilterRule> filters = new ArrayList<>(); filters.add(new FilterRule("third", ".*")); - coderToolset.addCoder(Triple.class.getCanonicalName(), - new JsonProtocolFilter(filters), 654321); + coderToolset.addCoder(Triple.class.getCanonicalName(), new JsonProtocolFilter(filters), 654321); Assert.assertTrue(coderToolset.getCoders().size() == 1); - Assert.assertTrue - (coderToolset.getCoder(Triple.class.getCanonicalName()). - getModelClassLoaderHash() == 654321); + Assert.assertTrue(coderToolset.getCoder(Triple.class.getCanonicalName()).getModelClassLoaderHash() == 654321); - Assert.assertTrue - (coderToolset.getCoder(Triple.class.getCanonicalName()). - getFilter().getRules("third").size() == 1); + Assert.assertTrue( + coderToolset.getCoder(Triple.class.getCanonicalName()).getFilter().getRules("third").size() == 1); - Assert.assertTrue - (coderToolset.getCoder(Triple.class.getCanonicalName()). - getFilter().getRules("third").size() == 1); + Assert.assertTrue( + coderToolset.getCoder(Triple.class.getCanonicalName()).getFilter().getRules("third").size() == 1); - Assert.assertTrue - (".*".equals(coderToolset.getCoder(Triple.class.getCanonicalName()). - getFilter().getRules("third").get(0).getRegex())); + Assert.assertTrue(".*".equals(coderToolset.getCoder(Triple.class.getCanonicalName()).getFilter() + .getRules("third").get(0).getRegex())); } private void validateInitialization(JsonProtocolFilter protocolFilter, ProtocolCoderToolset coderToolset) { @@ -261,22 +236,21 @@ public class ProtocolCoderToolsetTest { } private void createController() { - if (releaseId == null) + if (releaseId == null) { throw new IllegalStateException("no prereq artifact installed in maven repository"); + } Properties sinkConfig = new Properties(); - sinkConfig.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, JUNIT_PROTOCOL_CODER_TOPIC); - List<? extends TopicSink> noopTopics = - TopicEndpoint.manager.addTopicSinks(sinkConfig); + sinkConfig.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, JUNIT_PROTOCOL_CODER_TOPIC); + List<? extends TopicSink> noopTopics = ProxyTopicEndpointManager.getInstance().addTopicSinks(sinkConfig); Properties droolsControllerConfig = new Properties(); - droolsControllerConfig.put(PolicyProperties.RULES_GROUPID, releaseId.getGroupId()); - droolsControllerConfig.put(PolicyProperties.RULES_ARTIFACTID, releaseId.getArtifactId()); - droolsControllerConfig.put(PolicyProperties.RULES_VERSION, releaseId.getVersion()); - droolsControllerConfig.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS + "." + - JUNIT_PROTOCOL_CODER_TOPIC + PolicyProperties.PROPERTY_TOPIC_EVENTS_SUFFIX, - Triple.class.getCanonicalName()); - + droolsControllerConfig.put(DroolsProperties.RULES_GROUPID, releaseId.getGroupId()); + droolsControllerConfig.put(DroolsProperties.RULES_ARTIFACTID, releaseId.getArtifactId()); + droolsControllerConfig.put(DroolsProperties.RULES_VERSION, releaseId.getVersion()); + droolsControllerConfig.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS + "." + JUNIT_PROTOCOL_CODER_TOPIC + + PolicyEndPointProperties.PROPERTY_TOPIC_EVENTS_SUFFIX, Triple.class.getCanonicalName()); + DroolsController.factory.build(droolsControllerConfig, null, noopTopics); } diff --git a/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java b/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java index ba64d2f1..0f57cd97 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/server/restful/test/RestManagerTest.java @@ -21,6 +21,7 @@ package org.onap.policy.drools.server.restful.test; import static org.junit.Assert.assertEquals; + import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -42,9 +43,9 @@ import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; -import org.onap.policy.drools.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.impl.ProxyTopicEndpointManager; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.PolicyProperties; import org.onap.policy.drools.system.PolicyController; import org.onap.policy.drools.system.PolicyEngine; import org.slf4j.Logger; @@ -52,956 +53,815 @@ import org.slf4j.LoggerFactory; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class RestManagerTest { - public static final int DEFAULT_TELEMETRY_PORT = 7887; - private static final String HOST = "localhost"; - private static final String REST_MANAGER_PATH = "/policy/pdp"; - private static final String HOST_URL = - "http://" + HOST + ":" + DEFAULT_TELEMETRY_PORT + REST_MANAGER_PATH; - private static final String FOO_CONTROLLER = "foo"; - - private static final String UEB_TOPIC = "UEB-TOPIC-TEST"; - private static final String DMAAP_TOPIC = "DMAAP-TOPIC-TEST"; - private static final String NOOP_TOPIC = "NOOP_TOPIC"; - - private static final String UEB_SOURCE_SERVER_PROPERTY = - PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + UEB_TOPIC - + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; - private static final String UEB_SINK_SERVER_PROPERTY = PolicyProperties.PROPERTY_UEB_SINK_TOPICS - + "." + UEB_TOPIC + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; - private static final String DMAAP_SOURCE_SERVER_PROPERTY = - PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + DMAAP_TOPIC - + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; - private static final String DMAAP_SINK_SERVER_PROPERTY = - PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + DMAAP_TOPIC - + PolicyProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; - private static final String UEB_SERVER = "localhost"; - private static final String DMAAP_SERVER = "localhost"; - private static final String DMAAP_MECHID = "blah"; - private static final String DMAAP_PASSWD = "blah"; - - private static final String DMAAP_SOURCE_MECHID_KEY = - PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + DMAAP_TOPIC - + PolicyProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX; - private static final String DMAAP_SOURCE_PASSWD_KEY = - PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + DMAAP_TOPIC - + PolicyProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX; - - private static final String DMAAP_SINK_MECHID_KEY = PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS - + "." + DMAAP_TOPIC + PolicyProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX; - private static final String DMAAP_SINK_PASSWD_KEY = PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS - + "." + DMAAP_TOPIC + PolicyProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX; - - - private static final String FOO_CONTROLLER_FILE = FOO_CONTROLLER + "-controller.properties"; - private static final String FOO_CONTROLLER_FILE_BAK = FOO_CONTROLLER_FILE + ".bak"; - - private static CloseableHttpClient client; - - private static final Logger logger = LoggerFactory.getLogger(RestManagerTest.class); - - @BeforeClass - public static void setUp() throws IOException { - cleanUpWorkingDirs(); - - SystemPersistence.manager.setConfigurationDir(null); - - /* override default port */ - final Properties engineProps = PolicyEngine.manager.defaultTelemetryConfig(); - engineProps.put(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + PolicyEngine.TELEMETRY_SERVER_DEFAULT_NAME + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX, - "" + DEFAULT_TELEMETRY_PORT); - - /* other properties */ - engineProps.put(PolicyProperties.PROPERTY_UEB_SOURCE_TOPICS, UEB_TOPIC); - engineProps.put(PolicyProperties.PROPERTY_UEB_SINK_TOPICS, UEB_TOPIC); - engineProps.put(PolicyProperties.PROPERTY_DMAAP_SOURCE_TOPICS, DMAAP_TOPIC); - engineProps.put(PolicyProperties.PROPERTY_DMAAP_SINK_TOPICS, DMAAP_TOPIC); - engineProps.put(UEB_SOURCE_SERVER_PROPERTY, UEB_SERVER); - engineProps.put(UEB_SINK_SERVER_PROPERTY, UEB_SERVER); - engineProps.put(DMAAP_SOURCE_SERVER_PROPERTY, DMAAP_SERVER); - engineProps.put(DMAAP_SINK_SERVER_PROPERTY, DMAAP_SERVER); - engineProps.put(DMAAP_SOURCE_MECHID_KEY, DMAAP_MECHID); - engineProps.put(DMAAP_SOURCE_PASSWD_KEY, DMAAP_PASSWD); - engineProps.put(DMAAP_SINK_MECHID_KEY, DMAAP_MECHID); - engineProps.put(DMAAP_SINK_PASSWD_KEY, DMAAP_PASSWD); - engineProps.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, NOOP_TOPIC); - - PolicyEngine.manager.configure(engineProps); - PolicyEngine.manager.start(); - - Properties controllerProps = new Properties(); - PolicyEngine.manager.createPolicyController(FOO_CONTROLLER, controllerProps); - - - client = HttpClients.createDefault(); - - - } - - @AfterClass - public static void tearDown() throws IOException, InterruptedException { - /* Shutdown managed resources */ - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - PolicyEngine.manager.stop(); - Thread.sleep(10000L); - client.close(); - cleanUpWorkingDirs(); - } - - - @Test - public void putDeleteTest() throws ClientProtocolException, IOException, InterruptedException { - HttpPut httpPut; - HttpDelete httpDelete; - CloseableHttpResponse response; - - /* - * DELETE: - * /engine/controllers/controllerName/drools/facts/session/factType - * - */ - httpDelete = new HttpDelete(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts/session/factType"); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection(); - - httpDelete = new HttpDelete(HOST_URL + "/engine/controllers/controllerName/drools/facts/session/factType"); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection(); - - /* - * PUT: - * /engine/switches/lock - * /engine/controllers/controllername/switches/lock - * DELETE: - * /engine/switches/lock - * /engine/controllers/controllername - */ - httpPut = new HttpPut(HOST_URL + "/engine/switches/lock"); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(406, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpDelete = new HttpDelete(HOST_URL + "/engine/switches/lock"); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(406, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection(); - - httpDelete = new HttpDelete(HOST_URL + "/engine/controllers/"); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(405, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection(); - - httpDelete = new HttpDelete(HOST_URL + "/engine/controllers/" + null); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(400, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection(); - - httpPut = new HttpPut(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/switches/lock"); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() +" response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(406, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpDelete = new HttpDelete(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection(); - - httpPut = new HttpPut(HOST_URL + "/engine/switches/lock"); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpDelete = new HttpDelete(HOST_URL + "/engine/switches/lock"); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection(); - - /* - * PUT: - * /engine/topics/sources/ueb/topic/events - * /engine/topics/sources/dmaap/topic/events - * /engine/topics/switches/lock - * DELETE: - * /engine/topics/switches/lock - */ - httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/events"); - httpPut.addHeader("Content-Type", "text/plain"); - httpPut.addHeader("Accept", "application/json"); - httpPut.setEntity(new StringEntity("FOOOO")); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/events"); - httpPut.addHeader("Content-Type", "text/plain"); - httpPut.addHeader("Accept", "application/json"); - httpPut.setEntity(new StringEntity("FOOOO")); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/fiznits/events"); - httpPut.addHeader("Content-Type", "text/plain"); - httpPut.addHeader("Accept", "application/json"); - httpPut.setEntity(new StringEntity("FOOOO")); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(406, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/dmaap/fiznits/events"); - httpPut.addHeader("Content-Type", "text/plain"); - httpPut.addHeader("Accept", "application/json"); - httpPut.setEntity(new StringEntity("FOOOO")); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpPut = new HttpPut(HOST_URL + "/engine/topics/switches/lock"); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/events"); - httpPut.addHeader("Content-Type", "text/plain"); - httpPut.addHeader("Accept", "application/json"); - httpPut.setEntity(new StringEntity("FOOOO")); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(406, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/events"); - httpPut.addHeader("Content-Type", "text/plain"); - httpPut.addHeader("Accept", "application/json"); - httpPut.setEntity(new StringEntity("FOOOO")); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(406, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpDelete = new HttpDelete(HOST_URL + "/engine/topics/switches/lock"); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection(); - - /* - * PUT: - * /engine/topics/sources/ueb/topic/switches/lock - * /engine/topics/sources/dmaap/topic/switches/lock - * DELETE: - * /engine/topics/sources/ueb/topic/switches/lock - * /engine/topics/sources/dmaap/topic/switches/lock - */ - httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/switches/lock"); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpDelete = - new HttpDelete(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/switches/lock"); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection(); - - httpPut = - new HttpPut(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/switches/lock"); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpDelete = - new HttpDelete(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/switches/lock"); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection(); - - /* - * PUT: - * /engine/switches/activation - * DELETE: - * /engine/switches/activation - */ - /* httpPut = new HttpPut(HOST_URL + "/engine/switches/activation"); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - httpDelete = new HttpDelete(HOST_URL + "/engine/switches/activation"); - response = client.execute(httpDelete); - logger.info(httpDelete.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpDelete.releaseConnection();*/ - - /* - * PUT: - * /engine/tools/loggers/logger/level - */ - httpPut = new HttpPut(HOST_URL + "/engine/tools/loggers/ROOT/debug"); - response = client.execute(httpPut); - logger.info(httpPut.getRequestLine() + "response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpPut.releaseConnection(); - - } - - - @Test - public void getTest() throws ClientProtocolException, IOException, InterruptedException { - HttpGet httpGet; - CloseableHttpResponse response; - String responseBody; - - /* - * GET: - * /engine - * /engine/features - * /engine/features/inventory - * /engine/features/featurename - * /engine/inputs - * /engine/properties - * /engine/environment - * /engine/switches - * /engine/controllers - */ - httpGet = new HttpGet(HOST_URL + "/engine"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/features"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/features/inventory"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/features/foobar"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/inputs"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/properties"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/environment"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - PolicyEngine.manager.setEnvironmentProperty("foo", "bar"); - httpGet = new HttpGet(HOST_URL + "/engine/environment/foo"); - response = client.execute(httpGet); - responseBody = this.getResponseBody(response); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - logger.info(httpGet.getRequestLine() + " response body: {}", responseBody); - assertEquals(200, response.getStatusLine().getStatusCode()); - assertEquals("bar", responseBody); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/switches"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers"); - response = client.execute(httpGet); - responseBody = this.getResponseBody(response); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - logger.info(httpGet.getRequestLine() + " response body: {}", responseBody); - assertEquals(200, response.getStatusLine().getStatusCode()); - assertEquals("[\"" + FOO_CONTROLLER + "\"]", responseBody); - httpGet.releaseConnection(); - - /* - * GET: - * /engine/controllers/inventory - * /engine/controllers/features - * /engine/controllers/features/inventory - * /engine/controllers/features/featureName - * /engine/controllers/controllerName - * - */ - httpGet = new HttpGet(HOST_URL + "/engine/controllers/inventory"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/features"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/features/inventory"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/features/dummy"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - /* - * GET: - * /engine/controllers/controllerName/properties - * /engine/controllers/controllerName/inputs - * /engine/controllers/controllerName/switches - * /engine/controllers/controllerName/drools - */ - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/properties"); - response = client.execute(httpGet); - responseBody = this.getResponseBody(response); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - logger.info(httpGet.getRequestLine() + " response code: {}", responseBody); - assertEquals(200, response.getStatusLine().getStatusCode()); - assertEquals("{}", responseBody); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/properties"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/inputs"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/switches"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/drools"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - /* - * GET: - * /engine/controllers/controllerName/drools/facts - * /engine/controllers/controllerName/drools/facts/session - * /engine/controllers/controllerName/drools/facts/session/factType - * /engine/controllers/controllerName/drools/facts/session/query/queriedEntity - * - */ - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/drools/facts"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = - new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts/session"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet( - HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts/session/factType"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER - + "/drools/facts/session/query/queriedEntity"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/dummy" - + "/drools/facts/session/query/queriedEntity"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - - /* - * GET: - * /engine/controllers/controllerName/decoders - * /engine/controllers/controllerName/decoders/filters - * /engine/controllers/controllerName/decoders/topic - * /engine/controllers/controllerName/decoders/topic/filters - * /engine/controllers/controllerName/decoders/topic/filters/factType - * /engine/controllers/controllerName/decoders/topic/filters/factType/rules - * /engine/controllers/controllerName/decoders/topic/filtes/factType/rules/ruleName - * /engine/controllers/controllerName/encoders - */ - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/decoders"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/filters"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/decoders/filters"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = - new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic/filters"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet( - HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic/filters/factType"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER - + "/decoders/topic/filters/factType/rules"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER - + "/decoders/topic/filters/factType/rules/ruleName"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(404, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/encoders"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - /* - * GET: - * /engine/topics - * /engine/topics/switches - * /engine/topics/sources - * /engine/topics/sinks - * /engine/topics/sinks/ueb - * /engine/topics/sources/ueb - * /engine/topics/sinks/dmaap - * /engine/topics/sources/dmaap - * /engine/topics/sinks/ueb/topic - * /engine/topics/sources/ueb/topic - * /engine/topics/sinks/dmaap/topic - * /engine/topics/sources/dmaap/topic - * /engine/topics/sinks/ueb/topic/events - * /engine/topics/sources/ueb/topic/events - * /engine/topics/sinks/dmaap/topic/events - * /engine/topics/sources/dmaap/topic/events - * /engine/topics/sources/ueb/topic/switches - * /engine/topics/sources/dmaap/topic/switches - */ - httpGet = new HttpGet(HOST_URL + "/engine/topics"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/switches"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/foobar"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(500, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/" + UEB_TOPIC); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/foobar"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(500, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/foobar"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(500, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/" + DMAAP_TOPIC); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/foobar"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(500, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/events"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/foobar/events"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(500, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/" + UEB_TOPIC + "/events"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/foobar/events"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(500, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/events"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/foobar/events"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(500, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/" + DMAAP_TOPIC + "/events"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/foobar/events"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(500, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/switches"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/switches"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - /* - * GET: - * /engine/topics/sinks/noop - * /engine/topics/sinks/noop/topic - * /engine/topics/sinks/noop/topic/events - */ - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/noop"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/noop/" + NOOP_TOPIC); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/noop/" + NOOP_TOPIC + "/events"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - /* - * GET: - * /engine/tools/uuid - * /engine/tools/loggers - * /engine/tools/loggers/loggerName - */ - httpGet = new HttpGet(HOST_URL + "/engine/tools/uuid"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/tools/loggers"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - httpGet = new HttpGet(HOST_URL + "/engine/tools/loggers/ROOT"); - response = client.execute(httpGet); - logger.info(httpGet.getRequestLine() + " response code: {}", - response.getStatusLine().getStatusCode()); - assertEquals(200, response.getStatusLine().getStatusCode()); - httpGet.releaseConnection(); - - } - - - public String getResponseBody(CloseableHttpResponse response) { - - HttpEntity entity; - try { - entity = response.getEntity(); - return EntityUtils.toString(entity); - - } catch (final IOException e) { + public static final int DEFAULT_TELEMETRY_PORT = 7887; + private static final String HOST = "localhost"; + private static final String REST_MANAGER_PATH = "/policy/pdp"; + private static final String HOST_URL = "http://" + HOST + ":" + DEFAULT_TELEMETRY_PORT + REST_MANAGER_PATH; + private static final String FOO_CONTROLLER = "foo"; + + private static final String UEB_TOPIC = "UEB-TOPIC-TEST"; + private static final String DMAAP_TOPIC = "DMAAP-TOPIC-TEST"; + private static final String NOOP_TOPIC = "NOOP_TOPIC"; + + private static final String UEB_SOURCE_SERVER_PROPERTY = PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS + "." + + UEB_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; + private static final String UEB_SINK_SERVER_PROPERTY = PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS + "." + UEB_TOPIC + + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; + private static final String DMAAP_SOURCE_SERVER_PROPERTY = PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + + DMAAP_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; + private static final String DMAAP_SINK_SERVER_PROPERTY = PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + + DMAAP_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX; + private static final String UEB_SERVER = "localhost"; + private static final String DMAAP_SERVER = "localhost"; + private static final String DMAAP_MECHID = "blah"; + private static final String DMAAP_PASSWD = "blah"; + + private static final String DMAAP_SOURCE_MECHID_KEY = PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + + DMAAP_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX; + private static final String DMAAP_SOURCE_PASSWD_KEY = PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS + "." + + DMAAP_TOPIC + PolicyEndPointProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX; + + private static final String DMAAP_SINK_MECHID_KEY = PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + DMAAP_TOPIC + + PolicyEndPointProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX; + private static final String DMAAP_SINK_PASSWD_KEY = PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS + "." + DMAAP_TOPIC + + PolicyEndPointProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX; + + + private static final String FOO_CONTROLLER_FILE = FOO_CONTROLLER + "-controller.properties"; + private static final String FOO_CONTROLLER_FILE_BAK = FOO_CONTROLLER_FILE + ".bak"; + + private static CloseableHttpClient client; + + private static final Logger logger = LoggerFactory.getLogger(RestManagerTest.class); + + @BeforeClass + public static void setUp() throws IOException { + cleanUpWorkingDirs(); + + SystemPersistence.manager.setConfigurationDir(null); + + /* override default port */ + final Properties engineProps = PolicyEngine.manager.defaultTelemetryConfig(); + engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + + PolicyEngine.TELEMETRY_SERVER_DEFAULT_NAME + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, + "" + DEFAULT_TELEMETRY_PORT); + + /* other properties */ + engineProps.put(PolicyEndPointProperties.PROPERTY_UEB_SOURCE_TOPICS, UEB_TOPIC); + engineProps.put(PolicyEndPointProperties.PROPERTY_UEB_SINK_TOPICS, UEB_TOPIC); + engineProps.put(PolicyEndPointProperties.PROPERTY_DMAAP_SOURCE_TOPICS, DMAAP_TOPIC); + engineProps.put(PolicyEndPointProperties.PROPERTY_DMAAP_SINK_TOPICS, DMAAP_TOPIC); + engineProps.put(UEB_SOURCE_SERVER_PROPERTY, UEB_SERVER); + engineProps.put(UEB_SINK_SERVER_PROPERTY, UEB_SERVER); + engineProps.put(DMAAP_SOURCE_SERVER_PROPERTY, DMAAP_SERVER); + engineProps.put(DMAAP_SINK_SERVER_PROPERTY, DMAAP_SERVER); + engineProps.put(DMAAP_SOURCE_MECHID_KEY, DMAAP_MECHID); + engineProps.put(DMAAP_SOURCE_PASSWD_KEY, DMAAP_PASSWD); + engineProps.put(DMAAP_SINK_MECHID_KEY, DMAAP_MECHID); + engineProps.put(DMAAP_SINK_PASSWD_KEY, DMAAP_PASSWD); + engineProps.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, NOOP_TOPIC); + + PolicyEngine.manager.configure(engineProps); + PolicyEngine.manager.start(); + + Properties controllerProps = new Properties(); + PolicyEngine.manager.createPolicyController(FOO_CONTROLLER, controllerProps); + + + client = HttpClients.createDefault(); + + + } + + @AfterClass + public static void tearDown() throws IOException, InterruptedException { + /* Shutdown managed resources */ + PolicyController.factory.shutdown(); + ProxyTopicEndpointManager.getInstance().shutdown(); + PolicyEngine.manager.stop(); + Thread.sleep(10000L); + client.close(); + cleanUpWorkingDirs(); + } + + + @Test + public void putDeleteTest() throws ClientProtocolException, IOException, InterruptedException { + HttpPut httpPut; + HttpDelete httpDelete; + CloseableHttpResponse response; + + /* + * DELETE: /engine/controllers/controllerName/drools/facts/session/factType + * + */ + httpDelete = + new HttpDelete(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts/session/factType"); + response = client.execute(httpDelete); + logger.info(httpDelete.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/controllers/controllerName/drools/facts/session/factType"); + response = client.execute(httpDelete); + logger.info(httpDelete.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + /* + * PUT: /engine/switches/lock /engine/controllers/controllername/switches/lock DELETE: + * /engine/switches/lock /engine/controllers/controllername + */ + httpPut = new HttpPut(HOST_URL + "/engine/switches/lock"); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(406, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/switches/lock"); + response = client.execute(httpDelete); + logger.info(httpDelete.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(406, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/controllers/"); + response = client.execute(httpDelete); + logger.info(httpDelete.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(405, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/controllers/" + null); + response = client.execute(httpDelete); + logger.info(httpDelete.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(400, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/switches/lock"); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(406, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER); + response = client.execute(httpDelete); + logger.info(httpDelete.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/switches/lock"); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/switches/lock"); + response = client.execute(httpDelete); + logger.info(httpDelete.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + /* + * PUT: /engine/topics/sources/ueb/topic/events /engine/topics/sources/dmaap/topic/events + * /engine/topics/switches/lock DELETE: /engine/topics/switches/lock + */ + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/events"); + httpPut.addHeader("Content-Type", "text/plain"); + httpPut.addHeader("Accept", "application/json"); + httpPut.setEntity(new StringEntity("FOOOO")); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/events"); + httpPut.addHeader("Content-Type", "text/plain"); + httpPut.addHeader("Accept", "application/json"); + httpPut.setEntity(new StringEntity("FOOOO")); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/fiznits/events"); + httpPut.addHeader("Content-Type", "text/plain"); + httpPut.addHeader("Accept", "application/json"); + httpPut.setEntity(new StringEntity("FOOOO")); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(406, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/dmaap/fiznits/events"); + httpPut.addHeader("Content-Type", "text/plain"); + httpPut.addHeader("Accept", "application/json"); + httpPut.setEntity(new StringEntity("FOOOO")); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/switches/lock"); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/events"); + httpPut.addHeader("Content-Type", "text/plain"); + httpPut.addHeader("Accept", "application/json"); + httpPut.setEntity(new StringEntity("FOOOO")); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(406, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/events"); + httpPut.addHeader("Content-Type", "text/plain"); + httpPut.addHeader("Accept", "application/json"); + httpPut.setEntity(new StringEntity("FOOOO")); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(406, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/topics/switches/lock"); + response = client.execute(httpDelete); + logger.info(httpDelete.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + /* + * PUT: /engine/topics/sources/ueb/topic/switches/lock + * /engine/topics/sources/dmaap/topic/switches/lock DELETE: + * /engine/topics/sources/ueb/topic/switches/lock + * /engine/topics/sources/dmaap/topic/switches/lock + */ + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/switches/lock"); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/switches/lock"); + response = client.execute(httpDelete); + logger.info(httpDelete.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + httpPut = new HttpPut(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/switches/lock"); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); + + httpDelete = new HttpDelete(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/switches/lock"); + response = client.execute(httpDelete); + logger.info(httpDelete.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpDelete.releaseConnection(); + + /* + * PUT: /engine/switches/activation DELETE: /engine/switches/activation + */ + /* + * httpPut = new HttpPut(HOST_URL + "/engine/switches/activation"); response = + * client.execute(httpPut); logger.info(httpPut.getRequestLine() + " response code: {}", + * response.getStatusLine().getStatusCode()); assertEquals(200, + * response.getStatusLine().getStatusCode()); httpPut.releaseConnection(); + * + * httpDelete = new HttpDelete(HOST_URL + "/engine/switches/activation"); response = + * client.execute(httpDelete); logger.info(httpDelete.getRequestLine() + + * " response code: {}", response.getStatusLine().getStatusCode()); assertEquals(200, + * response.getStatusLine().getStatusCode()); httpDelete.releaseConnection(); + */ + + /* + * PUT: /engine/tools/loggers/logger/level + */ + httpPut = new HttpPut(HOST_URL + "/engine/tools/loggers/ROOT/debug"); + response = client.execute(httpPut); + logger.info(httpPut.getRequestLine() + "response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpPut.releaseConnection(); } - return null; - } - private static void cleanUpWorkingDirs() throws IOException { - final Path testControllerPath = - Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), FOO_CONTROLLER_FILE); - final Path testControllerBakPath = Paths - .get(SystemPersistence.manager.getConfigurationPath().toString(), FOO_CONTROLLER_FILE_BAK); + @Test + public void getTest() throws ClientProtocolException, IOException, InterruptedException { + HttpGet httpGet; + CloseableHttpResponse response; + String responseBody; + + /* + * GET: /engine /engine/features /engine/features/inventory /engine/features/featurename + * /engine/inputs /engine/properties /engine/environment /engine/switches + * /engine/controllers + */ + httpGet = new HttpGet(HOST_URL + "/engine"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/features"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/features/inventory"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/features/foobar"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/inputs"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/properties"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/environment"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + PolicyEngine.manager.setEnvironmentProperty("foo", "bar"); + httpGet = new HttpGet(HOST_URL + "/engine/environment/foo"); + response = client.execute(httpGet); + responseBody = this.getResponseBody(response); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + logger.info(httpGet.getRequestLine() + " response body: {}", responseBody); + assertEquals(200, response.getStatusLine().getStatusCode()); + assertEquals("bar", responseBody); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/switches"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers"); + response = client.execute(httpGet); + responseBody = this.getResponseBody(response); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + logger.info(httpGet.getRequestLine() + " response body: {}", responseBody); + assertEquals(200, response.getStatusLine().getStatusCode()); + assertEquals("[\"" + FOO_CONTROLLER + "\"]", responseBody); + httpGet.releaseConnection(); + + /* + * GET: /engine/controllers/inventory /engine/controllers/features + * /engine/controllers/features/inventory /engine/controllers/features/featureName + * /engine/controllers/controllerName + * + */ + httpGet = new HttpGet(HOST_URL + "/engine/controllers/inventory"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/features"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/features/inventory"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/features/dummy"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + /* + * GET: /engine/controllers/controllerName/properties + * /engine/controllers/controllerName/inputs /engine/controllers/controllerName/switches + * /engine/controllers/controllerName/drools + */ + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/properties"); + response = client.execute(httpGet); + responseBody = this.getResponseBody(response); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + logger.info(httpGet.getRequestLine() + " response code: {}", responseBody); + assertEquals(200, response.getStatusLine().getStatusCode()); + assertEquals("{}", responseBody); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/properties"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/inputs"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/switches"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/drools"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + /* + * GET: /engine/controllers/controllerName/drools/facts + * /engine/controllers/controllerName/drools/facts/session + * /engine/controllers/controllerName/drools/facts/session/factType + * /engine/controllers/controllerName/drools/facts/session/query/queriedEntity + * + */ + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/drools/facts"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts/session"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts/session/factType"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet( + HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/drools/facts/session/query/queriedEntity"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/dummy" + "/drools/facts/session/query/queriedEntity"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + + /* + * GET: /engine/controllers/controllerName/decoders + * /engine/controllers/controllerName/decoders/filters + * /engine/controllers/controllerName/decoders/topic + * /engine/controllers/controllerName/decoders/topic/filters + * /engine/controllers/controllerName/decoders/topic/filters/factType + * /engine/controllers/controllerName/decoders/topic/filters/factType/rules + * /engine/controllers/controllerName/decoders/topic/filtes/factType/rules/ruleName + * /engine/controllers/controllerName/encoders + */ + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/decoders"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/filters"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/nonexistantcontroller/decoders/filters"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic/filters"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic/filters/factType"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet( + HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic/filters/factType/rules"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet( + HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/decoders/topic/filters/factType/rules/ruleName"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(404, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/controllers/" + FOO_CONTROLLER + "/encoders"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + /* + * GET: /engine/topics /engine/topics/switches /engine/topics/sources /engine/topics/sinks + * /engine/topics/sinks/ueb /engine/topics/sources/ueb /engine/topics/sinks/dmaap + * /engine/topics/sources/dmaap /engine/topics/sinks/ueb/topic + * /engine/topics/sources/ueb/topic /engine/topics/sinks/dmaap/topic + * /engine/topics/sources/dmaap/topic /engine/topics/sinks/ueb/topic/events + * /engine/topics/sources/ueb/topic/events /engine/topics/sinks/dmaap/topic/events + * /engine/topics/sources/dmaap/topic/events /engine/topics/sources/ueb/topic/switches + * /engine/topics/sources/dmaap/topic/switches + */ + httpGet = new HttpGet(HOST_URL + "/engine/topics"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/switches"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/foobar"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/" + UEB_TOPIC); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/foobar"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/foobar"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/" + DMAAP_TOPIC); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/foobar"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/events"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/foobar/events"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/" + UEB_TOPIC + "/events"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/ueb/foobar/events"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/events"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/foobar/events"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/" + DMAAP_TOPIC + "/events"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/dmaap/foobar/events"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(500, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/ueb/" + UEB_TOPIC + "/switches"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sources/dmaap/" + DMAAP_TOPIC + "/switches"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + /* + * GET: /engine/topics/sinks/noop /engine/topics/sinks/noop/topic + * /engine/topics/sinks/noop/topic/events + */ + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/noop"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/noop/" + NOOP_TOPIC); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/topics/sinks/noop/" + NOOP_TOPIC + "/events"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + /* + * GET: /engine/tools/uuid /engine/tools/loggers /engine/tools/loggers/loggerName + */ + httpGet = new HttpGet(HOST_URL + "/engine/tools/uuid"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/tools/loggers"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + httpGet = new HttpGet(HOST_URL + "/engine/tools/loggers/ROOT"); + response = client.execute(httpGet); + logger.info(httpGet.getRequestLine() + " response code: {}", response.getStatusLine().getStatusCode()); + assertEquals(200, response.getStatusLine().getStatusCode()); + httpGet.releaseConnection(); + + } - Files.deleteIfExists(testControllerPath); - Files.deleteIfExists(testControllerBakPath); - } + + public String getResponseBody(CloseableHttpResponse response) { + + HttpEntity entity; + try { + entity = response.getEntity(); + return EntityUtils.toString(entity); + + } catch (final IOException e) { + + } + + return null; + } + + private static void cleanUpWorkingDirs() throws IOException { + final Path testControllerPath = + Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), FOO_CONTROLLER_FILE); + final Path testControllerBakPath = + Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), FOO_CONTROLLER_FILE_BAK); + + Files.deleteIfExists(testControllerPath); + Files.deleteIfExists(testControllerBakPath); + } } diff --git a/policy-management/src/test/java/org/onap/policy/drools/system/test/PolicyEngineTest.java b/policy-management/src/test/java/org/onap/policy/drools/system/test/PolicyEngineTest.java index 38f4e9b8..88d25563 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/system/test/PolicyEngineTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/system/test/PolicyEngineTest.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.drools.system.test; import static org.junit.Assert.assertFalse; @@ -33,11 +34,12 @@ import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; -import org.onap.policy.drools.event.comm.TopicEndpoint; -import org.onap.policy.drools.event.comm.TopicSink; -import org.onap.policy.drools.event.comm.bus.NoopTopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.bus.impl.IndexedNoopTopicSinkFactory; +import org.onap.policy.common.endpoints.event.comm.impl.ProxyTopicEndpointManager; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; import org.onap.policy.drools.persistence.SystemPersistence; -import org.onap.policy.drools.properties.PolicyProperties; +import org.onap.policy.drools.properties.DroolsProperties; import org.onap.policy.drools.protocol.coders.EventProtocolCoder; import org.onap.policy.drools.protocol.coders.JsonProtocolFilter; import org.onap.policy.drools.protocol.configuration.DroolsConfiguration; @@ -52,236 +54,237 @@ import org.slf4j.LoggerFactory; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class PolicyEngineTest { - /** - * Default Telemetry port for JUnits - */ - public static final int DEFAULT_TELEMETRY_PORT = 9698; - - /** - * Test JUnit Controller Name - */ - public static final String TEST_CONTROLLER_NAME = "foo"; - - /** - * Controller Configuration File - */ - public static final String TEST_CONTROLLER_FILE = TEST_CONTROLLER_NAME + "-controller.properties"; - - /** - * Controller Configuration Backup File - */ - public static final String TEST_CONTROLLER_FILE_BAK = TEST_CONTROLLER_FILE + ".bak"; - - /** - * Coder Group - */ - private static final String ENCODER_GROUP = "foo"; - - /** - * Coder Artifact - */ - private static final String ENCODER_ARTIFACT = "bar"; - - /** - * Coder Version - */ - private static final String ENCODER_VERSION = null; - - /** - * noop topic - */ - private static final String NOOP_TOPIC = "JUNIT"; - - /** - * logger - */ - private static Logger logger = LoggerFactory.getLogger(PolicyEngineTest.class); - - /** - * clean up working directory - */ - protected static void cleanUpWorkingDir() { - final Path testControllerPath = Paths - .get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE); - try { - Files.deleteIfExists(testControllerPath); - } catch (final Exception e) { - logger.info("Problem cleaning {}", testControllerPath, e); - } - - final Path testControllerBakPath = Paths - .get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE_BAK); - try { - Files.deleteIfExists(testControllerBakPath); - } catch (final Exception e) { - logger.info("Problem cleaning {}", testControllerBakPath, e); + /** + * Default Telemetry port for JUnits + */ + public static final int DEFAULT_TELEMETRY_PORT = 9698; + + /** + * Test JUnit Controller Name + */ + public static final String TEST_CONTROLLER_NAME = "foo"; + + /** + * Controller Configuration File + */ + public static final String TEST_CONTROLLER_FILE = TEST_CONTROLLER_NAME + "-controller.properties"; + + /** + * Controller Configuration Backup File + */ + public static final String TEST_CONTROLLER_FILE_BAK = TEST_CONTROLLER_FILE + ".bak"; + + /** + * Coder Group + */ + private static final String ENCODER_GROUP = "foo"; + + /** + * Coder Artifact + */ + private static final String ENCODER_ARTIFACT = "bar"; + + /** + * Coder Version + */ + private static final String ENCODER_VERSION = null; + + /** + * noop topic + */ + private static final String NOOP_TOPIC = "JUNIT"; + + /** + * logger + */ + private static Logger logger = LoggerFactory.getLogger(PolicyEngineTest.class); + + /** + * clean up working directory + */ + protected static void cleanUpWorkingDir() { + final Path testControllerPath = + Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE); + try { + Files.deleteIfExists(testControllerPath); + } catch (final Exception e) { + logger.info("Problem cleaning {}", testControllerPath, e); + } + + final Path testControllerBakPath = + Paths.get(SystemPersistence.manager.getConfigurationPath().toString(), TEST_CONTROLLER_FILE_BAK); + try { + Files.deleteIfExists(testControllerBakPath); + } catch (final Exception e) { + logger.info("Problem cleaning {}", testControllerBakPath, e); + } } - } - @BeforeClass - public static void startUp() throws IOException { - logger.info("enter"); + @BeforeClass + public static void startUp() throws IOException { + logger.info("enter"); - cleanUpWorkingDir(); + cleanUpWorkingDir(); - /* ensure presence of config directory */ - final Path configDir = Paths.get(SystemPersistence.DEFAULT_CONFIGURATION_DIR); - if (Files.notExists(configDir)) - Files.createDirectories(configDir); - } + /* ensure presence of config directory */ + final Path configDir = Paths.get(SystemPersistence.DEFAULT_CONFIGURATION_DIR); + if (Files.notExists(configDir)) { + Files.createDirectories(configDir); + } + } - @AfterClass - public static void tearDown() throws IOException { - logger.info("enter"); - cleanUpWorkingDir(); - } + @AfterClass + public static void tearDown() throws IOException { + logger.info("enter"); + cleanUpWorkingDir(); + } - @Test - public void test100Configure() { - logger.info("enter"); + @Test + public void test100Configure() { + logger.info("enter"); - final Properties engineProps = PolicyEngine.manager.defaultTelemetryConfig(); + final Properties engineProps = PolicyEngine.manager.defaultTelemetryConfig(); - /* override default port */ - engineProps.put(PolicyProperties.PROPERTY_HTTP_SERVER_SERVICES + "." - + PolicyEngine.TELEMETRY_SERVER_DEFAULT_NAME + PolicyProperties.PROPERTY_HTTP_PORT_SUFFIX, - "" + DEFAULT_TELEMETRY_PORT); + /* override default port */ + engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + + PolicyEngine.TELEMETRY_SERVER_DEFAULT_NAME + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, + "" + DEFAULT_TELEMETRY_PORT); - assertFalse(PolicyEngine.manager.isAlive()); - PolicyEngine.manager.configure(engineProps); - assertFalse(PolicyEngine.manager.isAlive()); + assertFalse(PolicyEngine.manager.isAlive()); + PolicyEngine.manager.configure(engineProps); + assertFalse(PolicyEngine.manager.isAlive()); - logger.info("policy-engine {} has configuration {}", PolicyEngine.manager, engineProps); - } + logger.info("policy-engine {} has configuration {}", PolicyEngine.manager, engineProps); + } - @Test - public void test200Start() { - logger.info("enter"); + @Test + public void test200Start() { + logger.info("enter"); - PolicyEngine.manager.start(); + PolicyEngine.manager.start(); - assertTrue(PolicyEngine.manager.isAlive()); - assertFalse(PolicyEngine.manager.isLocked()); - assertFalse(PolicyEngine.manager.getHttpServers().isEmpty()); - assertTrue(PolicyEngine.manager.getHttpServers().get(0).isAlive()); - } + assertTrue(PolicyEngine.manager.isAlive()); + assertFalse(PolicyEngine.manager.isLocked()); + assertFalse(PolicyEngine.manager.getHttpServers().isEmpty()); + assertTrue(PolicyEngine.manager.getHttpServers().get(0).isAlive()); + } - @Test - public void test300Lock() { - logger.info("enter"); + @Test + public void test300Lock() { + logger.info("enter"); - PolicyEngine.manager.lock(); + PolicyEngine.manager.lock(); - assertTrue(PolicyEngine.manager.isAlive()); - assertTrue(PolicyEngine.manager.isLocked()); - assertFalse(PolicyEngine.manager.getHttpServers().isEmpty()); - assertTrue(PolicyEngine.manager.getHttpServers().get(0).isAlive()); - } + assertTrue(PolicyEngine.manager.isAlive()); + assertTrue(PolicyEngine.manager.isLocked()); + assertFalse(PolicyEngine.manager.getHttpServers().isEmpty()); + assertTrue(PolicyEngine.manager.getHttpServers().get(0).isAlive()); + } - @Test - public void test301Unlock() { - logger.info("enter"); + @Test + public void test301Unlock() { + logger.info("enter"); - PolicyEngine.manager.unlock(); + PolicyEngine.manager.unlock(); - assertTrue(PolicyEngine.manager.isAlive()); - assertFalse(PolicyEngine.manager.isLocked()); - assertFalse(PolicyEngine.manager.getHttpServers().isEmpty()); - assertTrue(PolicyEngine.manager.getHttpServers().get(0).isAlive()); - } + assertTrue(PolicyEngine.manager.isAlive()); + assertFalse(PolicyEngine.manager.isLocked()); + assertFalse(PolicyEngine.manager.getHttpServers().isEmpty()); + assertTrue(PolicyEngine.manager.getHttpServers().get(0).isAlive()); + } - @Test - public void test350TopicDeliver() { - final Properties noopSinkProperties = new Properties(); - noopSinkProperties.put(PolicyProperties.PROPERTY_NOOP_SINK_TOPICS, NOOP_TOPIC); + @Test + public void test350TopicDeliver() { + final Properties noopSinkProperties = new Properties(); + noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, NOOP_TOPIC); - TopicEndpoint.manager.addTopicSinks(noopSinkProperties).get(0).start(); + ProxyTopicEndpointManager.getInstance().addTopicSinks(noopSinkProperties).get(0).start(); - EventProtocolCoder.manager.addEncoder(ENCODER_GROUP, ENCODER_ARTIFACT, NOOP_TOPIC, - DroolsConfiguration.class.getCanonicalName(), new JsonProtocolFilter(), null, null, - DroolsConfiguration.class.getName().hashCode()); + EventProtocolCoder.manager.addEncoder(ENCODER_GROUP, ENCODER_ARTIFACT, NOOP_TOPIC, + DroolsConfiguration.class.getCanonicalName(), new JsonProtocolFilter(), null, null, + DroolsConfiguration.class.getName().hashCode()); - assertTrue(PolicyEngine.manager.deliver(NOOP_TOPIC, - new DroolsConfiguration(ENCODER_GROUP, ENCODER_ARTIFACT, ENCODER_VERSION))); + assertTrue(PolicyEngine.manager.deliver(NOOP_TOPIC, + new DroolsConfiguration(ENCODER_GROUP, ENCODER_ARTIFACT, ENCODER_VERSION))); - final TopicSink sink = NoopTopicSink.factory.get(NOOP_TOPIC); - assertTrue(sink.getRecentEvents()[0].contains(ENCODER_GROUP)); - assertTrue(sink.getRecentEvents()[0].contains(ENCODER_ARTIFACT)); + final TopicSink sink = IndexedNoopTopicSinkFactory.getInstance().get(NOOP_TOPIC); + assertTrue(sink.getRecentEvents()[0].contains(ENCODER_GROUP)); + assertTrue(sink.getRecentEvents()[0].contains(ENCODER_ARTIFACT)); - EventProtocolCoder.manager.removeEncoders(ENCODER_GROUP, ENCODER_ARTIFACT, NOOP_TOPIC); - } + EventProtocolCoder.manager.removeEncoders(ENCODER_GROUP, ENCODER_ARTIFACT, NOOP_TOPIC); + } - @Test - public void test400ControllerAdd() throws Exception { - logger.info("enter"); + @Test + public void test400ControllerAdd() throws Exception { + logger.info("enter"); - final Properties controllerProperties = new Properties(); - controllerProperties.put(PolicyProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME); - PolicyEngine.manager.createPolicyController(TEST_CONTROLLER_NAME, controllerProperties); + final Properties controllerProperties = new Properties(); + controllerProperties.put(DroolsProperties.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME); + PolicyEngine.manager.createPolicyController(TEST_CONTROLLER_NAME, controllerProperties); - assertTrue(PolicyController.factory.inventory().size() == 1); - } + assertTrue(PolicyController.factory.inventory().size() == 1); + } - @Test - public void test401ControllerVerify() { - logger.info("enter"); + @Test + public void test401ControllerVerify() { + logger.info("enter"); - final PolicyController testController = PolicyController.factory.get(TEST_CONTROLLER_NAME); + final PolicyController testController = PolicyController.factory.get(TEST_CONTROLLER_NAME); - assertFalse(testController.isAlive()); - assertFalse(testController.isLocked()); + assertFalse(testController.isAlive()); + assertFalse(testController.isLocked()); - testController.start(); + testController.start(); - assertTrue(testController.isAlive()); - assertFalse(testController.isLocked()); - } + assertTrue(testController.isAlive()); + assertFalse(testController.isLocked()); + } - @Test - public void test500Deactivate() throws Exception { - logger.info("enter"); + @Test + public void test500Deactivate() throws Exception { + logger.info("enter"); - PolicyEngine.manager.deactivate(); + PolicyEngine.manager.deactivate(); - final PolicyController testController = PolicyController.factory.get(TEST_CONTROLLER_NAME); - assertFalse(testController.isAlive()); - assertTrue(testController.isLocked()); - assertTrue(PolicyEngine.manager.isLocked()); - assertTrue(PolicyEngine.manager.isAlive()); - } + final PolicyController testController = PolicyController.factory.get(TEST_CONTROLLER_NAME); + assertFalse(testController.isAlive()); + assertTrue(testController.isLocked()); + assertTrue(PolicyEngine.manager.isLocked()); + assertTrue(PolicyEngine.manager.isAlive()); + } - @Test - public void test501Activate() throws Exception { - logger.info("enter"); + @Test + public void test501Activate() throws Exception { + logger.info("enter"); - PolicyEngine.manager.activate(); + PolicyEngine.manager.activate(); - final PolicyController testController = PolicyController.factory.get(TEST_CONTROLLER_NAME); - assertTrue(testController.isAlive()); - assertFalse(testController.isLocked()); - assertFalse(PolicyEngine.manager.isLocked()); - assertTrue(PolicyEngine.manager.isAlive()); - } + final PolicyController testController = PolicyController.factory.get(TEST_CONTROLLER_NAME); + assertTrue(testController.isAlive()); + assertFalse(testController.isLocked()); + assertFalse(PolicyEngine.manager.isLocked()); + assertTrue(PolicyEngine.manager.isAlive()); + } - @Test - public void test900ControllerRemove() throws Exception { - logger.info("enter"); + @Test + public void test900ControllerRemove() throws Exception { + logger.info("enter"); - PolicyEngine.manager.removePolicyController(TEST_CONTROLLER_NAME); - assertTrue(PolicyController.factory.inventory().isEmpty()); - } + PolicyEngine.manager.removePolicyController(TEST_CONTROLLER_NAME); + assertTrue(PolicyController.factory.inventory().isEmpty()); + } - @Test - public void test901Stop() throws InterruptedException { - logger.info("enter"); + @Test + public void test901Stop() throws InterruptedException { + logger.info("enter"); - /* Shutdown managed resources */ - PolicyController.factory.shutdown(); - TopicEndpoint.manager.shutdown(); - PolicyEngine.manager.stop(); + /* Shutdown managed resources */ + PolicyController.factory.shutdown(); + ProxyTopicEndpointManager.getInstance().shutdown(); + PolicyEngine.manager.stop(); - Thread.sleep(10000L); - assertFalse(PolicyEngine.manager.isAlive()); - } + Thread.sleep(10000L); + assertFalse(PolicyEngine.manager.isAlive()); + } } diff --git a/policy-utils/pom.xml b/policy-utils/pom.xml index 649317f9..6a7c9fbd 100644 --- a/policy-utils/pom.xml +++ b/policy-utils/pom.xml @@ -42,6 +42,11 @@ <artifactId>junit</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>utils</artifactId> + <version>${project.version}</version> + </dependency> </dependencies> diff --git a/policy-utils/src/main/java/org/onap/policy/drools/utils/NetworkUtil.java b/policy-utils/src/main/java/org/onap/policy/drools/utils/NetworkUtil.java deleted file mode 100644 index 229927e5..00000000 --- a/policy-utils/src/main/java/org/onap/policy/drools/utils/NetworkUtil.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.drools.utils; - -import java.io.IOException; -import java.net.ConnectException; -import java.net.InetAddress; -import java.net.Socket; - -import java.net.UnknownHostException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Network Utilities - */ -public class NetworkUtil { - - public static final Logger logger = LoggerFactory.getLogger(NetworkUtil.class.getName()); - - /** - * IPv4 Wildcard IP address - */ - public static final String IPv4_WILDCARD_ADDRESS = "0.0.0.0"; - - private NetworkUtil() { - // Empty constructor - } - - /** - * try to connect to $host:$port $retries times while we are getting connection failures. - * - * @param host host - * @param port port - * @param retries number of attempts - * @return true is port is open, false otherwise - * @throws InterruptedException if execution has been interrupted - */ - public static boolean isTcpPortOpen(String host, int port, int retries, long interval) - throws InterruptedException, IOException { - int retry = 0; - while (retry < retries) { - try (Socket s = new Socket(host, port)) { - logger.debug("{}:{} connected - retries={} interval={}", host, port, retries, interval); - return true; - } catch (final ConnectException e) { - retry++; - logger.trace("{}:{} connected - retries={} interval={}", host, port, retries, interval, e); - Thread.sleep(interval); - } - } - - logger.warn("{}:{} closed = retries={} interval={}", host, port, retries, interval); - return false; - } - - /** - * gets host name - * - * @return host name - */ - public static String getHostname() { - - String hostname = System.getenv("HOSTNAME"); - if (hostname != null && !hostname.isEmpty()) { - return hostname; - } - - try { - return InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - logger.warn("cannot resolve local hostname", e); - /* continue */ - } - - return "localhost"; - } - - /** - * gets host's IP - * - * @return host IP - */ - public static String getHostIp() { - - try { - return InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e) { - logger.warn("cannot resolve local hostname", e); - /* continue */ - } - - return "127.0.0.1"; - } -} diff --git a/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MDCTransaction.java b/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MDCTransaction.java index 1a27dde6..39fbe8fb 100644 --- a/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MDCTransaction.java +++ b/policy-utils/src/main/java/org/onap/policy/drools/utils/logging/MDCTransaction.java @@ -24,7 +24,8 @@ import java.time.Duration; import java.time.Instant; import java.util.Date; import java.util.UUID; -import org.onap.policy.drools.utils.NetworkUtil; + +import org.onap.policy.common.utils.network.NetworkUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; @@ -32,51 +33,28 @@ import org.slf4j.MDC; /** * MDC Transaction Utility Class. * - * There is an implicit 2-level tree of Transactions in ONAP: transactions - * and subtransactions. + * There is an implicit 2-level tree of Transactions in ONAP: transactions and subtransactions. * - * 1. The top level transaction relates to the overarching transaction - * id (ie. RequestId) and should be made available to subtransactions - * for reuse in the ThreadLocal MDC structure. + * 1. The top level transaction relates to the overarching transaction id (ie. RequestId) and should + * be made available to subtransactions for reuse in the ThreadLocal MDC structure. * - * This is the data to be inherited and common to all subtransactions - * (not a common case but could be modified by subtransactions): + * This is the data to be inherited and common to all subtransactions (not a common case but could + * be modified by subtransactions): * - * Request ID - * Virtual Server Name - * Partner Name - * Server - * Server IP Address - * Server FQDN + * Request ID Virtual Server Name Partner Name Server Server IP Address Server FQDN * - * 2. The second level at the leaves is formed by subtransactions and the key - * identifier is the invocation id. + * 2. The second level at the leaves is formed by subtransactions and the key identifier is the + * invocation id. * - * Begin Timestamp - * End Timestamp - * Elapsed Time - * Service Instance ID - * Service Name - * Status Code - * Response Code - * Response Description - * Instance UUID - * Severity - * Target Entity - * Target Service Name - * Server - * Server IP Address - * Server FQDN - * Client IP Address - * Process Key - * Remote Host - * Alert Severity - * Target Virtual Entity + * Begin Timestamp End Timestamp Elapsed Time Service Instance ID Service Name Status Code Response + * Code Response Description Instance UUID Severity Target Entity Target Service Name Server Server + * IP Address Server FQDN Client IP Address Process Key Remote Host Alert Severity Target Virtual + * Entity * * * The naming convention for the fields must match the naming given at * - * https://wiki.onap.org/pages/viewpage.action?pageId=20087036 + * https://wiki.onap.org/pages/viewpage.action?pageId=20087036 */ public interface MDCTransaction { /* @@ -165,8 +143,8 @@ public interface MDCTransaction { String TARGET_SERVICE_NAME = "TargetServiceName"; /** - * Server Subtransactions inherit this value. if (this.getSources().size() == 1) - this.getSources().get(0).getTopic(); + * Server Subtransactions inherit this value. if (this.getSources().size() == 1) + * this.getSources().get(0).getTopic(); */ String SERVER = "Server"; @@ -246,16 +224,14 @@ public interface MDCTransaction { MDCTransaction flush(); /** - * convenience method to log a metric. Alternatively caller - * could call flush() and the logging statement directly for - * further granularity. + * convenience method to log a metric. Alternatively caller could call flush() and the logging + * statement directly for further granularity. */ MDCTransaction metric(); /** - * convenience method to log a transaction record. Alternatively caller - * could call flush() and the logging statement directly for - * further granularity. + * convenience method to log a transaction record. Alternatively caller could call flush() and + * the logging statement directly for further granularity. */ MDCTransaction transaction(); @@ -348,6 +324,7 @@ public interface MDCTransaction { * set virtual server */ MDCTransaction setVirtualServerName(String virtualServerName); + /** * sets end time */ @@ -549,6 +526,7 @@ public interface MDCTransaction { } + class MDCTransactionImpl implements MDCTransaction { private final static Logger logger = LoggerFactory.getLogger(MDCTransactionImpl.class.getName()); @@ -602,8 +580,8 @@ class MDCTransactionImpl implements MDCTransaction { /** * MDC Transaction * - * @param requestId transaction id - * @param partner transaction origin + * @param requestId transaction id + * @param partner transaction origin */ public MDCTransactionImpl(String requestId, String partner) { MDC.clear(); @@ -680,24 +658,24 @@ class MDCTransactionImpl implements MDCTransaction { */ @Override public MDCTransaction resetSubTransaction() { - MDC.remove(INVOCATION_ID); - MDC.remove(BEGIN_TIMESTAMP); - MDC.remove(END_TIMESTAMP); - MDC.remove(ELAPSED_TIME); - MDC.remove(SERVICE_INSTANCE_ID); - MDC.remove(STATUS_CODE); - MDC.remove(RESPONSE_CODE); - MDC.remove(RESPONSE_DESCRIPTION); - MDC.remove(INSTANCE_UUID); - MDC.remove(TARGET_ENTITY); - MDC.remove(TARGET_SERVICE_NAME); - MDC.remove(PROCESS_KEY); - MDC.remove(CLIENT_IP_ADDRESS); - MDC.remove(REMOTE_HOST); - MDC.remove(ALERT_SEVERITY); - MDC.remove(TARGET_VIRTUAL_ENTITY); - - return this; + MDC.remove(INVOCATION_ID); + MDC.remove(BEGIN_TIMESTAMP); + MDC.remove(END_TIMESTAMP); + MDC.remove(ELAPSED_TIME); + MDC.remove(SERVICE_INSTANCE_ID); + MDC.remove(STATUS_CODE); + MDC.remove(RESPONSE_CODE); + MDC.remove(RESPONSE_DESCRIPTION); + MDC.remove(INSTANCE_UUID); + MDC.remove(TARGET_ENTITY); + MDC.remove(TARGET_SERVICE_NAME); + MDC.remove(PROCESS_KEY); + MDC.remove(CLIENT_IP_ADDRESS); + MDC.remove(REMOTE_HOST); + MDC.remove(ALERT_SEVERITY); + MDC.remove(TARGET_VIRTUAL_ENTITY); + + return this; } @Override @@ -711,32 +689,41 @@ class MDCTransactionImpl implements MDCTransaction { */ @Override public MDCTransaction flush() { - if (this.requestId != null && !this.requestId.isEmpty()) + if (this.requestId != null && !this.requestId.isEmpty()) { MDC.put(REQUEST_ID, this.requestId); + } - if (this.invocationId != null && !this.invocationId.isEmpty()) + if (this.invocationId != null && !this.invocationId.isEmpty()) { MDC.put(INVOCATION_ID, this.invocationId); + } - if (this.partner != null) + if (this.partner != null) { MDC.put(PARTNER_NAME, this.partner); + } - if (this.virtualServerName != null) + if (this.virtualServerName != null) { MDC.put(VIRTUAL_SERVER_NAME, this.virtualServerName); + } - if (this.server != null) + if (this.server != null) { MDC.put(SERVER, this.server); + } - if (this.serverIpAddress != null) + if (this.serverIpAddress != null) { MDC.put(SERVER_IP_ADDRESS, this.serverIpAddress); + } - if (this.serverFqdn != null) + if (this.serverFqdn != null) { MDC.put(SERVER_FQDN, this.serverFqdn); + } - if (this.serviceName != null) + if (this.serviceName != null) { MDC.put(SERVICE_NAME, this.serviceName); + } - if (this.startTime != null) + if (this.startTime != null) { MDC.put(BEGIN_TIMESTAMP, timestamp(this.startTime)); + } if (this.endTime != null) { MDC.put(END_TIMESTAMP, timestamp(this.endTime)); @@ -749,49 +736,62 @@ class MDCTransactionImpl implements MDCTransaction { MDC.put(ELAPSED_TIME, String.valueOf(this.elapsedTime)); } else { if (endTime != null && startTime != null) { - this.elapsedTime = Duration.between(startTime, endTime).toMillis(); + this.elapsedTime = Duration.between(startTime, endTime).toMillis(); MDC.put(ELAPSED_TIME, String.valueOf(this.elapsedTime)); } } - if (this.serviceInstanceId != null) + if (this.serviceInstanceId != null) { MDC.put(SERVICE_INSTANCE_ID, this.serviceInstanceId); + } - if (this.instanceUUID != null) + if (this.instanceUUID != null) { MDC.put(INSTANCE_UUID, this.instanceUUID); + } - if (this.processKey != null) + if (this.processKey != null) { MDC.put(PROCESS_KEY, this.processKey); + } - if (this.statusCode != null) + if (this.statusCode != null) { MDC.put(STATUS_CODE, this.statusCode); + } - if (this.responseCode != null) + if (this.responseCode != null) { MDC.put(RESPONSE_CODE, this.responseCode); + } - if (this.responseDescription != null) + if (this.responseDescription != null) { MDC.put(RESPONSE_DESCRIPTION, this.responseDescription); + } - if (this.severity != null) + if (this.severity != null) { MDC.put(SEVERITY, this.severity); + } - if (this.alertSeverity != null) + if (this.alertSeverity != null) { MDC.put(ALERT_SEVERITY, this.alertSeverity); + } - if (this.targetEntity != null) + if (this.targetEntity != null) { MDC.put(TARGET_ENTITY, this.targetEntity); + } - if (this.targetServiceName != null) + if (this.targetServiceName != null) { MDC.put(TARGET_SERVICE_NAME, this.targetServiceName); + } - if (this.targetVirtualEntity != null) + if (this.targetVirtualEntity != null) { MDC.put(TARGET_VIRTUAL_ENTITY, this.targetVirtualEntity); + } - if (this.clientIpAddress != null) + if (this.clientIpAddress != null) { MDC.put(CLIENT_IP_ADDRESS, this.clientIpAddress); + } - if (this.remoteHost != null) + if (this.remoteHost != null) { MDC.put(REMOTE_HOST, this.remoteHost); + } return this; } diff --git a/policy-utils/src/test/java/org/onap/policy/drools/utils/NetworkUtilTest.java b/policy-utils/src/test/java/org/onap/policy/drools/utils/NetworkUtilTest.java deleted file mode 100644 index 406cdae9..00000000 --- a/policy-utils/src/test/java/org/onap/policy/drools/utils/NetworkUtilTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-utils - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.onap.policy.drools.utils; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - -import org.junit.Test; - -public class NetworkUtilTest { - - @Test - public void test() throws InterruptedException, IOException { - assertNotNull(NetworkUtil.IPv4_WILDCARD_ADDRESS); - assertFalse(NetworkUtil.isTcpPortOpen("localhost", 8080, 1, 5)); - assertNotNull(NetworkUtil.getHostname()); - assertNotNull(NetworkUtil.getHostIp()); - } - -} @@ -79,7 +79,6 @@ <modules> <module>policy-utils</module> <module>policy-core</module> - <module>policy-endpoints</module> <module>policy-management</module> <module>feature-healthcheck</module> <module>feature-eelf</module> |