diff options
14 files changed, 790 insertions, 440 deletions
diff --git a/feature-controller-logging/src/test/java/org/onap/policy/drools/controller/logging/ControllerLoggingTest.java b/feature-controller-logging/src/test/java/org/onap/policy/drools/controller/logging/ControllerLoggingTest.java index 82cfbd91..8c3e1c79 100755 --- a/feature-controller-logging/src/test/java/org/onap/policy/drools/controller/logging/ControllerLoggingTest.java +++ b/feature-controller-logging/src/test/java/org/onap/policy/drools/controller/logging/ControllerLoggingTest.java @@ -59,7 +59,7 @@ public class ControllerLoggingTest { private static final String JUNIT_KMODULE_DRL_PATH = "src/test/resources/test.drl"; private static final String JUNIT_KMODULE_POM_PATH = "src/test/resources/test.pom"; private static final String JUNIT_KMODULE_PATH = "src/test/resources/kmodule.xml"; - private static final String JUNIT_KJAR_DRL_PATH = "src/main/resources/org/onap/policy/drools/test/test.drl"; + private static final String JUNIT_KJAR_DRL_PATH = "src/main/resources/org/onap/policy/drools/test/"; /** * These properties are used for the Policy Controller to point to the test artifact. diff --git a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/ControllerSupport.java b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/ControllerSupport.java index e82eb42b..c6cf15c6 100644 --- a/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/ControllerSupport.java +++ b/feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/ControllerSupport.java @@ -42,7 +42,7 @@ public class ControllerSupport { protected static final String JUNIT_KMODULE_POM_PATH = "src/test/resources/lifecycle.pom"; protected static final String JUNIT_KMODULE_PATH = "src/test/resources/lifecycle.kmodule"; protected static final String JUNIT_KJAR_DRL_PATH = - "src/main/resources/kbLifecycle/org/onap/policy/drools/test/lifecycle.drl"; + "src/main/resources/kbLifecycle/org/onap/policy/drools/test/"; protected static final String POLICY_TYPE = "onap.policies.controlloop.Operational"; protected static final String POLICY_TYPE_VERSION = "1.0.0"; diff --git a/policy-core/src/main/java/org/onap/policy/drools/util/KieUtils.java b/policy-core/src/main/java/org/onap/policy/drools/util/KieUtils.java index 5500d110..babc0413 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/util/KieUtils.java +++ b/policy-core/src/main/java/org/onap/policy/drools/util/KieUtils.java @@ -22,10 +22,13 @@ package org.onap.policy.drools.util; import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; -import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import lombok.NonNull; import org.drools.compiler.kie.builder.impl.InternalKieModule; import org.drools.compiler.kproject.models.KieModuleModelImpl; import org.kie.api.KieServices; @@ -34,44 +37,52 @@ import org.kie.api.builder.KieFileSystem; import org.kie.api.builder.Message; import org.kie.api.builder.ReleaseId; import org.kie.api.builder.model.KieModuleModel; +import org.kie.api.definition.KiePackage; +import org.kie.api.definition.rule.Rule; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; import org.kie.scanner.KieMavenRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Kie related utilities. */ public class KieUtils { + private static final Logger logger = LoggerFactory.getLogger(KieUtils.class); + private KieUtils() { // Utility class } /** * Installs a rules artifact in the local maven repository. - * - * @param kmodule kmodule specification - * @param pom pom - * @param drlKJarPath path used in kjar drl to the actual drl - * @param drl rules in drl language - * - * @return releaseId result o a sucessful installation - * @throws IOException error accessing necessary resources */ - public static ReleaseId installArtifact(String kmodule, String pom, String drlKJarPath, - String drl) throws IOException { + public static ReleaseId installArtifact(File kmodule, File pom, String drlKJarPath, @NonNull List<File> drls) + throws IOException { KieModuleModel kieModule = KieModuleModelImpl.fromXML(kmodule); final KieFileSystem kieFileSystem = KieServices.Factory.get().newKieFileSystem(); kieFileSystem.writeKModuleXML(kieModule.toXML()); - kieFileSystem.writePomXML(pom); - kieFileSystem.write(drlKJarPath, drl); + kieFileSystem.writePomXML(new String(Files.readAllBytes(pom.toPath()))); + for (File drl : drls) { + kieFileSystem.write(drlKJarPath + drl.getName(), new String(Files.readAllBytes(drl.toPath()))); + } - KieBuilder kieBuilder = kieBuild(kieFileSystem); + KieBuilder kieBuilder = build(kieFileSystem); + return getReleaseId(kieBuilder, pom); + } - Path pomPath = Files.createTempFile("policy-core-", ".pom"); - Files.write(pomPath, pom.getBytes(StandardCharsets.UTF_8)); - File pomFile = pomPath.toFile(); - pomFile.deleteOnExit(); + /** + * Installs a rules artifact in the local maven repository. + */ + public static ReleaseId installArtifact(File kmodule, File pom, String drlKJarPath, File drl) + throws IOException { + return installArtifact(kmodule, pom, drlKJarPath, Collections.singletonList(drl)); + } + private static ReleaseId getReleaseId(KieBuilder kieBuilder, File pomFile) { ReleaseId releaseId = kieBuilder.getKieModule().getReleaseId(); KieMavenRepository .getKieMavenRepository() @@ -82,34 +93,65 @@ public class KieUtils { } /** - * Installs a rules artifact in the local maven repository. - * - * @param kmodule kmodule specification - * @param pom pom - * @param drlKJarPath path used in kjar drl to the actual drl - * @param drl rules in drl language - * - * @return releaseId result o a sucessful installation - * @throws IOException error accessing necessary resources + * Get Knowledge Bases. */ - public static ReleaseId installArtifact(File kmodule, File pom, String drlKJarPath, File drl) throws IOException { - KieModuleModel kieModule = KieModuleModelImpl.fromXML(kmodule); + public static List<String> getBases(KieContainer container) { + return new ArrayList<>(container.getKieBaseNames()); + } - final KieFileSystem kieFileSystem = KieServices.Factory.get().newKieFileSystem(); - kieFileSystem.writeKModuleXML(kieModule.toXML()); - kieFileSystem.writePomXML(new String(Files.readAllBytes(pom.toPath()))); - kieFileSystem.write(drlKJarPath, new String(Files.readAllBytes(drl.toPath()))); + /** + * Get Packages. + */ + public static List<KiePackage> getPackages(KieContainer container) { + return getBases(container).stream() + .flatMap(base -> container.getKieBase(base).getKiePackages().stream()) + .collect(Collectors.toList()); + } + + /** + * Get Package Names. + */ + public static List<String> getPackageNames(KieContainer container) { + return getPackages(container).stream() + .map(KiePackage::getName) + .collect(Collectors.toList()); + } - KieBuilder kieBuilder = kieBuild(kieFileSystem); + /** + * Get Rules. + */ + public static List<Rule> getRules(KieContainer container) { + return getPackages(container).stream() + .flatMap(kiePackage -> kiePackage.getRules().stream()) + .collect(Collectors.toList()); + } - ReleaseId releaseId = kieBuilder.getKieModule().getReleaseId(); - KieMavenRepository - .getKieMavenRepository() - .installArtifact(releaseId, (InternalKieModule) kieBuilder.getKieModule(), pom); - return releaseId; + /** + * Get Rule Names. + */ + public static List<String> getRuleNames(KieContainer container) { + return getRules(container).stream() + .map(Rule::getName) + .collect(Collectors.toList()); + } + + /** + * Get Facts. + */ + public static List<Object> getFacts(KieSession session) { + return session.getFactHandles().stream() + .map(session::getObject) + .collect(Collectors.toList()); + } + + /** + * Create Container. + */ + public static KieContainer createContainer(ReleaseId releaseId) { + return KieServices.Factory.get().newKieContainer(releaseId); } - private static KieBuilder kieBuild(KieFileSystem kieFileSystem) { + private static KieBuilder build(KieFileSystem kieFileSystem) { KieBuilder kieBuilder = KieServices.Factory.get().newKieBuilder(kieFileSystem); List<Message> messages = kieBuilder.buildAll().getResults().getMessages(); if (messages != null && !messages.isEmpty()) { diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java b/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java index d23bfd0c..d168ca8b 100644 --- a/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java +++ b/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-core * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -54,13 +54,13 @@ public class DroolsContainerTest { KieUtils.installArtifact( Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/META-INF/kmodule.xml").toFile(), Paths.get("src/test/resources/drools-artifact-1.1/pom.xml").toFile(), - "src/main/resources/rules/org/onap/policy/drools/core/test/rules.drl", + "src/main/resources/rules/org/onap/policy/drools/core/test/", Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/rules.drl").toFile()); KieUtils.installArtifact( Paths.get("src/test/resources/drools-artifact-1.2/src/main/resources/META-INF/kmodule.xml").toFile(), Paths.get("src/test/resources/drools-artifact-1.2/pom.xml").toFile(), - "src/main/resources/rules/org/onap/policy/drools/core/test/rules.drl", + "src/main/resources/rules/org/onap/policy/drools/core/test/", Paths.get("src/test/resources/drools-artifact-1.2/src/main/resources/rules.drl").toFile()); } diff --git a/policy-core/src/test/java/org/onap/policy/drools/util/KieUtilsTest.java b/policy-core/src/test/java/org/onap/policy/drools/util/KieUtilsTest.java new file mode 100644 index 00000000..83f62b32 --- /dev/null +++ b/policy-core/src/test/java/org/onap/policy/drools/util/KieUtilsTest.java @@ -0,0 +1,122 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 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.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.stream.Collectors; +import org.junit.BeforeClass; +import org.junit.Test; +import org.kie.api.builder.ReleaseId; +import org.kie.api.definition.KiePackage; +import org.kie.api.definition.rule.Rule; +import org.kie.api.runtime.KieContainer; +import org.kie.api.runtime.KieSession; + +/** + * Kie Utils Tests. + */ +public class KieUtilsTest { + + private static KieContainer container; + private static KieSession session; + + /** + * Test class initialization. + */ + @BeforeClass + public static void createArtifact() throws Exception { + ReleaseId releaseId = + KieUtils.installArtifact( + Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/META-INF/kmodule.xml").toFile(), + Paths.get("src/test/resources/drools-artifact-1.1/pom.xml").toFile(), + "src/main/resources/rules/org/onap/policy/drools/core/test/", + Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/rules.drl").toFile()); + + container = KieUtils.createContainer(releaseId); + session = container.getKieBase("rules").newKieSession(); + } + + @Test + public void installArtifact() throws IOException { + ReleaseId releaseId = + KieUtils.installArtifact( + Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/META-INF/kmodule.xml").toFile(), + Paths.get("src/test/resources/drools-artifact-1.1/pom.xml").toFile(), + "src/main/resources/rules/org/onap/policy/drools/core/test/", + Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/rules.drl").toFile()); + + assertNotNull(releaseId); + } + + @Test + public void installArtifactList() throws IOException { + ReleaseId releaseId = + KieUtils.installArtifact( + Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/META-INF/kmodule.xml").toFile(), + Paths.get("src/test/resources/drools-artifact-1.1/pom.xml").toFile(), + "src/main/resources/rules/org/onap/policy/drools/core/test/", + Collections.singletonList( + Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/rules.drl").toFile())); + + assertNotNull(releaseId); + } + + @Test + public void getBases() { + assertEquals(Collections.singletonList("rules"), KieUtils.getBases(container)); + } + + @Test + public void getPackages() { + assertEquals(Arrays.asList("java.util", "java.util.concurrent", "org.onap.policy.drools.core.test"), + KieUtils.getPackages(container) .stream().map(KiePackage::getName).collect(Collectors.toList())); + } + + @Test + public void getPackageNames() { + assertEquals(Arrays.asList("java.util", "java.util.concurrent", "org.onap.policy.drools.core.test"), + new ArrayList<>(KieUtils.getPackageNames(container))); + } + + @Test + public void getRules() { + assertEquals(Arrays.asList("Initialization", "Add elements of an int list"), + KieUtils.getRules(container).stream().map(Rule::getName).collect(Collectors.toList())); + } + + @Test + public void getRuleNames() { + assertEquals(Arrays.asList("Initialization", "Add elements of an int list"), + KieUtils.getRuleNames(container).stream().collect(Collectors.toList())); + } + + @Test + public void getFacts() { + assertEquals(0, KieUtils.getFacts(session).size()); + } +}
\ No newline at end of file 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 8b807387..cd3951d7 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 @@ -36,6 +36,8 @@ import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; +import java.util.function.Function; +import java.util.function.Supplier; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; @@ -590,17 +592,14 @@ public class RestManager { 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(PolicyControllerConstants.getFactory().get(controllerName)).build(); - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); - } + + return catchArgStateGenericEx( + () -> Response.status(Response.Status.OK) + .entity(PolicyControllerConstants.getFactory().get(controllerName)).build(), + e -> { + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return (controllerName); + }); } /** @@ -665,17 +664,15 @@ public class RestManager { 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 { + + return catchArgStateGenericEx(() -> { final PolicyController controller = PolicyControllerConstants.getFactory().get(controllerName); return Response.status(Response.Status.OK).entity(controller.getProperties()).build(); - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); - } + + }, e -> { + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return (controllerName); + }); } /** @@ -712,26 +709,21 @@ public class RestManager { .entity("A valid or matching controller names must be provided").build(); } - PolicyController controller; - try { - controller = PolicyEngineConstants.getManager().updatePolicyController(controllerConfiguration); + return catchArgStateGenericEx(() -> { + PolicyController controller = + PolicyEngineConstants.getManager().updatePolicyController(controllerConfiguration); if (controller == null) { return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + DOES_NOT_EXIST_MSG)).build(); + .entity(new Error(controllerName + DOES_NOT_EXIST_MSG)).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_MSG)).build(); - } - return Response.status(Response.Status.OK).entity(controller).build(); + return Response.status(Response.Status.OK).entity(controller).build(); + + }, e -> { + logger.info("{}: cannot update policy-controller {} because of {}", this, controllerName, + e.getMessage(), e); + return (controllerName); + }); } /** @@ -808,17 +800,15 @@ public class RestManager { 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 { + + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); return Response.status(Response.Status.OK).entity(drools).build(); - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); - } + + }, e -> { + logger.debug(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e); + return (controllerName); + }); } /** @@ -836,21 +826,19 @@ public class RestManager { 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 { + + return catchArgStateGenericEx(() -> { 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(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); - } + return sessionCounts; + + }, e -> { + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return controllerName; + }); } /** @@ -869,17 +857,15 @@ public class RestManager { 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 { + + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); - return Response.status(Response.Status.OK).entity(drools.factClassNames(sessionName)).build(); - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_DROOLS_FAILED, 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(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + sessionName + NOT_ACCEPTABLE_MSG)).build(); - } + return drools.factClassNames(sessionName); + + }, e -> { + logger.debug(FETCH_DROOLS_FAILED, this, controllerName, e.getMessage(), e); + return (controllerName + ":" + sessionName); + }); } /** @@ -902,24 +888,16 @@ public class RestManager { @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 { + + return catchArgStateGenericEx(() -> { 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(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + sessionName + ":" + factType + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + sessionName + ":" + factType + NOT_ACCEPTABLE_MSG)) - .build(); - } + return (count ? facts.size() : facts); + + }, e -> { + logger.debug(FETCH_POLICY_BY_NAME_FAILED, this, controllerName, e.getMessage(), e); + return (controllerName + ":" + sessionName + ":" + factType); + }); } /** @@ -946,33 +924,17 @@ public class RestManager { @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 { + + return catchArgStateGenericEx(() -> { 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(FETCH_DROOLS_BY_ENTITY_FAILED, this, - controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + NOT_FOUND_MSG)) - .build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_DROOLS_BY_ENTITY_FAILED, this, - controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error( - controllerName + ":" + sessionName + ":" + queryName + queriedEntity + NOT_ACCEPTABLE_MSG)) - .build(); - } catch (final Exception e) { - logger.debug(FETCH_DROOLS_BY_ENTITY_FAILED, this, - controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); - } + return (count ? facts.size() : facts); + + }, e -> { + logger.debug(FETCH_DROOLS_BY_ENTITY_FAILED, this, + controllerName, sessionName, queryName, queriedEntity, e.getMessage(), e); + return (controllerName + ":" + sessionName + ":" + queryName + queriedEntity); + }); } /** @@ -999,37 +961,20 @@ public class RestManager { required = true) @PathParam("queriedEntity") String queriedEntity, @ApiParam(value = "Query Parameter Values to pass in the DRL Query", required = false) List<Object> queryParameters) { - try { + + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); - List<Object> facts; if (queryParameters == null || queryParameters.isEmpty()) { - facts = drools.factQuery(sessionName, queryName, queriedEntity, false); + return drools.factQuery(sessionName, queryName, queriedEntity, false); } else { - facts = drools.factQuery(sessionName, queryName, queriedEntity, false, queryParameters.toArray()); + return drools.factQuery(sessionName, queryName, queriedEntity, false, queryParameters.toArray()); } - return Response.status(Response.Status.OK).entity(facts).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - FETCH_DROOLS_BY_PARAMS_FAILED, - 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_MSG)) - .build(); - } catch (final IllegalStateException e) { - logger.debug( - FETCH_DROOLS_BY_PARAMS_FAILED, - 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_MSG)) - .build(); - } catch (final Exception e) { - logger.debug( - FETCH_DROOLS_BY_PARAMS_FAILED, + + }, e -> { + logger.debug(FETCH_DROOLS_BY_PARAMS_FAILED, this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); - } + return (controllerName + ":" + sessionName + ":" + queryName + queriedEntity); + }); } /** @@ -1053,26 +998,16 @@ public class RestManager { @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 { + + return catchArgStateGenericEx(() -> { 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(FETCH_DROOLS_BY_FACTTYPE_FAILED, this, - controllerName, sessionName, factType, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + sessionName + ":" + factType + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_DROOLS_BY_FACTTYPE_FAILED, this, + return drools.facts(sessionName, factType, true); + + }, e -> { + logger.debug(FETCH_DROOLS_BY_FACTTYPE_FAILED, this, controllerName, sessionName, factType, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + sessionName + ":" + factType + NOT_ACCEPTABLE_MSG)) - .build(); - } catch (final Exception e) { - logger.debug(FETCH_DROOLS_BY_FACTTYPE_FAILED, this, - controllerName, sessionName, factType, e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); - } + return (controllerName + ":" + sessionName + ":" + factType); + }); } /** @@ -1100,37 +1035,20 @@ public class RestManager { required = true) @PathParam("queriedEntity") String queriedEntity, @ApiParam(value = "Query Parameter Values to pass in the DRL Query", required = false) List<Object> queryParameters) { - try { + + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); - List<Object> facts; if (queryParameters == null || queryParameters.isEmpty()) { - facts = drools.factQuery(sessionName, queryName, queriedEntity, true); + return drools.factQuery(sessionName, queryName, queriedEntity, true); } else { - facts = drools.factQuery(sessionName, queryName, queriedEntity, true, queryParameters.toArray()); + return drools.factQuery(sessionName, queryName, queriedEntity, true, queryParameters.toArray()); } - return Response.status(Response.Status.OK).entity(facts).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - FETCH_DROOLS_BY_PARAMS_FAILED, - 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_MSG)) - .build(); - } catch (final IllegalStateException e) { - logger.debug( - FETCH_DROOLS_BY_PARAMS_FAILED, - 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_MSG)) - .build(); - } catch (final Exception e) { - logger.debug( - FETCH_DROOLS_BY_PARAMS_FAILED, + + }, e -> { + logger.debug(FETCH_DROOLS_BY_PARAMS_FAILED, this, controllerName, sessionName, queryName, queriedEntity, queryParameters, e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); - } + return (controllerName + ":" + sessionName + ":" + queryName + queriedEntity); + }); } /** @@ -1165,21 +1083,16 @@ public class RestManager { 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 { + + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); - final List<ProtocolCoderToolset> decoders = - EventProtocolCoderConstants.getManager().getDecoders(drools.getGroupId(), drools.getArtifactId()); - return Response.status(Response.Status.OK).entity(decoders).build(); - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, + return EventProtocolCoderConstants.getManager().getDecoders(drools.getGroupId(), drools.getArtifactId()); + + }, e -> { + logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); - } + return (controllerName); + }); } /** @@ -1201,21 +1114,16 @@ public class RestManager { 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 { + + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); - final List<CoderFilters> filters = EventProtocolCoderConstants.getManager() + return EventProtocolCoderConstants.getManager() .getDecoderFilters(drools.getGroupId(), drools.getArtifactId()); - return Response.status(Response.Status.OK).entity(filters).build(); - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND).entity(new Error(controllerName + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + NOT_ACCEPTABLE_MSG)).build(); - } + + }, e -> { + logger.debug(FETCH_DECODERS_BY_POLICY_FAILED, this, controllerName, e.getMessage(), e); + return (controllerName); + }); } /** @@ -1237,22 +1145,16 @@ public class RestManager { 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 { + + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() + return EventProtocolCoderConstants.getManager() .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); - return Response.status(Response.Status.OK).entity(decoder).build(); - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + NOT_ACCEPTABLE_MSG)).build(); - } + + }, e -> { + logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e); + return (controllerName + ":" + topic); + }); } /** @@ -1275,7 +1177,8 @@ public class RestManager { 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 { + + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); @@ -1283,19 +1186,13 @@ public class RestManager { return Response.status(Response.Status.BAD_REQUEST).entity(new Error(topic + DOES_NOT_EXIST_MSG)) .build(); } else { - return Response.status(Response.Status.OK).entity(decoder.getCoders()).build(); + return decoder.getCoders(); } - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, - controllerName, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + NOT_ACCEPTABLE_MSG)).build(); - } + + }, e -> { + logger.debug(FETCH_DECODERS_BY_TOPIC_FAILED, this, controllerName, topic, e.getMessage(), e); + return (controllerName + ":" + topic); + }); } /** @@ -1319,7 +1216,8 @@ public class RestManager { @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 { + + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); @@ -1328,19 +1226,14 @@ public class RestManager { return Response.status(Response.Status.BAD_REQUEST) .entity(new Error(topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build(); } else { - return Response.status(Response.Status.OK).entity(filters).build(); + return filters; } - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this, - controllerName, topic, factClass, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this, - controllerName, topic, factClass, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_ACCEPTABLE_MSG)).build(); - } + + }, e -> { + logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this, + controllerName, topic, factClass, e.getMessage(), e); + return (controllerName + ":" + topic + ":" + factClass); + }); } /** @@ -1373,7 +1266,7 @@ public class RestManager { .build(); } - try { + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); @@ -1383,20 +1276,13 @@ public class RestManager { .entity(new Error(topic + ":" + factClass + DOES_NOT_EXIST_MSG)).build(); } filters.setFilter(configFilters); - return Response.status(Response.Status.OK).entity(filters).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - FETCH_DECODER_BY_FILTER_FAILED, - this, controllerName, topic, factClass, configFilters, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug( - FETCH_DECODER_BY_FILTER_FAILED, - this, controllerName, topic, factClass, configFilters, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_ACCEPTABLE_MSG)).build(); - } + return filters; + + }, e -> { + logger.debug(FETCH_DECODER_BY_FILTER_FAILED, + this, controllerName, topic, factClass, configFilters, e.getMessage(), e); + return (controllerName + ":" + topic + ":" + factClass); + }); } /** @@ -1418,7 +1304,8 @@ public class RestManager { @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 { + + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); @@ -1435,18 +1322,13 @@ public class RestManager { .entity(new Error(controllerName + ":" + topic + ":" + factClass + NO_FILTERS)).build(); } - return Response.status(Response.Status.OK).entity(filter.getRule()).build(); - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this, - controllerName, topic, factClass, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this, - controllerName, topic, factClass, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_ACCEPTABLE_MSG)).build(); - } + return filter.getRule(); + + }, e -> { + logger.debug(FETCH_DECODER_BY_TYPE_FAILED, this, + controllerName, topic, factClass, e.getMessage(), e); + return (controllerName + ":" + topic + ":" + factClass); + }); } /** @@ -1470,7 +1352,7 @@ public class RestManager { @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass) { - try { + return catchArgStateGenericEx(() -> { final DroolsController drools = this.getDroolsController(controllerName); final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); @@ -1488,23 +1370,13 @@ public class RestManager { } filter.setRule(null); - return Response.status(Response.Status.OK).entity(filter.getRule()).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - FETCH_DECODER_BY_TYPE_FAILED, - this, controllerName, topic, factClass, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + NOT_FOUND_MSG)) - .build(); - } catch (final IllegalStateException e) { - logger.debug( - FETCH_DECODER_BY_TYPE_FAILED, - this, controllerName, topic, factClass, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error( - controllerName + ":" + topic + ":" + factClass + NOT_ACCEPTABLE_MSG)) - .build(); - } + return filter.getRule(); + + }, e -> { + logger.debug(FETCH_DECODER_BY_TYPE_FAILED, + this, controllerName, topic, factClass, e.getMessage(), e); + return (controllerName + ":" + topic + ":" + factClass); + }); } /** @@ -1528,45 +1400,38 @@ public class RestManager { @ApiParam(value = "Fact Type", required = true) @PathParam("factType") String factClass, @ApiParam(value = "JsonPath filter expression", required = true) String rule) { - try { - final DroolsController drools = this.getDroolsController(controllerName); - final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() - .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); + return catchArgStateGenericEx(() -> decoderFilterRule2(controllerName, topic, factClass, rule), e -> { + logger.debug("{}: cannot access decoder filter rules for policy-controller {} " + + "topic {} type {} because of {}", + this, controllerName, topic, factClass, e.getMessage(), e); + return (controllerName + ":" + topic + ":" + factClass); + }); + } - 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_MSG)).build(); - } + private Object decoderFilterRule2(String controllerName, String topic, String factClass, String rule) { + final DroolsController drools = this.getDroolsController(controllerName); + final ProtocolCoderToolset decoder = EventProtocolCoderConstants.getManager() + .getDecoders(drools.getGroupId(), drools.getArtifactId(), topic); - final JsonProtocolFilter filter = filters.getFilter(); - if (filter == null) { - return Response.status(Response.Status.BAD_REQUEST) - .entity(new Error(controllerName + ":" + topic + ":" + factClass + NO_FILTERS)).build(); - } + 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_MSG)).build(); + } - if (rule == null || rule.isEmpty()) { - return Response.status(Response.Status.BAD_REQUEST).entity(new Error(controllerName + ":" + topic + ":" - + factClass + " no filter rule provided")).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(); + } - filter.setRule(rule); - return Response.status(Response.Status.OK).entity(filter.getRule()).build(); - } catch (final IllegalArgumentException e) { - logger.debug( - "{}: cannot access decoder filter rules 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 + NOT_FOUND_MSG)).build(); - } catch (final IllegalStateException e) { - logger.debug( - "{}: cannot access decoder filter rules 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_MSG)).build(); + if (rule == null || rule.isEmpty()) { + return Response.status(Response.Status.BAD_REQUEST).entity(new Error(controllerName + ":" + topic + ":" + + factClass + " no filter rule provided")).build(); } + + filter.setRule(rule); + return filter.getRule(); } /** @@ -1644,25 +1509,18 @@ public class RestManager { 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 { + + return catchArgStateGenericEx(() -> { final PolicyController controller = PolicyControllerConstants.getFactory().get(controllerName); final DroolsController drools = controller.getDrools(); - encoders = EventProtocolCoderConstants.getManager().getEncoderFilters(drools.getGroupId(), - drools.getArtifactId()); - } catch (final IllegalArgumentException e) { - logger.debug(FETCH_ENCODER_BY_FILTER_FAILED, 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(FETCH_ENCODER_BY_FILTER_FAILED, this, controllerName, - e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(controllerName + " is not accepting the request")).build(); - } + return EventProtocolCoderConstants.getManager() + .getEncoderFilters(drools.getGroupId(), drools.getArtifactId()); - return Response.status(Response.Status.OK).entity(encoders).build(); + }, e -> { + logger.debug(FETCH_ENCODER_BY_FILTER_FAILED, this, controllerName, + e.getMessage(), e); + return (controllerName); + }); } @GET @@ -2073,32 +1931,20 @@ public class RestManager { @ApiParam(value = "Topic Name", required = true) @PathParam("topic") String topic, @ApiParam(value = "Network Message", required = true) String json) { - try { - TopicSource source = - TopicEndpointManager.getManager().getTopicSource(CommInfrastructure.valueOf(comm.toUpperCase()), topic); + return catchArgStateGenericEx(() -> { + TopicSource source = TopicEndpointManager.getManager() + .getTopicSource(CommInfrastructure.valueOf(comm.toUpperCase()), topic); if (source.offer(json)) { - return Response.status(Status.OK) - .entity(Arrays.asList(source.getRecentEvents())) - .build(); + return Arrays.asList(source.getRecentEvents()); } else { - return Response.status(Status.NOT_ACCEPTABLE) - .entity(new Error("Failure to inject event over " + topic)) - .build(); + return Response.status(Status.NOT_ACCEPTABLE).entity(new Error("Failure to inject event over " + topic)) + .build(); } - } catch (IllegalArgumentException e) { - logger.debug(OFFER_FAILED, this, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_FOUND) - .entity(new Error(topic + NOT_FOUND_MSG)).build(); - } catch (IllegalStateException e) { - logger.debug(OFFER_FAILED, this, topic, e.getMessage(), e); - return Response.status(Response.Status.NOT_ACCEPTABLE) - .entity(new Error(topic + " not acceptable due to current state")) - .build(); - } catch (Exception e) { - logger.debug(OFFER_FAILED, this, topic, e.getMessage(), e); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())) - .build(); - } + + }, e -> { + logger.debug(OFFER_FAILED, this, topic, e.getMessage(), e); + return (topic); + }); } /** @@ -2218,6 +2064,40 @@ public class RestManager { return drools; } + /** + * Invokes a function and returns the generated response, catching illegal argument, + * illegal state, and generic runtime exceptions. + * + * @param responder function that will generate a response. If it returns a "Response" + * object, then that object is returned as-is. Otherwise, this method will + * return an "OK" Response, using the function's return value as the "entity" + * @param errorMsg function that will generate an error message prefix to be included + * in responses generated as a result of catching an exception + * @return a response + */ + private Response catchArgStateGenericEx(Supplier<Object> responder, Function<Exception, String> errorMsg) { + try { + Object result = responder.get(); + if (result instanceof Response) { + return (Response) result; + } + + return Response.status(Response.Status.OK).entity(result).build(); + + } catch (final IllegalArgumentException e) { + return Response.status(Response.Status.NOT_FOUND).entity(new Error(errorMsg.apply(e) + NOT_FOUND_MSG)) + .build(); + + } catch (final IllegalStateException e) { + return Response.status(Response.Status.NOT_ACCEPTABLE) + .entity(new Error(errorMsg.apply(e) + NOT_ACCEPTABLE_MSG)).build(); + + } catch (final RuntimeException e) { + errorMsg.apply(e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(new Error(e.getMessage())).build(); + } + } + /* * Helper classes for aggregation of results */ diff --git a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController3Test.java b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController3Test.java new file mode 100644 index 00000000..e237a455 --- /dev/null +++ b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsController3Test.java @@ -0,0 +1,145 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 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.controller.internal; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.kie.api.builder.ReleaseId; +import org.onap.policy.drools.controller.DroolsController; +import org.onap.policy.drools.util.KieUtils; +import org.onap.policy.drools.utils.logging.LoggerUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MavenDroolsController3Test { + private static final String DROOLS_RESOURCES_DIR = "src/test/resources/"; + private static final String DROOLS_KJAR_RESOURCES_DIR = "src/main/resources/"; + private static final String DRL_EXT = ".drl"; + private static final String POM_EXT = ".pom"; + private static final String KMODULE_EXT = ".kmodule"; + + private static final String RULES_BASE = "rules"; + private static final String KBNAME_RULES = "kbRules"; + private static final String KBSESSION_RULES = RULES_BASE; + private static final String KBPACKAGE_RULES = RULES_BASE; + + public static final CountDownLatch running1a = new CountDownLatch(1); + public static final CountDownLatch running1b = new CountDownLatch(1); + public static final CountDownLatch running2a = new CountDownLatch(1); + public static final CountDownLatch running2b = new CountDownLatch(1); + + private static final Logger logger = LoggerFactory.getLogger(MavenDroolsController3Test.class); + + private static ReleaseId install(String name, List<File> drls) throws IOException { + return + KieUtils.installArtifact( + Paths.get(DROOLS_RESOURCES_DIR + RULES_BASE + KMODULE_EXT).toFile(), + Paths.get(DROOLS_RESOURCES_DIR + name + POM_EXT).toFile(), + DROOLS_KJAR_RESOURCES_DIR + KBNAME_RULES + "/" + KBPACKAGE_RULES + "/", + drls); + } + + public static ReleaseId rulesDescriptor1; + public static ReleaseId rulesDescriptor2; + + /** + * Test Class Initialization. + */ + @BeforeClass + public static void setUpBeforeClass() throws IOException { + rulesDescriptor1 = + install("rules1", + Stream.of(Paths.get(DROOLS_RESOURCES_DIR + "rules1" + DRL_EXT).toFile()).collect(Collectors.toList())); + + rulesDescriptor2 = + install("rules2", + Stream.of(Paths.get(DROOLS_RESOURCES_DIR + "rules1" + DRL_EXT).toFile(), + Paths.get(DROOLS_RESOURCES_DIR + "rules2" + DRL_EXT).toFile()) + .collect(Collectors.toList())); + + LoggerUtil.setLevel("ROOT", "WARN"); + LoggerUtil.setLevel("org.onap.policy.drools.controller.internal", "INFO"); + } + + @Test + public void upgrades() throws InterruptedException { + DroolsController rules = + new MavenDroolsController( + rulesDescriptor1.getGroupId(), rulesDescriptor1.getArtifactId(), rulesDescriptor1.getVersion(), + null, null); + + assertTrue(rules.start()); + assertTrue(running1a.await(30, TimeUnit.SECONDS)); + summary(rules); + assertKie(rules, Arrays.asList("SETUP.1", "VERSION.12"), 1); + + rules.updateToVersion( + rulesDescriptor2.getGroupId(), + rulesDescriptor2.getArtifactId(), + rulesDescriptor2.getVersion(), + null, null); + + assertTrue(running2a.await(30, TimeUnit.SECONDS)); + assertTrue(running2b.await(30, TimeUnit.SECONDS)); + summary(rules); + assertKie(rules, Arrays.asList("SETUP.1", "VERSION.12", "SETUP.2", "VERSION.2"), 2); + + rules.updateToVersion( + rulesDescriptor1.getGroupId(), + rulesDescriptor1.getArtifactId(), + rulesDescriptor1.getVersion(), + null, null); + + assertTrue(running1b.await(30, TimeUnit.SECONDS)); + summary(rules); + assertKie(rules, Arrays.asList("SETUP.1", "VERSION.12"), 1); + } + + private void summary(DroolsController rules) { + logger.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + logger.info("Controller: " + rules.getGroupId() + ":" + rules.getArtifactId() + ":" + rules.getVersion()); + logger.info("....................................................................."); + logger.info("KIE-BASES: " + KieUtils.getBases(rules.getContainer().getKieContainer())); + logger.info("KIE-PACKAGE-NAMES: " + KieUtils.getPackageNames(rules.getContainer().getKieContainer())); + logger.info("KIE-RULE-NAMES: " + KieUtils.getRuleNames(rules.getContainer().getKieContainer())); + logger.info("FACTS: " + rules.facts(KBSESSION_RULES, Object.class)); + logger.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + } + + private void assertKie(DroolsController controller, List<String> expectedRuleNames, long expectedFactCount) { + assertEquals(Arrays.asList("kbRules"), KieUtils.getBases(controller.getContainer().getKieContainer())); + assertEquals(expectedRuleNames, KieUtils.getRuleNames(controller.getContainer().getKieContainer())); + assertEquals(expectedFactCount, controller.factCount(controller.getSessionNames().get(0))); + } +} diff --git a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerTest.java b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerTest.java index 0d8bdfab..e99e044a 100644 --- a/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerTest.java +++ b/policy-management/src/test/java/org/onap/policy/drools/controller/internal/MavenDroolsControllerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 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. @@ -34,17 +34,14 @@ import org.onap.policy.drools.controller.DroolsController; import org.onap.policy.drools.util.KieUtils; public class MavenDroolsControllerTest { - public static final String JUNIT_ECHO_KSESSION = "echo"; public static final String JUNIT_ECHO_KBASE = "onap.policies.test"; public static final String JUNIT_ECHO_KMODULE_DRL_PATH = "src/test/resources/echo.drl"; public static final String JUNIT_ECHO_KMODULE_POM_PATH = "src/test/resources/echo.pom"; public static final String JUNIT_ECHO_KMODULE_PATH = "src/test/resources/echo.kmodule"; - public static final String JUNIT_ECHO_KJAR_DRL_PATH = - "src/main/resources/kbEcho/org/onap/policy/drools/test/echo.drl"; + public static final String JUNIT_ECHO_KJAR_DRL_PATH = "src/main/resources/kbEcho/org/onap/policy/drools/test/"; private static volatile ReleaseId releaseId; - private static volatile CountDownLatch running; /** 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 7787a7b6..2bbb08bf 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 @@ -23,12 +23,11 @@ package org.onap.policy.drools.protocol.coders; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Properties; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.kie.api.builder.ReleaseId; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; @@ -45,45 +44,30 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * ProtocolCoder Toolset JUNITs. + * ProtocolCoder Toolset Junits. */ public class ProtocolCoderToolsetTest { public static final String JUNIT_PROTOCOL_CODER_ARTIFACT_ID = "protocolcoder"; 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>"; private static Logger logger = LoggerFactory.getLogger(ProtocolCoderToolset.class); - private volatile ReleaseId releaseId; + private static volatile ReleaseId releaseId; + // customCoder has to be public to be accessed in tests below public static final Gson customCoder = new GsonBuilder().create(); /** - * Setup. - * - * @throws IOException throws IO Exception + * Test Class Initialization. */ - @Before - public void setUp() throws IOException { - if (releaseId != null) { - return; - } - - String pom = new String(Files.readAllBytes(Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_POM_PATH))); - - 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 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))); - - releaseId = KieUtils.installArtifact(kmodule, newPom, MavenDroolsControllerTest.JUNIT_ECHO_KJAR_DRL_PATH, drl); + @BeforeClass + public static void setupClass() throws IOException { + releaseId = KieUtils.installArtifact( + Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_PATH).toFile(), + Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_POM_PATH).toFile(), + MavenDroolsControllerTest.JUNIT_ECHO_KJAR_DRL_PATH, + Paths.get(MavenDroolsControllerTest.JUNIT_ECHO_KMODULE_DRL_PATH).toFile()); } @Test diff --git a/policy-management/src/test/resources/rules.kmodule b/policy-management/src/test/resources/rules.kmodule new file mode 100644 index 00000000..4f3f8745 --- /dev/null +++ b/policy-management/src/test/resources/rules.kmodule @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + ONAP + ================================================================================ + Copyright (C) 2019 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========================================================= + --> + +<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule"> + <kbase name="kbRules"> + <ksession name="rules"/> + </kbase> +</kmodule>
\ No newline at end of file diff --git a/policy-management/src/test/resources/rules1.drl b/policy-management/src/test/resources/rules1.drl new file mode 100644 index 00000000..dd7051c6 --- /dev/null +++ b/policy-management/src/test/resources/rules1.drl @@ -0,0 +1,46 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 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 rules; + +import org.onap.policy.drools.controller.internal.MavenDroolsController3Test; + +declare Version + version : String +end + +rule "SETUP.1" +when +then + Version v1 = new Version(); + v1.setVersion("1"); + insert(v1); + + MavenDroolsController3Test.running1a.countDown(); +end + +rule "VERSION.12" +when + $v12 : Version( version == "12") +then + retract($v12); + + MavenDroolsController3Test.running1b.countDown(); +end
\ No newline at end of file diff --git a/policy-management/src/test/resources/rules1.pom b/policy-management/src/test/resources/rules1.pom new file mode 100644 index 00000000..74901bb7 --- /dev/null +++ b/policy-management/src/test/resources/rules1.pom @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + ONAP + ================================================================================ + Copyright (C) 2019 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> + + <groupId>org.onap.policy.drools.test</groupId> + <artifactId>rules</artifactId> + <version>1.0.0</version> +</project> diff --git a/policy-management/src/test/resources/rules2.drl b/policy-management/src/test/resources/rules2.drl new file mode 100644 index 00000000..22d56d0c --- /dev/null +++ b/policy-management/src/test/resources/rules2.drl @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2019 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 rules; + +declare Version + version : String +end + +rule "SETUP.2" +when +then + Version v2 = new Version(); + v2.setVersion("2"); + insert(v2); + + MavenDroolsController3Test.running2a.countDown(); +end + +rule "VERSION.2" +when + $v1 : Version( version == "1") +then + retract($v1); + + Version v12 = new Version(); + v12.setVersion("12"); + insert(v12); + + MavenDroolsController3Test.running2b.countDown(); +end diff --git a/policy-management/src/test/resources/rules2.pom b/policy-management/src/test/resources/rules2.pom new file mode 100644 index 00000000..a9fb151f --- /dev/null +++ b/policy-management/src/test/resources/rules2.pom @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + ONAP + ================================================================================ + Copyright (C) 2019 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> + + <groupId>org.onap.policy.drools.test</groupId> + <artifactId>rules</artifactId> + <version>2.0.0</version> +</project> |