Adding healthcheck endpoint to policy/pap 93/77793/2
authorramverma <ram.krishna.verma@est.tech>
Tue, 5 Feb 2019 10:28:22 +0000 (10:28 +0000)
committerramverma <ram.krishna.verma@est.tech>
Tue, 5 Feb 2019 10:28:22 +0000 (10:28 +0000)
1) Adding healthcheck REST endpoint to policy/pap using the
policy-endpoints module in policy/common.
2) Added the related unit test cases.

Change-Id: I6a215cceccc9cd42494aef1dfcdd46f0f3fd7d13
Issue-ID: POLICY-1477
Signed-off-by: ramverma <ram.krishna.verma@est.tech>
16 files changed:
main/pom.xml
main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java
main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterHandler.java
main/src/main/java/org/onap/policy/pap/main/parameters/RestServerParameters.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckProvider.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/pap/main/rest/PapRestController.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/pap/main/rest/PapRestServer.java [new file with mode: 0644]
main/src/main/java/org/onap/policy/pap/main/startstop/Main.java
main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java
main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java
main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java
main/src/test/java/org/onap/policy/pap/main/rest/TestPapRestServer.java [new file with mode: 0644]
main/src/test/resources/parameters/MinimumParameters.json
main/src/test/resources/parameters/PapConfigParameters.json
main/src/test/resources/parameters/PapConfigParameters_InvalidName.json
pom.xml

index e36c042..f9f4b39 100644 (file)
             <artifactId>utils</artifactId>
             <version>${policy.common.version}</version>
         </dependency>
+        <dependency>
+            <groupId>org.onap.policy.common</groupId>
+            <artifactId>policy-endpoints</artifactId>
+            <version>${policy.common.version}</version>
+        </dependency>
     </dependencies>
 
     <build>
