diff options
14 files changed, 1004 insertions, 1039 deletions
diff --git a/main/pom.xml b/main/pom.xml index 13839887..146b2393 100644 --- a/main/pom.xml +++ b/main/pom.xml @@ -53,6 +53,17 @@ <artifactId>common-parameters</artifactId> <version>${policy.common.version}</version> </dependency> + <dependency> + <groupId>org.onap.policy.models</groupId> + <artifactId>platform</artifactId> + <version>${policy.models.version}</version> + </dependency> + <dependency> + <groupId>org.projectlombok</groupId> + <artifactId>lombok</artifactId> + <version>1.18.4</version> + <scope>provided</scope> + </dependency> </dependencies> <build> diff --git a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java index ca211b67..f13e8f74 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ + * ONAP Policy API + * ================================================================================ * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -25,45 +25,468 @@ package org.onap.policy.api.main.rest; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.BasicAuthDefinition; import io.swagger.annotations.Info; +import io.swagger.annotations.SecurityDefinition; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; import javax.ws.rs.GET; +import javax.ws.rs.POST; import javax.ws.rs.Path; +import javax.ws.rs.PathParam; import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.onap.policy.api.main.rest.provider.HealthCheckProvider; +import org.onap.policy.api.main.rest.provider.PolicyProvider; +import org.onap.policy.api.main.rest.provider.PolicyTypeProvider; +import org.onap.policy.api.main.rest.provider.StatisticsProvider; import org.onap.policy.common.endpoints.report.HealthCheckReport; +import org.onap.policy.model.tosca.ToscaPolicy; +import org.onap.policy.model.tosca.ToscaPolicyList; +import org.onap.policy.model.tosca.ToscaPolicyType; +import org.onap.policy.model.tosca.ToscaPolicyTypeList; /** * Class to provide REST API services. */ -@Path("/") -@Api +@Path("/policy/api/v1") +@Api(value = "Policy Design API") @Produces(MediaType.APPLICATION_JSON) -@SwaggerDefinition( - info = @Info(description = "Policy Api Service", version = "v2.0", title = "Policy Api"), +@Consumes(MediaType.APPLICATION_JSON) +@SwaggerDefinition(info = @Info( + description = "Policy Design API is publicly exposed for clients to Create/Read/Update/Delete" + + "policy types, policy type implementation and policies which can be recognized" + + "and executable by incorporated policy engines XACML, Drools and APEX. It is a" + + "standalone component running rest service that takes all policy design API calls" + + "from clients and then assign them to different API working functions. Besides" + + "that, API is also exposed for clients to retrieve healthcheck status of this API" + + "rest service and the statistics report including the counters of API invocation.", + version = "v1.0", title = "Policy Design"), consumes = { MediaType.APPLICATION_JSON }, produces = { MediaType.APPLICATION_JSON }, schemes = { SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS }, - tags = { @Tag(name = "policy-api", description = "Policy Api Service Operations") }) + tags = { @Tag(name = "policy-api", description = "Policy API Service Operations") }, + securityDefinition = @SecurityDefinition(basicAuthDefinitions = { @BasicAuthDefinition(key = "basicAuth") })) public class ApiRestController { + /** + * Retrieves the healthcheck status of the API component. + * + * @return the Response object containing the results of the API operation + */ @GET - @Path("healthcheck") - @Produces(MediaType.APPLICATION_JSON) + @Path("/healthcheck") @ApiOperation(value = "Perform a system healthcheck", - notes = "Provides healthy status of the Policy Api component", response = HealthCheckReport.class) - public Response healthcheck() { + notes = "Returns healthy status of the Policy API component", + response = HealthCheckReport.class, + authorizations = @Authorization(value = "basicAuth"), + tags = { "HealthCheck", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response getHealthCheck() { return Response.status(Response.Status.OK).entity(new HealthCheckProvider().performHealthCheck()).build(); } - + + /** + * Retrieves the statistics report of the API component. + * + * @return the Response object containing the results of the API operation + */ @GET - @Path("statistics") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Fetch current statistics", - notes = "Provides current statistics of the Policy API component", - response = StatisticsReport.class) - public Response statistics() { + @Path("/statistics") + @ApiOperation(value = "Retrieve current statistics", + notes = "Returns current statistics including the counters of API invocation", + response = StatisticsReport.class, + authorizations = @Authorization(value = "basicAuth"), + tags = { "Statistics", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response getStatistics() { return Response.status(Response.Status.OK).entity(new StatisticsProvider().fetchCurrentStatistics()).build(); } + + /** + * Retrieves all available policy types. + * + * @return the Response object containing the results of the API operation + */ + @GET + @Path("/policytypes") + @ApiOperation(value = "Retrieve existing policy types", + notes = "Returns a list of existing policy types stored in Policy Framework", + response = ToscaPolicyTypeList.class, + authorizations = @Authorization(value = "basicAuth"), + tags = { "PolicyType", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response getAllPolicyTypes() { + return Response.status(Response.Status.OK) + .entity(new PolicyTypeProvider().fetchPolicyTypes(null, null)).build(); + } + + /** + * Retrieves all versions of a particular policy type. + * + * @param policyTypeId the ID of specified policy type + * + * @return the Response object containing the results of the API operation + */ + @GET + @Path("/policytypes/{policyTypeId}") + @ApiOperation(value = "Retrieve all available versions of a policy type", + notes = "Returns a list of all available versions for the specified policy type", + response = ToscaPolicyTypeList.class, + authorizations = @Authorization(value = "basicAuth"), + tags = { "PolicyType", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response getAllVersionsOfPolicyType( + @PathParam("policyTypeId") @ApiParam("ID of policy type") String policyTypeId) { + return Response.status(Response.Status.OK) + .entity(new PolicyTypeProvider().fetchPolicyTypes(policyTypeId, null)).build(); + } + + /** + * Retrieves specified version of a particular policy type. + * + * @param policyTypeId the ID of specified policy type + * @param versionId the version of specified policy type + * + * @return the Response object containing the results of the API operation + */ + @GET + @Path("/policytypes/{policyTypeId}/versions/{versionId}") + @ApiOperation(value = "Retrieve one particular version of a policy type", + notes = "Returns a particular version for the specified policy type", + response = ToscaPolicyTypeList.class, + authorizations = @Authorization(value = "basicAuth"), + tags = { "PolicyType", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response getSpecificVersionOfPolicyType( + @PathParam("policyTypeId") @ApiParam("ID of policy type") String policyTypeId, + @PathParam("versionId") @ApiParam("ID of version") String versionId) { + return Response.status(Response.Status.OK) + .entity(new PolicyTypeProvider().fetchPolicyTypes(policyTypeId, versionId)).build(); + } + + /** + * Creates a new policy type. + * + * @param body the body of policy type following TOSCA definition + * + * @return the Response object containing the results of the API operation + */ + @POST + @Path("/policytypes") + @ApiOperation(value = "Create a new policy type", + notes = "Client should provide TOSCA body of the new policy type", + authorizations = @Authorization(value = "basicAuth"), + tags = { "PolicyType", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid Body"), + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response createPolicyType(ToscaPolicyType body) { + return Response.status(Response.Status.OK).entity(new PolicyTypeProvider().createPolicyType(body)).build(); + } + + /** + * Deletes all versions of a particular policy type. + * + * @param policyTypeId the ID of specified policy type + * + * @return the Response object containing the results of the API operation + */ + @DELETE + @Path("/policytypes/{policyTypeId}") + @ApiOperation(value = "Delete all versions of a policy type", + notes = "Rule 1: pre-defined policy types cannot be deleted;" + + "Rule 2: policy types that are in use (parameterized by a TOSCA policy) cannot be deleted." + + "The parameterizing TOSCA policies must be deleted first;", + authorizations = @Authorization(value = "basicAuth"), + tags = { "PolicyType", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 409, message = "Delete Conflict, Rule Violation"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response deleteAllVersionsOfPolicyType( + @PathParam("policyTypeId") @ApiParam("ID of policy type") String policyTypeId) { + return Response.status(Response.Status.OK) + .entity(new PolicyTypeProvider().deletePolicyTypes(policyTypeId, null)).build(); + } + + /** + * Deletes specified version of a particular policy type. + * + * @param policyTypeId the ID of specified policy type + * @param versionId the version of specified policy type + * + * @return the Response object containing the results of the API operation + */ + @DELETE + @Path("/policytypes/{policyTypeId}/versions/{versionId}") + @ApiOperation(value = "Delete one version of a policy type", + notes = "Rule 1: pre-defined policy types cannot be deleted;" + + "Rule 2: policy types that are in use (parameterized by a TOSCA policy) cannot be deleted." + + "The parameterizing TOSCA policies must be deleted first;", + authorizations = @Authorization(value = "basicAuth"), + tags = { "PolicyType", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 409, message = "Delete Conflict, Rule Violation"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response deleteSpecificVersionOfPolicyType( + @PathParam("policyTypeId") @ApiParam("ID of policy type") String policyTypeId, + @PathParam("versionId") @ApiParam("ID of version") String versionId) { + return Response.status(Response.Status.OK) + .entity(new PolicyTypeProvider().deletePolicyTypes(policyTypeId, versionId)).build(); + } + + /** + * Retrieves all versions of a particular policy. + * + * @param policyTypeId the ID of specified policy type + * @param policyTypeVersion the version of specified policy type + * + * @return the Response object containing the results of the API operation + */ + @GET + @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies") + @ApiOperation(value = "Retrieve all versions of a policy created for a particular policy type version", + notes = "Returns a list of all versions of specified policy created for the specified policy type version", + response = ToscaPolicyList.class, + authorizations = @Authorization(value = "basicAuth"), + tags = { "Policy", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response getAllPolicies( + @PathParam("policyTypeId") @ApiParam("ID of policy type") String policyTypeId, + @PathParam("policyTypeVersion") @ApiParam("ID of policy type version") String policyTypeVersion) { + return Response.status(Response.Status.OK) + .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, null, null)).build(); + } + + /** + * Retrieves all versions of a particular policy. + * + * @param policyTypeId the ID of specified policy type + * @param policyTypeVersion the version of specified policy type + * @param policyId the ID of specified policy + * + * @return the Response object containing the results of the API operation + */ + @GET + @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}") + @ApiOperation(value = "Retrieve all version details of a policy created for a particular policy type version", + notes = "Returns a list of all version details of the specified policy", + response = ToscaPolicyList.class, + authorizations = @Authorization(value = "basicAuth"), + tags = { "Policy", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response getAllVersionsOfPolicy( + @PathParam("policyTypeId") @ApiParam("ID of policy type") String policyTypeId, + @PathParam("policyTypeVersion") @ApiParam("ID of policy type version") String policyTypeVersion, + @PathParam("policyId") @ApiParam("ID of policy") String policyId) { + return Response.status(Response.Status.OK) + .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, policyId, null)).build(); + } + + /** + * Retrieves the specified version of a particular policy. + * + * @param policyTypeId the ID of specified policy type + * @param policyTypeVersion the version of specified policy type + * @param policyId the ID of specified policy + * @param policyVersion the version of specified policy + * + * @return the Response object containing the results of the API operation + */ + @GET + @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/{policyVersion}") + @ApiOperation(value = "Retrieve one version of a policy created for a particular policy type version", + notes = "Returns a particular version of specified policy created for the specified policy type version", + response = ToscaPolicyList.class, + authorizations = @Authorization(value = "basicAuth"), + tags = { "Policy", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response getSpecificVersionOfPolicy( + @PathParam("policyTypeId") @ApiParam("ID of policy type") String policyTypeId, + @PathParam("policyTypeVersion") @ApiParam("ID of policy type version") String policyTypeVersion, + @PathParam("policyId") @ApiParam("ID of policy") String policyId, + @PathParam("policyVersion") @ApiParam("ID of policy version") String policyVersion) { + return Response.status(Response.Status.OK) + .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, + policyId, policyVersion)).build(); + } + + /** + * Retrieves either latest or deployed version of a particular policy depending on query parameter. + * + * @param policyTypeId the ID of specified policy type + * @param policyTypeVersion the version of specified policy type + * @param policyId the ID of specified policy + * + * @return the Response object containing the results of the API operation + */ + @GET + @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions") + @ApiOperation(value = "Retrieve either latest or deployed version of a particular policy depending on query param", + notes = "Returns either latest or deployed version of specified policy depending on query param", + response = ToscaPolicyList.class, + authorizations = @Authorization(value = "basicAuth"), + tags = { "Policy", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response getEitherLatestOrDeployedVersionOfPolicy( + @PathParam("policyTypeId") @ApiParam("ID of policy type") String policyTypeId, + @PathParam("policyTypeVersion") @ApiParam("ID of policy type version") String policyTypeVersion, + @PathParam("policyId") @ApiParam("ID of policy") String policyId, + @QueryParam("type") @ApiParam("Type of version that can only be 'latest' or 'deployed'") String type) { + return Response.status(Response.Status.OK) + .entity(new PolicyProvider().fetchPolicies(policyTypeId, policyTypeVersion, policyId, type)).build(); + } + + /** + * Creates a new policy for a particular policy type and version. + * + * @param policyTypeId the ID of specified policy type + * @param policyTypeVersion the version of specified policy type + * @param body the body of policy following TOSCA definition + * + * @return the Response object containing the results of the API operation + */ + @POST + @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies") + @ApiOperation(value = "Create a new policy for a policy type version", + notes = "Client should provide TOSCA body of the new policy", + authorizations = @Authorization(value = "basicAuth"), + tags = { "Policy", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid Body"), + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response createPolicy( + @PathParam("policyTypeId") @ApiParam("ID of policy type") String policyTypeId, + @PathParam("policyTypeVersion") @ApiParam("ID of policy type version") String policyTypeVersion, + ToscaPolicy body) { + return Response.status(Response.Status.OK) + .entity(new PolicyProvider().createPolicy(policyTypeId, policyTypeVersion, body)).build(); + } + + /** + * Deletes all versions of a particular policy. + * + * @param policyTypeId the ID of specified policy type + * @param policyTypeVersion the version of specified policy type + * @param policyId the ID of specified policy + * + * @return the Response object containing the results of the API operation + */ + @DELETE + @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}") + @ApiOperation(value = "Delete all versions of a policy", + notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted", + authorizations = @Authorization(value = "basicAuth"), + tags = { "Policy", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 409, message = "Delete Conflict, Rule Violation"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response deleteAllVersionsOfPolicy( + @PathParam("policyTypeId") @ApiParam("ID of policy type") String policyTypeId, + @PathParam("policyTypeVersion") @ApiParam("ID of policy type version") String policyTypeVersion, + @PathParam("policyId") @ApiParam("ID of policy") String policyId) { + return Response.status(Response.Status.OK) + .entity(new PolicyProvider().deletePolicies(policyTypeId, policyTypeVersion, policyId, null)).build(); + } + + /** + * Deletes the specified version of a particular policy. + * + * @param policyTypeId the ID of specified policy type + * @param policyTypeVersion the version of specified policy type + * @param policyId the ID of specified policy + * @param policyVersion the version of specified policy + * + * @return the Response object containing the results of the API operation + */ + @DELETE + @Path("/policytypes/{policyTypeId}/versions/{policyTypeVersion}/policies/{policyId}/versions/{policyVersion}") + @ApiOperation(value = "Delete a particular version of a policy", + notes = "Rule: the version that has been deployed in PDP group(s) cannot be deleted", + authorizations = @Authorization(value = "basicAuth"), + tags = { "Policy", }) + @ApiResponses(value = { + @ApiResponse(code = 401, message = "Authentication Error"), + @ApiResponse(code = 403, message = "Authorization Error"), + @ApiResponse(code = 404, message = "Resource Not Found"), + @ApiResponse(code = 409, message = "Delete Conflict, Rule Violation"), + @ApiResponse(code = 500, message = "Internal Server Error") + }) + public Response deleteSpecificVersionOfPolicy( + @PathParam("policyTypeId") @ApiParam("PolicyType ID") String policyTypeId, + @PathParam("policyTypeVersion") @ApiParam("ID of policy type version") String policyTypeVersion, + @PathParam("policyId") @ApiParam("ID of policy") String policyId, + @PathParam("policyVersion") @ApiParam("ID of policy version") String policyVersion) { + return Response.status(Response.Status.OK) + .entity(new PolicyProvider().deletePolicies(policyTypeId, policyTypeVersion, + policyId, policyVersion)).build(); + } } diff --git a/main/src/main/java/org/onap/policy/api/main/rest/ApiStatisticsManager.java b/main/src/main/java/org/onap/policy/api/main/rest/ApiStatisticsManager.java index 55c8cee1..6f8fb103 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/ApiStatisticsManager.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/ApiStatisticsManager.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ + * ONAP Policy API + * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,301 +22,199 @@ package org.onap.policy.api.main.rest; +import lombok.Getter; + /** * Class to hold statistical data for API access. + * + * @author Chenfei Gao (cgao@research.att.com) */ public class ApiStatisticsManager { - + + @Getter private static long totalApiCallCount; + + @Getter private static long apiCallSuccessCount; + + @Getter private static long apiCallFailureCount; + + @Getter private static long totalPolicyGetCount; + + @Getter private static long totalPolicyPostCount; - private static long totalTemplateGetCount; - private static long totalTemplatePostCount; + + @Getter + private static long totalPolicyTypeGetCount; + + @Getter + private static long totalPolicyTypePostCount; + + @Getter private static long policyGetSuccessCount; + + @Getter private static long policyGetFailureCount; + + @Getter private static long policyPostSuccessCount; + + @Getter private static long policyPostFailureCount; - private static long templateGetSuccessCount; - private static long templateGetFailureCount; - private static long templatePostSuccessCount; - private static long templatePostFailureCount; - + + @Getter + private static long policyTypeGetSuccessCount; + + @Getter + private static long policyTypeGetFailureCount; + + @Getter + private static long policyTypePostSuccessCount; + + @Getter + private static long policyTypePostFailureCount; + private ApiStatisticsManager() { throw new IllegalStateException("Instantiation of the class is not allowed"); } - + /** * Method to update the total api call count. - * + * * @return the updated value of totalApiCallCount */ public static long updateTotalApiCallCount() { return ++totalApiCallCount; } - + /** * Method to update the successful api call count. - * + * * @return the updated value of apiCallSuccessCount */ public static long updateApiCallSuccessCount() { return ++apiCallSuccessCount; } - + /** * Method to update the failed api call count. - * + * * @return the updated value of apiCallFailureCount */ public static long updateApiCallFailureCount() { return ++apiCallFailureCount; } - + /** * Method to update the total policy GET count. - * + * * @return the updated value of totalPolicyGetCount */ public static long updateTotalPolicyGetCount() { return ++totalPolicyGetCount; } - + /** * Method to update the total policy POST count. - * + * * @return the updated value of totalPolicyPostCount */ public static long updateTotalPolicyPostCount() { return ++totalPolicyPostCount; } - + /** - * Method to update the total template GET count. - * - * @return the updated value of totalTemplateGetCount + * Method to update the total policyType GET count. + * + * @return the updated value of totalPolicyTypeGetCount */ - public static long updateTotalTemplateGetCount() { - return ++totalTemplateGetCount; + public static long updateTotalPolicyTypeGetCount() { + return ++totalPolicyTypeGetCount; } - + /** - * Method to update the total template POST count. - * - * @return the updated value of totalTemplatePostCount + * Method to update the total policyType POST count. + * + * @return the updated value of totalPolicyTypePostCount */ - public static long updateTotalTemplatePostCount() { - return ++totalTemplatePostCount; + public static long updateTotalPolicyTypePostCount() { + return ++totalPolicyTypePostCount; } - + /** * Method to update successful policy GET count. - * + * * @return the updated value of policyGetSuccessCount */ public static long updatePolicyGetSuccessCount() { return ++policyGetSuccessCount; } - + /** * Method to update failed policy GET count. - * + * * @return the updated value of policyGetFailureCount */ public static long updatePolicyGetFailureCount() { return ++policyGetFailureCount; } - + /** * Method to update successful policy POST count. - * + * * @return the updated value of policyPostSuccessCount */ public static long updatePolicyPostSuccessCount() { return ++policyPostSuccessCount; } - + /** * Method to update failed policy POST count. - * + * * @return the updated value of policyPostFailureCount */ public static long updatePolicyPostFailureCount() { return ++policyPostFailureCount; } - - /** - * Method to update successful template GET count. - * - * @return the updated value of templateGetSuccessCount - */ - public static long updateTemplateGetSuccessCount() { - return ++templateGetSuccessCount; - } - - /** - * Method to update failed template GET count. - * - * @return the updated value of templateGetFailureCount - */ - public static long updateTemplateGetFailureCount() { - return ++templateGetFailureCount; - } - - /** - * Method to update successful template POST count. - * - * @return the updated value of templatePostSuccessCount - */ - public static long updateTemplatePostSuccessCount() { - return ++templatePostSuccessCount; - } - - /** - * Method to update failed template POST count. - * - * @return the updated value of templatePostFailureCount - */ - public static long updateTemplatePostFailureCount() { - return ++templatePostFailureCount; - } - - /** - * Returns the current value of totalApiCallCount. - * - * @return the totalApiCallCount - */ - public static long getTotalApiCallCount() { - return totalApiCallCount; - } - - /** - * Returns the current value of apiCallSuccessCount. - * - * @return the apiCallSuccessCount - */ - public static long getApiCallSuccessCount() { - return apiCallSuccessCount; - } - - /** - * Returns the current value of apiCallFailureCount. - * - * @return the apiCallFailureCount - */ - public static long getApiCallFailureCount() { - return apiCallFailureCount; - } - - /** - * Returns the current value of totalPolicyGetCount. - * - * @return the totalPolicyGetCount - */ - public static long getTotalPolicyGetCount() { - return totalPolicyGetCount; - } - - /** - * Returns the current value of totalPolicyPostCount. - * - * @return the totalPolicyPostCount - */ - public static long getTotalPolicyPostCount() { - return totalPolicyPostCount; - } - - /** - * Returns the current value of totalTemplateGetCount. - * - * @return the totalTemplateGetCount - */ - public static long getTotalTemplateGetCount() { - return totalTemplateGetCount; - } - - /** - * Returns the current value of totalTemplatePostCount. - * - * @return the totalTemplatePostCount - */ - public static long getTotalTemplatePostCount() { - return totalTemplatePostCount; - } - - /** - * Returns the current value of policyGetSuccessCount. - * - * @return the policyGetSuccessCount - */ - public static long getPolicyGetSuccessCount() { - return policyGetSuccessCount; - } - - /** - * Returns the current value of policyGetFailureCount. - * - * @return the policyGetFailureCount - */ - public static long getPolicyGetFailureCount() { - return policyGetFailureCount; - } - - /** - * Returns the current value of policyPostSuccessCount. - * - * @return the policyPostSuccessCount - */ - public static long getPolicyPostSuccessCount() { - return policyPostSuccessCount; - } - - /** - * Returns the current value of policyPostFailureCount. - * - * @return the policyPostFailureCount - */ - public static long getPolicyPostFailureCount() { - return policyPostFailureCount; - } - + /** - * Returns the current value of templateGetSuccessCount. - * - * @return the templateGetSuccessCount + * Method to update successful policyType GET count. + * + * @return the updated value of policyTypeGetSuccessCount */ - public static long getTemplateGetSuccessCount() { - return templateGetSuccessCount; + public static long updatePolicyTypeGetSuccessCount() { + return ++policyTypeGetSuccessCount; } - + /** - * Returns the current value of templateGetFailureCount. - * - * @return the templateGetFailureCount + * Method to update failed policyType GET count. + * + * @return the updated value of policyTypeGetFailureCount */ - public static long getTemplateGetFailureCount() { - return templateGetFailureCount; + public static long updatePolicyTypeGetFailureCount() { + return ++policyTypeGetFailureCount; } - + /** - * Returns the current value of templatePostSuccessCount. - * - * @return the templatePostSuccessCount + * Method to update successful policyType POST count. + * + * @return the updated value of policyTypePostSuccessCount */ - public static long getTemplatePostSuccessCount() { - return templatePostSuccessCount; + public static long updatePolicyTypePostSuccessCount() { + return ++policyTypePostSuccessCount; } - + /** - * Returns the current value of templatePostFailureCount. - * - * @return the templatePostFailureCount + * Method to update failed policyType POST count. + * + * @return the updated value of policyTypePostFailureCount */ - public static long getTemplatePostFailureCount() { - return templatePostFailureCount; + public static long updatePolicyTypePostFailureCount() { + return ++policyTypePostFailureCount; } - + /** * Reset all the statistics counts to 0. */ @@ -326,15 +224,15 @@ public class ApiStatisticsManager { apiCallFailureCount = 0L; totalPolicyGetCount = 0L; totalPolicyPostCount = 0L; - totalTemplateGetCount = 0L; - totalTemplatePostCount = 0L; + totalPolicyTypeGetCount = 0L; + totalPolicyTypePostCount = 0L; policyGetSuccessCount = 0L; policyGetFailureCount = 0L; policyPostSuccessCount = 0L; policyPostFailureCount = 0L; - templateGetSuccessCount = 0L; - templateGetFailureCount = 0L; - templatePostSuccessCount = 0L; - templatePostFailureCount = 0L; + policyTypeGetSuccessCount = 0L; + policyTypeGetFailureCount = 0L; + policyTypePostSuccessCount = 0L; + policyTypePostFailureCount = 0L; } } diff --git a/main/src/main/java/org/onap/policy/api/main/rest/StatisticsReport.java b/main/src/main/java/org/onap/policy/api/main/rest/StatisticsReport.java index 03bc9590..4919303f 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/StatisticsReport.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/StatisticsReport.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ + * ONAP Policy API + * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,355 +22,79 @@ package org.onap.policy.api.main.rest; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + /** * Class to represent API statistics report. + * + * @author Chenfei Gao (cgao@research.att.com) */ +@ToString public class StatisticsReport { - + + @Getter + @Setter private int code; + + @Getter + @Setter private long totalApiCallCount; + + @Getter + @Setter private long apiCallSuccessCount; + + @Getter + @Setter private long apiCallFailureCount; + + @Getter + @Setter private long totalPolicyGetCount; + + @Getter + @Setter private long totalPolicyPostCount; - private long totalTemplateGetCount; - private long totalTemplatePostCount; + + @Getter + @Setter + private long totalPolicyTypeGetCount; + + @Getter + @Setter + private long totalPolicyTypePostCount; + + @Getter + @Setter private long policyGetSuccessCount; + + @Getter + @Setter private long policyGetFailureCount; + + @Getter + @Setter private long policyPostSuccessCount; + + @Getter + @Setter private long policyPostFailureCount; - private long templateGetSuccessCount; - private long templateGetFailureCount; - private long templatePostSuccessCount; - private long templatePostFailureCount; - - /** - * Returns the code of this {@link StatisticsReport} instance. - * - * @return the code - */ - public int getCode() { - return code; - } - - /** - * Set code in this {@link StatisticsReport} instance. - * - * @param code the code to set - */ - public void setCode(final int code) { - this.code = code; - } - - /** - * Returns the totalApiCallCount of this {@link StatisticsReport} instance. - * - * @return the totalApiCallCount - */ - public long getTotalApiCallCount() { - return totalApiCallCount; - } - - /** - * Set totalApiCallCount in this {@link StatisticsReport} instance. - * - * @param totalApiCallCount the totalApiCallCount to set - */ - public void setTotalApiCallCount(final long totalApiCallCount) { - this.totalApiCallCount = totalApiCallCount; - } - - /** - * Returns the apiCallSuccessCount of this {@link StatisticsReport} instance. - * - * @return the apiCallSuccessCount - */ - public long getApiCallSuccessCount() { - return apiCallSuccessCount; - } - - /** - * Set apiCallSuccessCount in this {@link StatisticsReport} instance. - * - * @param apiCallSuccessCount the apiCallSuccessCount to set - */ - public void setApiCallSuccessCount(final long apiCallSuccessCount) { - this.apiCallSuccessCount = apiCallSuccessCount; - } - - /** - * Returns the apiCallFailureCount of this {@link StatisticsReport} instance. - * - * @return the apiCallFailureCount - */ - public long getApiCallFailureCount() { - return apiCallFailureCount; - } - - /** - * Set apiCallFailureCount in this {@link StatisticsReport} instance. - * - * @param apiCallFailureCount the apiCallFailureCount to set - */ - public void setApiCallFailureCount(final long apiCallFailureCount) { - this.apiCallFailureCount = apiCallFailureCount; - } - - /** - * Returns the totalPolicyGetCount of this {@link StatisticsReport} instance. - * - * @return the totalPolicyGetCount - */ - public long getTotalPolicyGetCount() { - return totalPolicyGetCount; - } - - /** - * Set totalPolicyGetCount in this {@link StatisticsReport} instance. - * - * @param totalPolicyGetCount the totalPolicyGetCount to set - */ - public void setTotalPolicyGetCount(final long totalPolicyGetCount) { - this.totalPolicyGetCount = totalPolicyGetCount; - } - - /** - * Returns the totalPolicyPostCount of this {@link StatisticsReport} instance. - * - * @return the totalPolicyPostCount - */ - public long getTotalPolicyPostCount() { - return totalPolicyPostCount; - } - - /** - * Set totalPolicyPostCount in this {@link StatisticsReport} instance. - * - * @param totalPolicyPostCount the totalPolicyPostCount to set - */ - public void setTotalPolicyPostCount(final long totalPolicyPostCount) { - this.totalPolicyPostCount = totalPolicyPostCount; - } - - /** - * Returns the totalTemplateGetCount of this {@link StatisticsReport} instance. - * - * @return the totalTemplateGetCount - */ - public long getTotalTemplateGetCount() { - return totalTemplateGetCount; - } - - /** - * Set totalTemplateGetCount in this {@link StatisticsReport} instance. - * - * @param totalTemplateGetCount the totalTemplateGetCount to set - */ - public void setTotalTemplateGetCount(final long totalTemplateGetCount) { - this.totalTemplateGetCount = totalTemplateGetCount; - } - - /** - * Returns the totalTemplatePostCount of this {@link StatisticsReport} instance. - * - * @return the totalTemplatePostCount - */ - public long getTotalTemplatePostCount() { - return totalTemplatePostCount; - } - - /** - * Set totalTemplatePostCount in this {@link StatisticsReport} instance. - * - * @param totalTemplatePostCount the totalTemplatePostCount to set - */ - public void setTotalTemplatePostCount(final long totalTemplatePostCount) { - this.totalTemplatePostCount = totalTemplatePostCount; - } - - /** - * Returns the policyGetSuccessCount of this {@link StatisticsReport} instance. - * - * @return the policyGetSuccessCount - */ - public long getPolicyGetSuccessCount() { - return policyGetSuccessCount; - } - - /** - * Set policyGetSuccessCount in this {@link StatisticsReport} instance. - * - * @param policyGetSuccessCount the policyGetSuccessCount to set - */ - public void setPolicyGetSuccessCount(final long policyGetSuccessCount) { - this.policyGetSuccessCount = policyGetSuccessCount; - } - - /** - * Returns the policyGetFailureCount of this {@link StatisticsReport} instance. - * - * @return the policyGetFailureCount - */ - public long getPolicyGetFailureCount() { - return policyGetFailureCount; - } - - /** - * Set policyGetFailureCount in this {@link StatisticsReport} instance. - * - * @param policyGetFailureCount the policyGetFailureCount to set - */ - public void setPolicyGetFailureCount(final long policyGetFailureCount) { - this.policyGetFailureCount = policyGetFailureCount; - } - - /** - * Returns the policyPostSuccessCount of this {@link StatisticsReport} instance. - * - * @return the policyPostSuccessCount - */ - public long getPolicyPostSuccessCount() { - return policyPostSuccessCount; - } - - /** - * Set policyPostSuccessCount in this {@link StatisticsReport} instance. - * - * @param policyPostSuccessCount the policyPostSuccessCount to set - */ - public void setPolicyPostSuccessCount(final long policyPostSuccessCount) { - this.policyPostSuccessCount = policyPostSuccessCount; - } - - /** - * Returns the policyPostFailureCount of this {@link StatisticsReport} instance. - * - * @return the policyPostFailureCount - */ - public long getPolicyPostFailureCount() { - return policyPostFailureCount; - } - - /** - * Set policyPostFailureCount in this {@link StatisticsReport} instance. - * - * @param policyPostFailureCount the policyPostFailureCount to set - */ - public void setPolicyPostFailureCount(final long policyPostFailureCount) { - this.policyPostFailureCount = policyPostFailureCount; - } - - /** - * Returns the templateGetSuccessCount of this {@link StatisticsReport} instance. - * - * @return the templateGetSuccessCount - */ - public long getTemplateGetSuccessCount() { - return templateGetSuccessCount; - } - - /** - * Set templateGetSuccessCount in this {@link StatisticsReport} instance. - * - * @param templateGetSuccessCount the templateGetSuccessCount to set - */ - public void setTemplateGetSuccessCount(final long templateGetSuccessCount) { - this.templateGetSuccessCount = templateGetSuccessCount; - } - - /** - * Returns the templateGetFailureCount of this {@link StatisticsReport} instance. - * - * @return the templateGetFailureCount - */ - public long getTemplateGetFailureCount() { - return templateGetFailureCount; - } - - /** - * Set templateGetFailureCount in this {@link StatisticsReport} instance. - * - * @param templateGetFailureCount the templateGetFailureCount to set - */ - public void setTemplateGetFailureCount(final long templateGetFailureCount) { - this.templateGetFailureCount = templateGetFailureCount; - } - - /** - * Returns the templatePostSuccessCount of this {@link StatisticsReport} instance. - * - * @return the templatePostSuccessCount - */ - public long getTemplatePostSuccessCount() { - return templatePostSuccessCount; - } - - /** - * Set templatePostSuccessCount in this {@link StatisticsReport} instance. - * - * @param templatePostSuccessCount the templatePostSuccessCount to set - */ - public void setTemplatePostSuccessCount(final long templatePostSuccessCount) { - this.templatePostSuccessCount = templatePostSuccessCount; - } - - /** - * Returns the templatePostFailureCount of this {@link StatisticsReport} instance. - * - * @return the templatePostFailureCount - */ - public long getTemplatePostFailureCount() { - return templatePostFailureCount; - } - - /** - * Set templatePostFailureCount in this {@link StatisticsReport} instance. - * - * @param templatePostFailureCount the templatePostFailureCount to set - */ - public void setTemplatePostFailureCount(final long templatePostFailureCount) { - this.templatePostFailureCount = templatePostFailureCount; - } - - /** - * {@inheritDoc}}. - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("StatisticsReport [code="); - builder.append(getCode()); - builder.append(", totalApiCallCount="); - builder.append(getTotalApiCallCount()); - builder.append(", apiCallSuccessCount="); - builder.append(getApiCallSuccessCount()); - builder.append(", apiCallFailureCount="); - builder.append(getApiCallFailureCount()); - builder.append(", totalPolicyGetCount="); - builder.append(getTotalPolicyGetCount()); - builder.append(", totalPolicyPostCount="); - builder.append(getTotalPolicyPostCount()); - builder.append(", totalTemplateGetCount="); - builder.append(getTotalTemplateGetCount()); - builder.append(", totalTemplatePostCount="); - builder.append(getTotalTemplatePostCount()); - builder.append(", policyGetSuccessCount="); - builder.append(getPolicyGetSuccessCount()); - builder.append(", policyGetFailureCount="); - builder.append(getPolicyGetFailureCount()); - builder.append(", policyPostSuccessCount="); - builder.append(getPolicyPostSuccessCount()); - builder.append(", policyPostFailureCount="); - builder.append(getPolicyPostFailureCount()); - builder.append(", templateGetSuccessCount="); - builder.append(getTemplateGetSuccessCount()); - builder.append(", templateGetFailureCount="); - builder.append(getTemplateGetFailureCount()); - builder.append(", templatePostSuccessCount="); - builder.append(getTemplatePostSuccessCount()); - builder.append(", templatePostFailureCount="); - builder.append(getTemplatePostFailureCount()); - builder.append("]"); - return builder.toString(); - } + + @Getter + @Setter + private long policyTypeGetSuccessCount; + + @Getter + @Setter + private long policyTypeGetFailureCount; + + @Getter + @Setter + private long policyTypePostSuccessCount; + + @Getter + @Setter + private long policyTypePostFailureCount; } diff --git a/main/src/main/java/org/onap/policy/api/main/rest/HealthCheckProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/HealthCheckProvider.java index 48387336..e59aee8b 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/HealthCheckProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/HealthCheckProvider.java @@ -21,7 +21,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.api.main.rest; +package org.onap.policy.api.main.rest.provider; import org.onap.policy.api.main.startstop.ApiActivator; import org.onap.policy.common.endpoints.report.HealthCheckReport; diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java new file mode 100644 index 00000000..3a8c238b --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy API + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.api.main.rest.provider; + +import org.onap.policy.model.tosca.ToscaPolicy; +import org.onap.policy.model.tosca.ToscaPolicyList; + +/** + * Class to provide all kinds of policy operations. + */ +public class PolicyProvider { + + private static final String POST_OK = "Successfully created"; + private static final String DELETE_OK = "Successfully deleted"; + + /** + * Retrieves a list of policies matching specified ID and version of both policy type and policy. + * + * @param policyTypeId the ID of policy type + * @param policyTypeVersion the version of policy type + * @param policyId the ID of policy + * @param policyVersion the version of policy + * + * @return the ToscaPolicyList object containing a list of policies matching specified fields + */ + public ToscaPolicyList fetchPolicies(String policyTypeId, String policyTypeVersion, + String policyId, String policyVersion) { + // placeholder + return new ToscaPolicyList(); + } + + /** + * Creates a new policy for a policy type ID and version. + * + * @param policyTypeId the ID of policy type + * @param policyTypeVersion the version of policy type + * @param body the entity body of policy + * + * @return a string message indicating the operation results + */ + public String createPolicy(String policyTypeId, String policyTypeVersion, ToscaPolicy body) { + // placeholder + return POST_OK; + } + + /** + * Deletes the policies matching specified ID and version of both policy type and policy. + * + * @param policyTypeId the ID of policy type + * @param policyTypeVersion the version of policy type + * @param policyId the ID of policy + * @param policyVersion the version of policy + * + * @return a string message indicating the operation results + */ + public String deletePolicies(String policyTypeId, String policyTypeVersion, + String policyId, String policyVersion) { + // placeholder + return DELETE_OK; + } +} diff --git a/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java new file mode 100644 index 00000000..6443d496 --- /dev/null +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyTypeProvider.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy API + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.api.main.rest.provider; + +import org.onap.policy.model.tosca.ToscaPolicyType; +import org.onap.policy.model.tosca.ToscaPolicyTypeList; + +/** + * Class to provide all kinds of policy type operations. + */ +public class PolicyTypeProvider { + + private static final String POST_OK = "Successfully created"; + private static final String DELETE_OK = "Successfully deleted"; + + /** + * Retrieves a list of policy types matching specified policy type ID and version. + * + * @param policyTypeId the ID of policy type + * @param policyTypeVersion the version of policy type + * + * @return the ToscaPolicyTypeList object containing a list of policy types matching specified fields + */ + public ToscaPolicyTypeList fetchPolicyTypes(String policyTypeId, String policyTypeVersion) { + // placeholder + return new ToscaPolicyTypeList(); + } + + /** + * Creates a new policy type. + * + * @param body the entity body of policy type + * + * @return a string message indicating the operation results + */ + public String createPolicyType(ToscaPolicyType body) { + // placeholder + return POST_OK; + } + + /** + * Delete the policy types matching specified policy type ID and version. + * + * @param policyTypeId the ID of policy type + * @param policyTypeVersion the version of policy type + * + * @return a string message indicating the operation results + */ + public String deletePolicyTypes(String policyTypeId, String policyTypeVersion) { + // placeholder + return DELETE_OK; + } +} diff --git a/main/src/main/java/org/onap/policy/api/main/rest/StatisticsProvider.java b/main/src/main/java/org/onap/policy/api/main/rest/provider/StatisticsProvider.java index e8f18404..3a842227 100644 --- a/main/src/main/java/org/onap/policy/api/main/rest/StatisticsProvider.java +++ b/main/src/main/java/org/onap/policy/api/main/rest/provider/StatisticsProvider.java @@ -1,8 +1,8 @@ /*- /*- * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ + * ONAP Policy API + * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,18 +21,22 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.api.main.rest; +package org.onap.policy.api.main.rest.provider; +import org.onap.policy.api.main.rest.ApiStatisticsManager; +import org.onap.policy.api.main.rest.StatisticsReport; import org.onap.policy.api.main.startstop.ApiActivator; /** * Class to fetch API statistics. + * + * @author Chenfei Gao (cgao@research.att.com) */ public class StatisticsProvider { - + /** * Return the current API statistics. - * + * * @return Report containing API statistics */ public StatisticsReport fetchCurrentStatistics() { @@ -43,16 +47,16 @@ public class StatisticsProvider { report.setApiCallFailureCount(ApiStatisticsManager.getApiCallFailureCount()); report.setTotalPolicyGetCount(ApiStatisticsManager.getTotalPolicyGetCount()); report.setTotalPolicyPostCount(ApiStatisticsManager.getTotalPolicyPostCount()); - report.setTotalTemplateGetCount(ApiStatisticsManager.getTotalTemplateGetCount()); - report.setTotalTemplatePostCount(ApiStatisticsManager.getTotalTemplatePostCount()); + report.setTotalPolicyTypeGetCount(ApiStatisticsManager.getTotalPolicyTypeGetCount()); + report.setTotalPolicyTypePostCount(ApiStatisticsManager.getTotalPolicyTypePostCount()); report.setPolicyGetSuccessCount(ApiStatisticsManager.getPolicyGetSuccessCount()); report.setPolicyGetFailureCount(ApiStatisticsManager.getPolicyGetFailureCount()); report.setPolicyPostSuccessCount(ApiStatisticsManager.getPolicyPostSuccessCount()); report.setPolicyPostFailureCount(ApiStatisticsManager.getPolicyPostFailureCount()); - report.setTemplateGetSuccessCount(ApiStatisticsManager.getTemplateGetSuccessCount()); - report.setTemplateGetFailureCount(ApiStatisticsManager.getTemplateGetFailureCount()); - report.setTemplatePostSuccessCount(ApiStatisticsManager.getTemplatePostSuccessCount()); - report.setTemplatePostFailureCount(ApiStatisticsManager.getTemplatePostFailureCount()); + report.setPolicyTypeGetSuccessCount(ApiStatisticsManager.getPolicyTypeGetSuccessCount()); + report.setPolicyTypeGetFailureCount(ApiStatisticsManager.getPolicyTypeGetFailureCount()); + report.setPolicyTypePostSuccessCount(ApiStatisticsManager.getPolicyTypePostSuccessCount()); + report.setPolicyTypePostFailureCount(ApiStatisticsManager.getPolicyTypePostFailureCount()); return report; } } diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java index 1ea42e0e..3c8b251d 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java @@ -26,7 +26,15 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.Properties; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Invocation; @@ -35,6 +43,7 @@ import javax.ws.rs.core.MediaType; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; +import org.junit.After; import org.junit.Test; import org.onap.policy.api.main.exception.PolicyApiException; import org.onap.policy.api.main.parameters.CommonTestData; @@ -46,8 +55,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Class to perform unit test of HealthCheckMonitor. + * Class to perform unit test of {@link ApiRestServer}. * + * @author Chenfei Gao (cgao@research.att.com) */ public class TestApiRestServer { @@ -56,15 +66,37 @@ public class TestApiRestServer { private static final String ALIVE = "alive"; private static final String SELF = "self"; private static final String NAME = "Policy API"; + private static final String HEALTHCHECK_ENDPOINT = "healthcheck"; + private static final String STATISTICS_ENDPOINT = "statistics"; + private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore"; + private Main main; + private ApiRestServer restServer; + + /** + * Method for cleanup after each test. + */ + @After + public void teardown() { + try { + if (NetworkUtil.isTcpPortOpen("localhost", 6969, 1, 1000L)) { + if (main != null) { + stopApiService(main); + } else if (restServer != null) { + restServer.stop(); + } + } + } catch (InterruptedException | IOException | PolicyApiException exp) { + LOGGER.error("teardown failed", exp); + } + } @Test - public void testHealthCheckSuccess() throws PolicyApiException, InterruptedException { - final String reportString = "Report [name=Policy API, url=self, healthy=true, code=200, message=alive]"; + public void testHealthCheckSuccess() { try { - final Main main = startApiService(); - final HealthCheckReport report = performHealthCheck(); - validateReport(NAME, SELF, true, 200, ALIVE, reportString, report); - stopApiService(main); + main = startApiService(true); + final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT); + final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); + validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report); } catch (final Exception exp) { LOGGER.error("testHealthCheckSuccess failed", exp); fail("Test should not throw an exception"); @@ -72,26 +104,109 @@ public class TestApiRestServer { } @Test - public void testHealthCheckFailure() throws InterruptedException { - final String reportString = "Report [name=Policy API, url=self, healthy=false, code=500, message=not alive]"; + public void testHealthCheckFailure() throws InterruptedException, IOException { final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); restServerParams.setName(CommonTestData.API_GROUP_NAME); - final ApiRestServer restServer = new ApiRestServer(restServerParams); + restServer = new ApiRestServer(restServerParams); try { restServer.start(); - final HealthCheckReport report = performHealthCheck(); - validateReport(NAME, SELF, false, 500, NOT_ALIVE, reportString, report); + final Invocation.Builder invocationBuilder = sendHttpRequest(HEALTHCHECK_ENDPOINT); + final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); + validateHealthCheckReport(NAME, SELF, false, 500, NOT_ALIVE, report); assertTrue(restServer.isAlive()); assertTrue(restServer.toString().startsWith("ApiRestServer [servers=")); - restServer.shutdown(); } catch (final Exception exp) { LOGGER.error("testHealthCheckFailure failed", exp); fail("Test should not throw an exception"); } } - private Main startApiService() { - final String[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters.json" }; + @Test + public void testHttpsHealthCheckSuccess() { + try { + main = startApiService(false); + final Invocation.Builder invocationBuilder = sendHttpsRequest(HEALTHCHECK_ENDPOINT); + final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); + validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report); + } catch (final Exception exp) { + LOGGER.error("testHttpsHealthCheckSuccess failed", exp); + fail("Test should not throw an exception"); + } + } + + @Test + public void testApiStatistics_200() { + try { + main = startApiService(true); + Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT); + StatisticsReport report = invocationBuilder.get(StatisticsReport.class); + validateStatisticsReport(report, 0, 200); + updateApiStatistics(); + invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT); + report = invocationBuilder.get(StatisticsReport.class); + validateStatisticsReport(report, 1, 200); + ApiStatisticsManager.resetAllStatistics(); + } catch (final Exception exp) { + LOGGER.error("testApiStatistics_200 failed", exp); + fail("Test should not throw an exception"); + } + } + + @Test + public void testApiStatistics_500() { + final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); + restServerParams.setName(CommonTestData.API_GROUP_NAME); + restServer = new ApiRestServer(restServerParams); + try { + restServer.start(); + final Invocation.Builder invocationBuilder = sendHttpRequest(STATISTICS_ENDPOINT); + final StatisticsReport report = invocationBuilder.get(StatisticsReport.class); + validateStatisticsReport(report, 0, 500); + ApiStatisticsManager.resetAllStatistics(); + } catch (final Exception exp) { + LOGGER.error("testApiStatistics_500 failed", exp); + fail("Test should not throw an exception"); + } + } + + @Test + public void testHttpsApiStatistics() { + try { + main = startApiService(false); + final Invocation.Builder invocationBuilder = sendHttpsRequest(STATISTICS_ENDPOINT); + final StatisticsReport report = invocationBuilder.get(StatisticsReport.class); + validateStatisticsReport(report, 0, 200); + } catch (final Exception exp) { + LOGGER.error("testHttpsApiStatistics failed", exp); + fail("Test should not throw an exception"); + } + } + + @Test + public void testApiStatisticsConstructorIsPrivate() { + try { + final Constructor<ApiStatisticsManager> constructor = ApiStatisticsManager.class.getDeclaredConstructor(); + assertTrue(Modifier.isPrivate(constructor.getModifiers())); + constructor.setAccessible(true); + constructor.newInstance(); + } catch (final Exception exp) { + assertTrue(exp.getCause().toString().contains("Instantiation of the class is not allowed")); + } + } + + private Main startApiService(final boolean http) { + final String[] apiConfigParameters = new String[2]; + if (http) { + apiConfigParameters[0] = "-c"; + apiConfigParameters[1] = "parameters/ApiConfigParameters.json"; + } else { + final Properties systemProps = System.getProperties(); + systemProps.put("javax.net.ssl.keyStore", KEYSTORE); + systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap"); + System.setProperties(systemProps); + apiConfigParameters[0] = "-c"; + apiConfigParameters[1] = "parameters/ApiConfigParameters_Https.json"; + } return new Main(apiConfigParameters); } @@ -99,30 +214,100 @@ public class TestApiRestServer { main.shutdown(); } - private HealthCheckReport performHealthCheck() throws InterruptedException, IOException { + private Invocation.Builder sendHttpRequest(final String endpoint) throws Exception { 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 WebTarget webTarget = client.target("http://localhost:6969/policy/api/v1/" + endpoint); final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); - + if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) { throw new IllegalStateException("cannot connect to port 6969"); } - return invocationBuilder.get(HealthCheckReport.class); + return invocationBuilder; + } + + private Invocation.Builder sendHttpsRequest(final String endpoint) throws Exception { + + final TrustManager[] noopTrustManager = new TrustManager[] { new X509TrustManager() { + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + @Override + public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {} + + @Override + public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) {} + } }; + + final SSLContext sc = SSLContext.getInstance("TLSv1.2"); + sc.init(null, noopTrustManager, new SecureRandom()); + final ClientBuilder clientBuilder = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, + session) -> true); + final Client client = clientBuilder.build(); + final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"); + client.register(feature); + + final WebTarget webTarget = client.target("https://localhost:6969/policy/api/v1/" + endpoint); + + final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); + + if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) { + throw new IllegalStateException("cannot connect to port 6969"); + } + return invocationBuilder; + } + + private void updateApiStatistics() { + ApiStatisticsManager.updateTotalApiCallCount(); + ApiStatisticsManager.updateApiCallSuccessCount(); + ApiStatisticsManager.updateApiCallFailureCount(); + ApiStatisticsManager.updateTotalPolicyGetCount(); + ApiStatisticsManager.updateTotalPolicyPostCount(); + ApiStatisticsManager.updateTotalPolicyTypeGetCount(); + ApiStatisticsManager.updateTotalPolicyTypePostCount(); + ApiStatisticsManager.updatePolicyGetSuccessCount(); + ApiStatisticsManager.updatePolicyGetFailureCount(); + ApiStatisticsManager.updatePolicyPostSuccessCount(); + ApiStatisticsManager.updatePolicyPostFailureCount(); + ApiStatisticsManager.updatePolicyTypeGetSuccessCount(); + ApiStatisticsManager.updatePolicyTypeGetFailureCount(); + ApiStatisticsManager.updatePolicyTypePostSuccessCount(); + ApiStatisticsManager.updatePolicyTypePostFailureCount(); + } + + private void validateStatisticsReport(final StatisticsReport report, final int count, final int code) { + assertEquals(code, report.getCode()); + assertEquals(count, report.getTotalApiCallCount()); + assertEquals(count, report.getApiCallSuccessCount()); + assertEquals(count, report.getApiCallFailureCount()); + assertEquals(count, report.getTotalPolicyGetCount()); + assertEquals(count, report.getTotalPolicyPostCount()); + assertEquals(count, report.getTotalPolicyTypeGetCount()); + assertEquals(count, report.getTotalPolicyTypePostCount()); + assertEquals(count, report.getPolicyGetSuccessCount()); + assertEquals(count, report.getPolicyGetFailureCount()); + assertEquals(count, report.getPolicyPostSuccessCount()); + assertEquals(count, report.getPolicyPostFailureCount()); + assertEquals(count, report.getPolicyTypeGetSuccessCount()); + assertEquals(count, report.getPolicyTypeGetFailureCount()); + assertEquals(count, report.getPolicyTypePostSuccessCount()); + assertEquals(count, report.getPolicyTypePostFailureCount()); } - private void validateReport(final String name, final String url, final boolean healthy, final int code, - final String message, final String reportString, final HealthCheckReport report) { + private void validateHealthCheckReport(final String name, final String url, final boolean healthy, final int code, + final String message, 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()); } -} +}
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatistics.java b/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatistics.java deleted file mode 100644 index 5d535678..00000000 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestApiStatistics.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.api.main.rest; - -import static org.junit.Assert.assertEquals; -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.api.main.exception.PolicyApiException; -import org.onap.policy.api.main.parameters.CommonTestData; -import org.onap.policy.api.main.parameters.RestServerParameters; -import org.onap.policy.api.main.startstop.Main; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class to perform unit test of {@link ApiRestController}. - */ -public class TestApiStatistics { - - private static final Logger LOGGER = LoggerFactory.getLogger(TestApiStatistics.class); - - @Test - public void testApiStatistics_200() throws PolicyApiException, InterruptedException { - try { - final Main main = startApiService(); - StatisticsReport report = getApiStatistics(); - validateReport(report, 0, 200); - updateApiStatistics(); - report = getApiStatistics(); - validateReport(report, 1, 200); - stopApiService(main); - ApiStatisticsManager.resetAllStatistics(); - } catch (final Exception exp) { - LOGGER.error("testApiStatistics_200 failed", exp); - fail("Test should not throw an exception"); - } - } - - @Test - public void testApiStatistics_500() throws InterruptedException { - final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); - restServerParams.setName(CommonTestData.API_GROUP_NAME); - - final ApiRestServer restServer = new ApiRestServer(restServerParams); - try { - restServer.start(); - final StatisticsReport report = getApiStatistics(); - validateReport(report, 0, 500); - restServer.shutdown(); - ApiStatisticsManager.resetAllStatistics(); - } catch (final Exception exp) { - LOGGER.error("testApiStatistics_500 failed", exp); - fail("Test should not throw an exception"); - } - } - - - private Main startApiService() { - final String[] distributionConfigParameters = { "-c", "parameters/ApiConfigParameters.json" }; - return new Main(distributionConfigParameters); - } - - private void stopApiService(final Main main) throws PolicyApiException { - main.shutdown(); - } - - private StatisticsReport getApiStatistics() throws InterruptedException, IOException { - 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/statistics"); - - final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); - - if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) { - throw new IllegalStateException("cannot connect to port 6969"); - } - return invocationBuilder.get(StatisticsReport.class); - } - - private void updateApiStatistics() { - ApiStatisticsManager.updateTotalApiCallCount(); - ApiStatisticsManager.updateApiCallSuccessCount(); - ApiStatisticsManager.updateApiCallFailureCount(); - ApiStatisticsManager.updateTotalPolicyGetCount(); - ApiStatisticsManager.updateTotalPolicyPostCount(); - ApiStatisticsManager.updateTotalTemplateGetCount(); - ApiStatisticsManager.updateTotalTemplatePostCount(); - ApiStatisticsManager.updatePolicyGetSuccessCount(); - ApiStatisticsManager.updatePolicyGetFailureCount(); - ApiStatisticsManager.updatePolicyPostSuccessCount(); - ApiStatisticsManager.updatePolicyPostFailureCount(); - ApiStatisticsManager.updateTemplateGetSuccessCount(); - ApiStatisticsManager.updateTemplateGetFailureCount(); - ApiStatisticsManager.updateTemplatePostSuccessCount(); - ApiStatisticsManager.updateTemplatePostFailureCount(); - } - - private void validateReport(final StatisticsReport report, final int count, final int code) { - assertEquals(code, report.getCode()); - assertEquals(count, report.getTotalApiCallCount()); - assertEquals(count, report.getApiCallSuccessCount()); - assertEquals(count, report.getApiCallFailureCount()); - assertEquals(count, report.getTotalPolicyGetCount()); - assertEquals(count, report.getTotalPolicyPostCount()); - assertEquals(count, report.getTotalTemplateGetCount()); - assertEquals(count, report.getTotalTemplatePostCount()); - assertEquals(count, report.getPolicyGetSuccessCount()); - assertEquals(count, report.getPolicyGetFailureCount()); - assertEquals(count, report.getPolicyPostSuccessCount()); - assertEquals(count, report.getPolicyPostFailureCount()); - assertEquals(count, report.getTemplateGetSuccessCount()); - assertEquals(count, report.getTemplateGetFailureCount()); - assertEquals(count, report.getTemplatePostSuccessCount()); - assertEquals(count, report.getTemplatePostFailureCount()); - } -} diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsApiRestServer.java b/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsApiRestServer.java deleted file mode 100644 index d080350a..00000000 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsApiRestServer.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.api.main.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import java.util.Properties; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import org.junit.Test; -import org.onap.policy.api.main.exception.PolicyApiException; -import org.onap.policy.api.main.startstop.Main; -import org.onap.policy.common.endpoints.report.HealthCheckReport; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class to perform unit test of https set on API REST server. - */ -public class TestHttpsApiRestServer { - - private static final Logger LOGGER = LoggerFactory.getLogger(TestHttpsApiRestServer.class); - private static final String ALIVE = "alive"; - private static final String SELF = "self"; - private static final String NAME = "Policy API"; - private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore"; - - @Test - public void testHttpsHealthCheckSuccess() { - final String reportString = "Report [name=Policy API, url=self, healthy=true, code=200, message=alive]"; - try { - final Main main = startApiService(); - final HealthCheckReport report = performHealthCheck(); - validateReport(NAME, SELF, true, 200, ALIVE, reportString, report); - stopApiService(main); - } catch (final Exception exp) { - LOGGER.error("testHttpsHealthCheckSuccess failed", exp); - fail("Test should not throw an exception"); - } - } - - private Main startApiService() { - final Properties systemProps = System.getProperties(); - systemProps.put("javax.net.ssl.keyStore", KEYSTORE); - systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap"); - System.setProperties(systemProps); - - final String[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters_Https.json" }; - return new Main(apiConfigParameters); - } - - private void stopApiService(final Main main) throws PolicyApiException { - main.shutdown(); - } - - private HealthCheckReport performHealthCheck() throws Exception { - - final TrustManager[] noopTrustManager = new TrustManager[] { new X509TrustManager() { - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - @Override - public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) { - } - - @Override - public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) { - } - } }; - - final SSLContext sc = SSLContext.getInstance("TLSv1.2"); - sc.init(null, noopTrustManager, new SecureRandom()); - final ClientBuilder clientBuilder = - ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); - final Client client = clientBuilder.build(); - final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"); - client.register(feature); - - final WebTarget webTarget = client.target("https://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"); - } - return invocationBuilder.get(HealthCheckReport.class); - } - - 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()); - } -} diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsStatisticApiRestServer.java b/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsStatisticApiRestServer.java deleted file mode 100644 index 6b992442..00000000 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestHttpsStatisticApiRestServer.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.api.main.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.cert.X509Certificate; -import java.util.Properties; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import org.junit.Test; -import org.onap.policy.api.main.exception.PolicyApiException; -import org.onap.policy.api.main.startstop.Main; -import org.onap.policy.common.utils.network.NetworkUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class to perform unit test of API statistics via https set on API REST server. - */ -public class TestHttpsStatisticApiRestServer { - - private static final Logger LOGGER = LoggerFactory.getLogger(TestHttpsStatisticApiRestServer.class); - private static String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore"; - - @Test - public void testHttpsApiStatistic() - throws PolicyApiException, InterruptedException, KeyManagementException, NoSuchAlgorithmException { - final String reportString = "StatisticsReport [code=200, totalApiCallCount=0, apiCallSuccessCount=0, " - + "apiCallFailureCount=0, " + "totalPolicyGetCount=0, totalPolicyPostCount=0, " - + "totalTemplateGetCount=0, totalTemplatePostCount=0, " - + "policyGetSuccessCount=0, policyGetFailureCount=0, " - + "policyPostSuccessCount=0, policyPostFailureCount=0, " - + "templateGetSuccessCount=0, templateGetFailureCount=0, " - + "templatePostSuccessCount=0, templatePostFailureCount=0]"; - try { - final Main main = startApiService(); - final StatisticsReport report = performStatisticCheck(); - validateReport(200, 0, reportString, report); - stopApiService(main); - } catch (final Exception exp) { - LOGGER.error("testHttpsApiStatistic failed", exp); - fail("Test should not throw an exception"); - } - } - - private Main startApiService() { - final Properties systemProps = System.getProperties(); - systemProps.put("javax.net.ssl.keyStore", KEYSTORE); - systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap"); - System.setProperties(systemProps); - - final String[] apiConfigParameters = { "-c", "parameters/ApiConfigParameters_Https.json" }; - return new Main(apiConfigParameters); - } - - private void stopApiService(final Main main) throws PolicyApiException { - main.shutdown(); - } - - private StatisticsReport performStatisticCheck() throws Exception { - - final TrustManager[] noopTrustManager = new TrustManager[] { new X509TrustManager() { - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - @Override - public void checkClientTrusted(final java.security.cert.X509Certificate[] certs, final String authType) { - } - - @Override - public void checkServerTrusted(final java.security.cert.X509Certificate[] certs, final String authType) { - } - } }; - - final SSLContext sc = SSLContext.getInstance("TLSv1.2"); - sc.init(null, noopTrustManager, new SecureRandom()); - final ClientBuilder clientBuilder = - ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); - final Client client = clientBuilder.build(); - final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"); - client.register(feature); - - final WebTarget webTarget = client.target("https://localhost:6969/statistics"); - - final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); - - if (!NetworkUtil.isTcpPortOpen("localhost", 6969, 6, 10000L)) { - throw new IllegalStateException("cannot connect to port 6969"); - } - return invocationBuilder.get(StatisticsReport.class); - } - - private void validateReport(final int code, final int count, - final String reportString, final StatisticsReport report) { - assertEquals(code, report.getCode()); - assertEquals(count, report.getTotalApiCallCount()); - assertEquals(count, report.getApiCallSuccessCount()); - assertEquals(count, report.getApiCallFailureCount()); - assertEquals(count, report.getTotalPolicyGetCount()); - assertEquals(count, report.getTotalPolicyPostCount()); - assertEquals(count, report.getTotalTemplateGetCount()); - assertEquals(count, report.getTotalTemplatePostCount()); - assertEquals(count, report.getPolicyGetSuccessCount()); - assertEquals(count, report.getPolicyGetFailureCount()); - assertEquals(count, report.getPolicyPostSuccessCount()); - assertEquals(count, report.getPolicyPostFailureCount()); - assertEquals(count, report.getTemplateGetSuccessCount()); - assertEquals(count, report.getTemplateGetFailureCount()); - assertEquals(count, report.getTemplatePostSuccessCount()); - assertEquals(count, report.getTemplatePostFailureCount()); - assertEquals(reportString, report.toString()); - } -} diff --git a/main/src/test/java/org/onap/policy/api/main/rest/TestStatisticsReport.java b/main/src/test/java/org/onap/policy/api/main/rest/TestStatisticsReport.java index 75b89c15..e240f683 100644 --- a/main/src/test/java/org/onap/policy/api/main/rest/TestStatisticsReport.java +++ b/main/src/test/java/org/onap/policy/api/main/rest/TestStatisticsReport.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= - * ONAP Policy API - * ================================================================================ + * ONAP Policy API + * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -30,10 +30,13 @@ import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; import org.junit.Test; +import org.onap.policy.api.main.rest.StatisticsReport; import org.onap.policy.common.utils.validation.ToStringTester; /** * Class to perform unit testing of {@link StatisticsReport}. + * + * @author Chenfei Gao (cgao@research.att.com) */ public class TestStatisticsReport { @@ -26,7 +26,7 @@ <parent> <groupId>org.onap.policy.parent</groupId> <artifactId>integration</artifactId> - <version>2.0.0</version> + <version>2.1.0-SNAPSHOT</version> <relativePath /> </parent> @@ -47,6 +47,7 @@ <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis> <policy.common.version>1.4.0-SNAPSHOT</policy.common.version> + <policy.models.version>2.0.0-SNAPSHOT</policy.models.version> </properties> <modules> |