index 01032c5..09f8704 100644 (file)
@@ -32,14 +32,17 @@ import org.onap.policy.common.utils.validation.ParameterValidationUtils;
  */
 public class PapParameterGroup implements ParameterGroup {
     private String name;
+    private RestServerParameters restServerParameters;
 
     /**
      * Create the pap parameter group.
      *
      * @param name the parameter group name
+     * @param restServerParameters the rest server parameters
      */
-    public PapParameterGroup(final String name) {
+    public PapParameterGroup(final String name, final RestServerParameters restServerParameters) {
         this.name = name;
+        this.restServerParameters = restServerParameters;
     }
 
     /**
@@ -62,6 +65,15 @@ public class PapParameterGroup implements ParameterGroup {
         this.name = name;
     }
 
+    /**
+     * Return the restServerParameters of this parameter group instance.
+     *
+     * @return the restServerParameters
+     */
+    public RestServerParameters getRestServerParameters() {
+        return restServerParameters;
+    }
+
     /**
      * Validate the parameter group.
      *
@@ -73,6 +85,12 @@ public class PapParameterGroup implements ParameterGroup {
         if (!ParameterValidationUtils.validateStringParameter(name)) {
             validationResult.setResult("name", ValidationStatus.INVALID, "must be a non-blank string");
         }
+        if (restServerParameters == null) {
+            validationResult.setResult("restServerParameters", ValidationStatus.INVALID,
+                    "must have restServerParameters to configure pap rest server");
+        } else {
+            validationResult.setResult("restServerParameters", restServerParameters.validate());
+        }
         return validationResult;
     }
 }
index f397dae..08124bb 100644 (file)
@@ -28,8 +28,8 @@ import java.io.FileReader;
 import org.onap.policy.common.parameters.GroupValidationResult;
 import org.onap.policy.pap.main.PolicyPapException;
 import org.onap.policy.pap.main.startstop.PapCommandLineArguments;
-import org.slf4j.ext.XLogger;
-import org.slf4j.ext.XLoggerFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * This class handles reading, parsing and validating of policy pap parameters from JSON files.
@@ -37,7 +37,8 @@ import org.slf4j.ext.XLoggerFactory;
  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
  */
 public class PapParameterHandler {
-    private static final XLogger LOGGER = XLoggerFactory.getXLogger(PapParameterHandler.class);
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(PapParameterHandler.class);
 
     /**
      * Read the parameters from the parameter file.
diff --git a/main/src/main/java/org/onap/policy/pap/main/parameters/RestServerParameters.java b/main/src/main/java/org/onap/policy/pap/main/parameters/RestServerParameters.java
new file mode 100644 (file)
index 0000000..cfc8832
--- /dev/null
@@ -0,0 +1,138 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.parameters;
+
+import org.onap.policy.common.parameters.GroupValidationResult;
+import org.onap.policy.common.parameters.ParameterGroup;
+import org.onap.policy.common.parameters.ValidationStatus;
+import org.onap.policy.common.utils.validation.ParameterValidationUtils;
+
+/**
+ * Class to hold all parameters needed for pap rest server.
+ *
+ * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
+ */
+public class RestServerParameters implements ParameterGroup {
+    private String name;
+    private String host;
+    private int port;
+    private String userName;
+    private String password;
+
+    /**
+     * Constructor for instantiating RestServerParameters.
+     *
+     * @param host the host name
+     * @param port the port
+     * @param userName the user name
+     * @param password the password
+     */
+    public RestServerParameters(final String host, final int port, final String userName, final String password) {
+        super();
+        this.host = host;
+        this.port = port;
+        this.userName = userName;
+        this.password = password;
+    }
+
+    /**
+     * Return the name of this RestServerParameters instance.
+     *
+     * @return name the name of this RestServerParameters
+     */
+    @Override
+    public String getName() {
+        return name;
+    }
+
+    /**
+     * Return the host of this RestServerParameters instance.
+     *
+     * @return the host
+     */
+    public String getHost() {
+        return host;
+    }
+
+    /**
+     * Return the port of this RestServerParameters instance.
+     *
+     * @return the port
+     */
+    public int getPort() {
+        return port;
+    }
+
+    /**
+     * Return the user name of this RestServerParameters instance.
+     *
+     * @return the userName
+     */
+    public String getUserName() {
+        return userName;
+    }
+
+    /**
+     * Return the password of this RestServerParameters instance.
+     *
+     * @return the password
+     */
+    public String getPassword() {
+        return password;
+    }
+
+    /**
+     * Set the name of this RestServerParameters instance.
+     *
+     * @param name the name to set
+     */
+    @Override
+    public void setName(final String name) {
+        this.name = name;
+    }
+
+    /**
+     * Validate the rest server parameters.
+     *
+     * @return the result of the validation
+     */
+    @Override
+    public GroupValidationResult validate() {
+        final GroupValidationResult validationResult = new GroupValidationResult(this);
+        if (!ParameterValidationUtils.validateStringParameter(host)) {
+            validationResult.setResult("host", ValidationStatus.INVALID,
+                    "must be a non-blank string containing hostname/ipaddress of the pap rest server");
+        }
+        if (!ParameterValidationUtils.validateStringParameter(userName)) {
+            validationResult.setResult("userName", ValidationStatus.INVALID,
+                    "must be a non-blank string containing userName for pap rest server credentials");
+        }
+        if (!ParameterValidationUtils.validateStringParameter(password)) {
+            validationResult.setResult("password", ValidationStatus.INVALID,
+                    "must be a non-blank string containing password for pap rest server credentials");
+        }
+        if (!ParameterValidationUtils.validateIntParameter(port)) {
+            validationResult.setResult("port", ValidationStatus.INVALID,
+                    "must be a positive integer containing port of the pap rest server");
+        }
+        return validationResult;
+    }
+}
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/HealthCheckProvider.java
new file mode 100644 (file)
index 0000000..d67d0d5
--- /dev/null
@@ -0,0 +1,52 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest;
+
+import org.onap.policy.common.endpoints.report.HealthCheckReport;
+import org.onap.policy.pap.main.startstop.PapActivator;
+
+/**
+ * Class to fetch health check of PAP service.
+ *
+ * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
+ */
+public class HealthCheckProvider {
+
+    private static final String NOT_ALIVE = "not alive";
+    private static final String ALIVE = "alive";
+    private static final String URL = "self";
+    private static final String NAME = "Policy PAP";
+
+    /**
+     * Performs the health check of PAP service.
+     *
+     * @return Report containing health check status
+     */
+    public HealthCheckReport performHealthCheck() {
+        final HealthCheckReport report = new HealthCheckReport();
+        report.setName(NAME);
+        report.setUrl(URL);
+        report.setHealthy(PapActivator.isAlive());
+        report.setCode(PapActivator.isAlive() ? 200 : 500);
+        report.setMessage(PapActivator.isAlive() ? ALIVE : NOT_ALIVE);
+        return report;
+    }
+}
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PapRestController.java b/main/src/main/java/org/onap/policy/pap/main/rest/PapRestController.java
new file mode 100644 (file)
index 0000000..226dc35
--- /dev/null
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.Info;
+import io.swagger.annotations.SwaggerDefinition;
+import io.swagger.annotations.Tag;
+
+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 org.onap.policy.common.endpoints.report.HealthCheckReport;
+
+/**
+ * Class to provide REST endpoints for PAP component.
+ *
+ * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
+ */
+@Path("/")
+@Api
+@Produces(MediaType.APPLICATION_JSON)
+@SwaggerDefinition(info = @Info(description = "Policy Pap Service", version = "v1.0", title = "Policy Pap"),
+        consumes = { MediaType.APPLICATION_JSON }, produces = { MediaType.APPLICATION_JSON },
+        schemes = { SwaggerDefinition.Scheme.HTTP },
+        tags = { @Tag(name = "policy-pap", description = "Policy Pap Service Operations") })
+public class PapRestController {
+
+    @GET
+    @Path("healthcheck")
+    @Produces(MediaType.APPLICATION_JSON)
+    @ApiOperation(value = "Perform a system healthcheck", notes = "Provides healthy status of the Policy Pap component",
+            response = HealthCheckReport.class)
+    public Response healthcheck() {
+        return Response.status(Response.Status.OK).entity(new HealthCheckProvider().performHealthCheck()).build();
+    }
+}
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PapRestServer.java b/main/src/main/java/org/onap/policy/pap/main/rest/PapRestServer.java
new file mode 100644 (file)
index 0000000..39f65f2
--- /dev/null
@@ -0,0 +1,141 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest;
+
+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.pap.main.parameters.RestServerParameters;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Class to manage life cycle of PAP rest server.
+ *
+ * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
+ */
+public class PapRestServer implements Startable {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(PapRestServer.class);
+
+    private static final String SEPARATOR = ".";
+    private static final String HTTP_SERVER_SERVICES = "http.server.services";
+
+    private List<HttpServletServer> servers = new ArrayList<>();
+
+    private RestServerParameters restServerParameters;
+
+    /**
+     * Constructor for instantiating PapRestServer.
+     *
+     * @param restServerParameters the rest server parameters
+     */
+    public PapRestServer(final RestServerParameters restServerParameters) {
+        this.restServerParameters = restServerParameters;
+    }
+
+    /**
+     * {@inheritDoc}.
+     */
+    @Override
+    public boolean start() {
+        try {
+            servers = HttpServletServer.factory.build(getServerProperties());
+            for (final HttpServletServer server : servers) {
+                server.start();
+            }
+        } catch (final Exception exp) {
+            LOGGER.error("Failed to start pap http server", exp);
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Creates the server properties object using restServerParameters.
+     *
+     * @return the properties object
+     */
+    private Properties getServerProperties() {
+        final Properties props = new Properties();
+        props.setProperty(HTTP_SERVER_SERVICES, restServerParameters.getName());
+        props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".host",
+                restServerParameters.getHost());
+        props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".port",
+                Integer.toString(restServerParameters.getPort()));
+        props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".restClasses",
+                PapRestController.class.getCanonicalName());
+        props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".managed", "false");
+        props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".swagger", "true");
+        props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".userName",
+                restServerParameters.getUserName());
+        props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".password",
+                restServerParameters.getPassword());
+        return props;
+    }
+
+    /**
+     * {@inheritDoc}.
+     */
+    @Override
+    public boolean stop() {
+        for (final HttpServletServer server : servers) {
+            try {
+                server.stop();
+            } catch (final Exception exp) {
+                LOGGER.error("Failed to stop pap http server", exp);
+            }
+        }
+        return true;
+    }
+
+    /**
+     * {@inheritDoc}.
+     */
+    @Override
+    public void shutdown() {
+        stop();
+    }
+
+    /**
+     * {@inheritDoc}.
+     */
+    @Override
+    public boolean isAlive() {
+        return !servers.isEmpty();
+    }
+
+    /**
+     * {@inheritDoc}.
+     */
+    @Override
+    public String toString() {
+        final StringBuilder builder = new StringBuilder();
+        builder.append("PapRestServer [servers=");
+        builder.append(servers);
+        builder.append("]");
+        return builder.toString();
+    }
+
+}
index 63d41a0..602e04d 100644 (file)
@@ -25,8 +25,8 @@ import java.util.Arrays;
 import org.onap.policy.pap.main.PolicyPapException;
 import org.onap.policy.pap.main.parameters.PapParameterGroup;
 import org.onap.policy.pap.main.parameters.PapParameterHandler;
-import org.slf4j.ext.XLogger;
-import org.slf4j.ext.XLoggerFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * This class initiates ONAP Policy Framework PAP component.
@@ -34,7 +34,8 @@ import org.slf4j.ext.XLoggerFactory;
  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
  */
 public class Main {
-    private static final XLogger LOGGER = XLoggerFactory.getXLogger(Main.class);
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
 
     private PapActivator activator;
     private PapParameterGroup parameterGroup;
index 8aec2ad..b1674ef 100644 (file)
@@ -23,8 +23,9 @@ package org.onap.policy.pap.main.startstop;
 import org.onap.policy.common.parameters.ParameterService;
 import org.onap.policy.pap.main.PolicyPapException;
 import org.onap.policy.pap.main.parameters.PapParameterGroup;
-import org.slf4j.ext.XLogger;
-import org.slf4j.ext.XLoggerFactory;
+import org.onap.policy.pap.main.rest.PapRestServer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * This class wraps a distributor so that it can be activated as a complete service together with all its pap and
@@ -33,13 +34,12 @@ import org.slf4j.ext.XLoggerFactory;
  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
  */
 public class PapActivator {
-    // The logger for this class
-    private static final XLogger LOGGER = XLoggerFactory.getXLogger(PapActivator.class);
 
-    // The parameters of this policy pap activator
-    private final PapParameterGroup papParameterGroup;
+    private static final Logger LOGGER = LoggerFactory.getLogger(PapActivator.class);
 
+    private final PapParameterGroup papParameterGroup;
     private static boolean alive = false;
+    private PapRestServer restServer;
 
     /**
      * Instantiate the activator for policy pap as a complete service.
@@ -58,6 +58,7 @@ public class PapActivator {
     public void initialize() throws PolicyPapException {
         try {
             LOGGER.debug("Policy pap starting as a service . . .");
+            startPapRestServer();
             registerToParameterService(papParameterGroup);
             PapActivator.setAlive(true);
             LOGGER.debug("Policy pap started as a service");
@@ -77,6 +78,8 @@ public class PapActivator {
             deregisterToParameterService(papParameterGroup);
             PapActivator.setAlive(false);
 
+            // Stop the pap rest server
+            restServer.stop();
         } catch (final Exception exp) {
             LOGGER.error("Policy pap service termination failed", exp);
             throw new PolicyPapException(exp.getMessage(), exp);
@@ -127,4 +130,17 @@ public class PapActivator {
     public static void setAlive(final boolean status) {
         alive = status;
     }
+
+    /**
+     * Starts the pap rest server using configuration parameters.
+     *
+     * @throws PolicyPapException if server start fails
+     */
+    private void startPapRestServer() throws PolicyPapException {
+        papParameterGroup.getRestServerParameters().setName(papParameterGroup.getName());
+        restServer = new PapRestServer(papParameterGroup.getRestServerParameters());
+        if (!restServer.start()) {
+            throw new PolicyPapException("Failed to start pap rest server. Check log for more details...");
+        }
+    }
 }
index 5e62ba6..0e4ae52 100644 (file)
@@ -27,6 +27,27 @@ package org.onap.policy.pap.main.parameters;
  */
 public class CommonTestData {
 
+    private static final String REST_SERVER_PASSWORD = "zb!XztG34";
+    private static final String REST_SERVER_USER = "healthcheck";
+    private static final int REST_SERVER_PORT = 6969;
+    private static final String REST_SERVER_HOST = "0.0.0.0";
     public static final String PAP_GROUP_NAME = "PapGroup";
 
+    /**
+     * Returns an instance of RestServerParameters for test cases.
+     *
+     * @param isEmpty boolean value to represent that object created should be empty or not
+     * @return the restServerParameters object
+     */
+    public RestServerParameters getRestServerParameters(final boolean isEmpty) {
+        final RestServerParameters restServerParameters;
+        if (!isEmpty) {
+            restServerParameters = new RestServerParameters(REST_SERVER_HOST, REST_SERVER_PORT, REST_SERVER_USER,
+                    REST_SERVER_PASSWORD);
+        } else {
+            restServerParameters = new RestServerParameters(null, 0, null, null);
+        }
+        return restServerParameters;
+    }
+
 }
index 086d7c2..7d5355a 100644 (file)
@@ -33,18 +33,26 @@ import org.onap.policy.common.parameters.GroupValidationResult;
  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
  */
 public class TestPapParameterGroup {
+    CommonTestData commonTestData = new CommonTestData();
 
     @Test
     public void testPapParameterGroup() {
-        final PapParameterGroup papParameters = new PapParameterGroup(CommonTestData.PAP_GROUP_NAME);
+        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false);
+        final PapParameterGroup papParameters =
+                new PapParameterGroup(CommonTestData.PAP_GROUP_NAME, restServerParameters);
         final GroupValidationResult validationResult = papParameters.validate();
         assertTrue(validationResult.isValid());
         assertEquals(CommonTestData.PAP_GROUP_NAME, papParameters.getName());
+        assertEquals(restServerParameters.getHost(), papParameters.getRestServerParameters().getHost());
+        assertEquals(restServerParameters.getPort(), papParameters.getRestServerParameters().getPort());
+        assertEquals(restServerParameters.getUserName(), papParameters.getRestServerParameters().getUserName());
+        assertEquals(restServerParameters.getPassword(), papParameters.getRestServerParameters().getPassword());
     }
 
     @Test
     public void testPapParameterGroup_NullName() {
-        final PapParameterGroup papParameters = new PapParameterGroup(null);
+        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false);
+        final PapParameterGroup papParameters = new PapParameterGroup(null, restServerParameters);
         final GroupValidationResult validationResult = papParameters.validate();
         assertFalse(validationResult.isValid());
         assertEquals(null, papParameters.getName());
@@ -54,7 +62,8 @@ public class TestPapParameterGroup {
 
     @Test
     public void testPapParameterGroup_EmptyName() {
-        final PapParameterGroup papParameters = new PapParameterGroup("");
+        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false);
+        final PapParameterGroup papParameters = new PapParameterGroup("", restServerParameters);
         final GroupValidationResult validationResult = papParameters.validate();
         assertFalse(validationResult.isValid());
         assertEquals("", papParameters.getName());
@@ -64,10 +73,25 @@ public class TestPapParameterGroup {
 
     @Test
     public void testPapParameterGroup_SetName() {
-        final PapParameterGroup papParameters = new PapParameterGroup(CommonTestData.PAP_GROUP_NAME);
+        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false);
+        final PapParameterGroup papParameters =
+                new PapParameterGroup(CommonTestData.PAP_GROUP_NAME, restServerParameters);
         papParameters.setName("PapNewGroup");
         final GroupValidationResult validationResult = papParameters.validate();
         assertTrue(validationResult.isValid());
         assertEquals("PapNewGroup", papParameters.getName());
     }
+
+    @Test
+    public void testApiParameterGroup_EmptyRestServerParameters() {
+        final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(true);
+
+        final PapParameterGroup papParameters =
+                new PapParameterGroup(CommonTestData.PAP_GROUP_NAME, restServerParameters);
+        final GroupValidationResult validationResult = papParameters.validate();
+        assertFalse(validationResult.isValid());
+        assertTrue(validationResult.getResult()
+                .contains("\"org.onap.policy.pap.main.parameters.RestServerParameters\" INVALID, "
+                        + "parameter group has status INVALID"));
+    }
 }
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPapRestServer.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPapRestServer.java
new file mode 100644 (file)
index 0000000..b604e20
--- /dev/null
@@ -0,0 +1,125 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.Invocation;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.MediaType;
+
+import org.glassfish.jersey.client.ClientConfig;
+import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
+import org.junit.Test;
+import org.onap.policy.common.endpoints.report.HealthCheckReport;
+import org.onap.policy.common.utils.network.NetworkUtil;
+import org.onap.policy.pap.main.PolicyPapException;
+import org.onap.policy.pap.main.parameters.CommonTestData;
+import org.onap.policy.pap.main.parameters.RestServerParameters;
+import org.onap.policy.pap.main.startstop.Main;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Class to perform unit test of {@link PapRestServer}.
+ *
+ * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
+ */
+public class TestPapRestServer {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(TestPapRestServer.class);
+    private static final String NOT_ALIVE = "not alive";
+    private static final String ALIVE = "alive";
+    private static final String SELF = "self";
+    private static final String NAME = "Policy PAP";
+
+    @Test
+    public void testHealthCheckSuccess() throws PolicyPapException, InterruptedException {
+        final String reportString = "Report [name=Policy PAP, url=self, healthy=true, code=200, message=alive]";
+        try {
+            final Main main = startPapService();
+            final HealthCheckReport report = performHealthCheck();
+            validateReport(NAME, SELF, true, 200, ALIVE, reportString, report);
+            stopPapService(main);
+        } catch (final Exception exp) {
+            LOGGER.error("testHealthCheckSuccess failed", exp);
+            fail("Test should not throw an exception");
+        }
+    }
+
+    @Test
+    public void testHealthCheckFailure() throws InterruptedException, IOException {
+        final String reportString = "Report [name=Policy PAP, url=self, healthy=false, code=500, message=not alive]";
+        final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false);
+        restServerParams.setName(CommonTestData.PAP_GROUP_NAME);
+        final PapRestServer restServer = new PapRestServer(restServerParams);
+        restServer.start();
+        final HealthCheckReport report = performHealthCheck();
+        validateReport(NAME, SELF, false, 500, NOT_ALIVE, reportString, report);
+        assertTrue(restServer.isAlive());
+        assertTrue(restServer.toString().startsWith("PapRestServer [servers="));
+        restServer.shutdown();
+    }
+
+    private Main startPapService() {
+        final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters.json" };
+        return new Main(papConfigParameters);
+    }
+
+    private void stopPapService(final Main main) throws PolicyPapException {
+        main.shutdown();
+    }
+
+    private HealthCheckReport performHealthCheck() throws InterruptedException, IOException {
+        HealthCheckReport response = null;
+        final ClientConfig clientConfig = new ClientConfig();
+
+        final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34");
+        clientConfig.register(feature);
+
+        final Client client = ClientBuilder.newClient(clientConfig);
+        final WebTarget webTarget = client.target("http://localhost:6969/healthcheck");
+
+        final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
+
+        if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) {
+            throw new IllegalStateException("cannot connect to port 6969");
+        }
+        response = invocationBuilder.get(HealthCheckReport.class);
+        return response;
+    }
+
+    private void validateReport(final String name, final String url, final boolean healthy, final int code,
+            final String message, final String reportString, final HealthCheckReport report) {
+        assertEquals(name, report.getName());
+        assertEquals(url, report.getUrl());
+        assertEquals(healthy, report.isHealthy());
+        assertEquals(code, report.getCode());
+        assertEquals(message, report.getMessage());
+        assertEquals(reportString, report.toString());
+    }
+}
index ec79d58..34a8f80 100644 (file)
@@ -1,3 +1,9 @@
 {  
-    "name":"PapGroup"
+    "name":"PapGroup",
+    "restServerParameters":{
+        "host":"0.0.0.0",
+        "port":6969,
+        "userName":"healthcheck",
+        "password":"zb!XztG34"
+    }
 }
index 88d0051..7e41559 100644 (file)
@@ -1,3 +1,9 @@
 {
-    "name":"PapGroup"
+    "name":"PapGroup",
+    "restServerParameters":{
+        "host":"0.0.0.0",
+        "port":6969,
+        "userName":"healthcheck",
+        "password":"zb!XztG34"
+    }
 }
index 1a466d0..80fb823 100644 (file)
@@ -1,3 +1,9 @@
 {
-    "name":" "
+    "name":" ",
+    "restServerParameters":{
+        "host":"0.0.0.0",
+        "port":6969,
+        "userName":"healthcheck",
+        "password":"zb!XztG34"
+    }
 }
diff --git a/pom.xml b/pom.xml
index 5ae35dd..8438e89 100644 (file)
--- a/pom.xml
+++ b/pom.xml
             <artifactId>junit</artifactId>
             <scope>test</scope>
         </dependency>
-        <dependency>
-            <groupId>org.slf4j</groupId>
-            <artifactId>slf4j-ext</artifactId>
-            <version>1.8.0-beta2</version>
-        </dependency>
-        <dependency>
-            <groupId>org.slf4j</groupId>
-            <artifactId>slf4j-api</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ch.qos.logback</groupId>
-            <artifactId>logback-core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ch.qos.logback</groupId>
-            <artifactId>logback-classic</artifactId>
-        </dependency>
     </dependencies>
 
     <distributionManagement>