From 4a3cfdff6285a516f1e05d4cebd748ea623177e5 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Tue, 12 Mar 2019 11:53:22 -0400 Subject: Add PDP Group Deploy and Delete REST API stubs Note: this will not build until the models-pap code has been added. Added PDP group Delete methods, with and without version. Added checks for OK status codes. Added topic configuration. Still does not have the "simplified" PDP Group deploy/undeploy. Still won't build without "Move PDP Group classes to concepts subdirectory". Will add junit tests for code changes in another review. Updated comments about unlocking after updates. Made ServiceManager final. Included topic start/stop actions. Fixed parameter comment. Removed unneeded parameters from json files. Fixed argument test in shell script. Updated licenses. Change-Id: I6176d51918ae758e04fb68562dc9ca70534137d4 Issue-ID: POLICY-1542 Signed-off-by: Jim Hahn --- main/pom.xml | 5 + .../org/onap/policy/pap/main/comm/PdpClient.java | 101 --------------- .../policy/pap/main/comm/PdpClientException.java | 49 ------- .../pap/main/parameters/PapParameterGroup.java | 70 ++-------- .../pap/main/parameters/RestServerParameters.java | 141 +++------------------ .../policy/pap/main/rest/PapRestControllerV1.java | 61 ++++++++- .../onap/policy/pap/main/rest/PapRestServer.java | 4 +- .../pap/main/rest/PdpGroupDeleteControllerV1.java | 132 +++++++++++++++++++ .../pap/main/rest/PdpGroupDeleteProvider.java | 58 +++++++++ .../pap/main/rest/PdpGroupDeployControllerV1.java | 88 +++++++++++++ .../pap/main/rest/PdpGroupDeployProvider.java | 57 +++++++++ .../org/onap/policy/pap/main/startstop/Main.java | 18 ++- .../policy/pap/main/startstop/PapActivator.java | 61 ++++++--- .../main/startstop/PapCommandLineArguments.java | 54 ++++++++ .../pap/main/comm/PdpClientExceptionTest.java | 35 ----- .../onap/policy/pap/main/comm/PdpClientTest.java | 141 --------------------- .../policy/pap/main/parameters/CommonTestData.java | 74 +++++++++-- .../pap/main/parameters/TestPapParameterGroup.java | 36 +++--- .../main/parameters/TestPapParameterHandler.java | 9 +- .../policy/pap/main/rest/CommonPapRestServer.java | 115 +++++++++-------- .../pap/main/rest/PapRestControllerV1Test.java | 63 +++++++++ .../main/rest/TestHealthCheckRestControllerV1.java | 3 + .../main/rest/TestPdpGroupDeleteControllerV1.java | 79 ++++++++++++ .../main/rest/TestPdpGroupDeployControllerV1.java | 78 ++++++++++++ .../main/rest/TestStatisticsRestControllerV1.java | 3 + .../onap/policy/pap/main/startstop/TestMain.java | 3 +- .../pap/main/startstop/TestPapActivator.java | 16 ++- .../src/test/resources/parameters/topic.properties | 22 ++++ .../src/main/docker/policy-pap.sh | 17 ++- .../src/main/package/tarball/assembly.xml | 2 + .../src/main/resources/etc/topic.properties | 25 ++++ pom.xml | 3 +- 32 files changed, 989 insertions(+), 634 deletions(-) delete mode 100644 main/src/main/java/org/onap/policy/pap/main/comm/PdpClient.java delete mode 100644 main/src/main/java/org/onap/policy/pap/main/comm/PdpClientException.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java delete mode 100644 main/src/test/java/org/onap/policy/pap/main/comm/PdpClientExceptionTest.java delete mode 100644 main/src/test/java/org/onap/policy/pap/main/comm/PdpClientTest.java create mode 100644 main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java create mode 100644 main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteControllerV1.java create mode 100644 main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java create mode 100644 main/src/test/resources/parameters/topic.properties create mode 100644 packages/policy-pap-tarball/src/main/resources/etc/topic.properties diff --git a/main/pom.xml b/main/pom.xml index 6cf42d09..01c41545 100644 --- a/main/pom.xml +++ b/main/pom.xml @@ -63,6 +63,11 @@ gson ${policy.common.version} + + org.onap.policy.models + models-pap + ${policy.models.version} + org.projectlombok lombok diff --git a/main/src/main/java/org/onap/policy/pap/main/comm/PdpClient.java b/main/src/main/java/org/onap/policy/pap/main/comm/PdpClient.java deleted file mode 100644 index 7919912a..00000000 --- a/main/src/main/java/org/onap/policy/pap/main/comm/PdpClient.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP PAP - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.comm; - -import java.util.List; -import lombok.Getter; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.utils.coder.Coder; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Client for communication with PDPs. - */ -public class PdpClient { - private static final Logger logger = LoggerFactory.getLogger(PdpClient.class); - - /** - * Coder used to encode messages being sent to PDPs. - */ - private static final Coder CODER = new StandardCoder(); - - /** - * Topic to which messages are published. - */ - @Getter - private final String topic; - - /** - * Where messages are published. - */ - private final TopicSink sink; - - /** - * Constructs the object. - * - * @param topic topic to which messages should be published - * @throws PdpClientException if the topic does not exist - */ - public PdpClient(String topic) throws PdpClientException { - this.topic = topic; - - List lst = getTopicSinks(topic); - if (lst.isEmpty()) { - throw new PdpClientException("no sinks for topic: " + topic); - } - - this.sink = lst.get(0); - } - - /** - * Sends a message to the PDPs via the topic, after encoding the message as json. - * - * @param message message to be encoded and sent - * @return {@code true} if the message was successfully sent/enqueued, {@code false} - * otherwise - */ - public boolean send(Object message) { - try { - String json = CODER.encode(message); - return sink.send(json); - - } catch (RuntimeException | CoderException e) { - logger.warn("send to {} failed because of {}", topic, e.getMessage(), e); - return false; - } - } - - // the remaining methods are wrappers that can be overridden by junit tests - - /** - * Gets the sinks for a given topic. - * - * @param topic the topic of interest - * @return the sinks for the topic - */ - protected List getTopicSinks(String topic) { - return TopicEndpoint.manager.getTopicSinks(topic); - } -} diff --git a/main/src/main/java/org/onap/policy/pap/main/comm/PdpClientException.java b/main/src/main/java/org/onap/policy/pap/main/comm/PdpClientException.java deleted file mode 100644 index 547812f2..00000000 --- a/main/src/main/java/org/onap/policy/pap/main/comm/PdpClientException.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP PAP - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.comm; - -/** - * Exception thrown by PDP client classes. - */ -public class PdpClientException extends Exception { - private static final long serialVersionUID = 1L; - - public PdpClientException() { - super(); - } - - public PdpClientException(String message) { - super(message); - } - - public PdpClientException(Throwable cause) { - super(cause); - } - - public PdpClientException(String message, Throwable cause) { - super(message, cause); - } - - public PdpClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - -} diff --git a/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java index 09f87049..dce21f98 100644 --- a/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java +++ b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,77 +21,28 @@ 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; +import lombok.Getter; +import org.onap.policy.common.parameters.ParameterGroupImpl; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; /** * Class to hold all parameters needed for pap component. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -public class PapParameterGroup implements ParameterGroup { - private String name; +@NotNull +@NotBlank +@Getter +public class PapParameterGroup extends ParameterGroupImpl { 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, final RestServerParameters restServerParameters) { - this.name = name; - this.restServerParameters = restServerParameters; - } - - /** - * Return the name of this parameter group instance. - * - * @return name the parameter group name - */ - @Override - public String getName() { - return name; - } - - /** - * Set the name of this parameter group instance. - * - * @param name the parameter group name - */ - @Override - public void setName(final String name) { - this.name = name; - } - - /** - * Return the restServerParameters of this parameter group instance. - * - * @return the restServerParameters - */ - public RestServerParameters getRestServerParameters() { - return restServerParameters; - } - - /** - * Validate the parameter group. - * - * @return the result of the validation - */ - @Override - public GroupValidationResult validate() { - final GroupValidationResult validationResult = new GroupValidationResult(this); - 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; + public PapParameterGroup(final String name) { + super(name); } } 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 index 6b1e3f82..99b346e1 100644 --- 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 @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,144 +21,32 @@ 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; +import lombok.Getter; +import org.onap.policy.common.parameters.ParameterGroupImpl; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; /** * 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; +@NotNull +@NotBlank +@Getter +public class RestServerParameters extends ParameterGroupImpl { private String host; + + @Min(value = 1) private int port; + private String userName; private String password; private boolean https; private boolean aaf; - /** - * Constructor for instantiating RestServerParameters. - * - * @param host the host name - * @param port the port - * @param userName the user name - * @param password the password - * @param https the https flag - * @param aaf the aaf flag - */ - public RestServerParameters(final String host, final int port, final String userName, final String password, - final boolean https, final boolean aaf) { - super(); - this.host = host; - this.port = port; - this.userName = userName; - this.password = password; - this.https = https; - this.aaf = aaf; - } - - /** - * 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; - } - - /** - * Return the https flag of this RestServerParameters instance. - * - * @return the https flag - */ - public boolean isHttps() { - return https; - } - - /** - * Return the aaf flag of this RestServerParameters instance. - * - * @return the aaf flag - */ - public boolean isAaf() { - return aaf; - } - - /** - * 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; + public RestServerParameters() { + super("RestServerParameters"); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java index bd182239..fb5d2d89 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * Modifications 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. @@ -28,15 +28,18 @@ import io.swagger.annotations.SecurityDefinition; import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.Tag; import java.net.HttpURLConnection; +import java.util.UUID; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.ResponseBuilder; /** * Version v1 common superclass to provide REST endpoints for PAP component. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ +// @formatter:off @Path("/policy/pap/v1") @Api(value = "Policy Administration (PAP) API") @Produces(MediaType.APPLICATION_JSON) @@ -48,12 +51,36 @@ import javax.ws.rs.core.MediaType; + " ensuring that policies are available to users, that policies are executing correctly," + " and that the state and status of policies is monitored", version = "v1.0", title = "Policy Administration"), - consumes = {MediaType.APPLICATION_JSON}, produces = {MediaType.APPLICATION_JSON}, + consumes = {MediaType.APPLICATION_JSON}, + produces = {MediaType.APPLICATION_JSON}, schemes = {SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS}, tags = {@Tag(name = "policy-administration", description = "Policy Administration Service Operations")}, - securityDefinition = @SecurityDefinition( - basicAuthDefinitions = {@BasicAuthDefinition(key = "basicAuth")})) + securityDefinition = @SecurityDefinition(basicAuthDefinitions = {@BasicAuthDefinition(key = "basicAuth")})) +// @formatter:on public class PapRestControllerV1 { + public static final String EXTENSION_NAME = "interface info"; + + public static final String API_VERSION_NAME = "api-version"; + public static final String API_VERSION = "1.0.0"; + + public static final String LAST_MOD_NAME = "last-mod-release"; + public static final String LAST_MOD_RELEASE = "Dublin"; + + public static final String VERSION_MINOR_NAME = "X-MinorVersion"; + public static final String VERSION_MINOR_DESCRIPTION = + "Used to request or communicate a MINOR version back from the client" + + " to the server, and from the server back to the client"; + + public static final String VERSION_PATCH_NAME = "X-PatchVersion"; + public static final String VERSION_PATCH_DESCRIPTION = "Used only to communicate a PATCH version in a response for" + + " troubleshooting purposes only, and will not be provided by" + " the client on request"; + + public static final String VERSION_LATEST_NAME = "X-LatestVersion"; + public static final String VERSION_LATEST_DESCRIPTION = "Used only to communicate an API's latest version"; + + public static final String REQUEST_ID_NAME = "X-ONAP-RequestID"; + public static final String REQUEST_ID_HDR_DESCRIPTION = "Used to track REST transactions for logging purpose"; + public static final String REQUEST_ID_PARAM_DESCRIPTION = "RequestID for http transaction"; public static final String AUTHORIZATION_TYPE = "basicAuth"; @@ -64,4 +91,30 @@ public class PapRestControllerV1 { public static final String AUTHENTICATION_ERROR_MESSAGE = "Authentication Error"; public static final String AUTHORIZATION_ERROR_MESSAGE = "Authorization Error"; public static final String SERVER_ERROR_MESSAGE = "Internal Server Error"; + + /** + * Adds version headers to the response. + * + * @param respBuilder response builder + * @return the response builder, with version headers + */ + public ResponseBuilder addVersionControlHeaders(ResponseBuilder respBuilder) { + return respBuilder.header(VERSION_MINOR_NAME, "0").header(VERSION_PATCH_NAME, "0").header(VERSION_LATEST_NAME, + "1.0.0"); + } + + /** + * Adds logging headers to the response. + * + * @param respBuilder response builder + * @return the response builder, with version logging + */ + public ResponseBuilder addLoggingHeaders(ResponseBuilder respBuilder, UUID requestId) { + if (requestId == null) { + // Generate a random uuid if client does not embed requestId in rest request + return respBuilder.header(REQUEST_ID_NAME, UUID.randomUUID()); + } + + return respBuilder.header(REQUEST_ID_NAME, requestId); + } } 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 index 6064a14f..582c10d2 100644 --- 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 @@ -92,7 +92,9 @@ public class PapRestServer implements Startable { Integer.toString(restServerParameters.getPort())); props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, String.join(",", HealthCheckRestControllerV1.class.getCanonicalName(), - StatisticsRestControllerV1.class.getCanonicalName())); + StatisticsRestControllerV1.class.getCanonicalName(), + PdpGroupDeployControllerV1.class.getCanonicalName(), + PdpGroupDeleteControllerV1.class.getCanonicalName())); props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "false"); props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "true"); props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_AUTH_USERNAME_SUFFIX, diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java new file mode 100644 index 00000000..46982183 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java @@ -0,0 +1,132 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.rest; + +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.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.ResponseHeader; +import java.util.UUID; +import javax.ws.rs.DELETE; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.policy.models.pap.concepts.PdpGroupDeleteResponse; + +/** + * Class to provide REST end points for PAP component to delete a PDP group. + */ +public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 { + + private final PdpGroupDeleteProvider provider = new PdpGroupDeleteProvider(); + + /** + * Deletes a PDP group. + * + * @param requestId request ID used in ONAP logging + * @param groupName name of the PDP group to be deleted + * @return a response + */ + // @formatter:off + @DELETE + @Path("pdps/groups/{name}") + @ApiOperation(value = "Delete PDP Group", + notes = "Deletes a PDP Group, returning optional error details", + response = PdpGroupDeleteResponse.class, + tags = {"Policy Administration (PAP) API"}, + authorizations = @Authorization(value = AUTHORIZATION_TYPE), + responseHeaders = { + @ResponseHeader(name = VERSION_MINOR_NAME, description = VERSION_MINOR_DESCRIPTION, + response = String.class), + @ResponseHeader(name = VERSION_PATCH_NAME, description = VERSION_PATCH_DESCRIPTION, + response = String.class), + @ResponseHeader(name = VERSION_LATEST_NAME, description = VERSION_LATEST_DESCRIPTION, + response = String.class), + @ResponseHeader(name = REQUEST_ID_NAME, description = REQUEST_ID_HDR_DESCRIPTION, + response = UUID.class)}, + extensions = {@Extension(name = EXTENSION_NAME, + properties = {@ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION), + @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)})}) + @ApiResponses(value = {@ApiResponse(code = AUTHENTICATION_ERROR_CODE, message = AUTHENTICATION_ERROR_MESSAGE), + @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE), + @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE)}) + // @formatter:on + + public Response deleteGroup(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + @ApiParam(value = "PDP Group Name", required = true) @PathParam("name") String groupName) { + + Pair pair = provider.delete(groupName, null); + + return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) + .entity(pair.getRight()).build(); + } + + /** + * Deletes a PDP group. + * + * @param requestId request ID used in ONAP logging + * @param groupName name of the PDP group to be deleted + * @param version version to be deleted + * @return a response + */ + // @formatter:off + @DELETE + @Path("pdps/groups/{name}/versions/{version}") + @ApiOperation(value = "Delete version of a PDP Group", + notes = "Deletes a version of PDP Group, returning optional error details", + response = PdpGroupDeleteResponse.class, + tags = {"Policy Administration (PAP) API"}, + authorizations = @Authorization(value = AUTHORIZATION_TYPE), + responseHeaders = { + @ResponseHeader(name = VERSION_MINOR_NAME, description = VERSION_MINOR_DESCRIPTION, + response = String.class), + @ResponseHeader(name = VERSION_PATCH_NAME, description = VERSION_PATCH_DESCRIPTION, + response = String.class), + @ResponseHeader(name = VERSION_LATEST_NAME, description = VERSION_LATEST_DESCRIPTION, + response = String.class), + @ResponseHeader(name = REQUEST_ID_NAME, description = REQUEST_ID_HDR_DESCRIPTION, + response = UUID.class)}, + extensions = {@Extension(name = EXTENSION_NAME, + properties = {@ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION), + @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)})}) + @ApiResponses(value = {@ApiResponse(code = AUTHENTICATION_ERROR_CODE, message = AUTHENTICATION_ERROR_MESSAGE), + @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE), + @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE)}) + // @formatter:on + + public Response deleteGroupVersion( + @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + @ApiParam(value = "PDP Group Name", required = true) @PathParam("name") String groupName, + @ApiParam(value = "PDP Group Version", required = true) @PathParam("version") String version) { + + Pair pair = provider.delete(groupName, version); + + return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) + .entity(pair.getRight()).build(); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java new file mode 100644 index 00000000..e40b053c --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java @@ -0,0 +1,58 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.rest; + +import javax.ws.rs.core.Response; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.policy.models.pap.concepts.PdpGroupDeleteResponse; + +/** + * Provider for PAP component to delete PDP groups. + */ +public class PdpGroupDeleteProvider { + + /** + * Deletes a PDP group. + * + * @param groupName name of the PDP group to be deleted + * @param version group version to delete; may be {@code null} if the group has only + * one version + * @return a pair containing the status and the response + */ + public Pair delete(String groupName, String version) { + + /* + * TODO Lock for updates - return error if already locked. + */ + + /* + * TODO Make updates - sending initial messages to PDPs and arranging for + * listeners to complete the deletion actions (in the background). The final step + * for the listener is to unlock. + */ + + /* + * TODO Return error if unable to send updates to all PDPs. + */ + + return Pair.of(Response.Status.OK, new PdpGroupDeleteResponse()); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java new file mode 100644 index 00000000..228d97c9 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java @@ -0,0 +1,88 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.rest; + +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.Extension; +import io.swagger.annotations.ExtensionProperty; +import io.swagger.annotations.ResponseHeader; +import java.util.UUID; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.policy.models.pap.concepts.PdpGroup; +import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; + +/** + * Class to provide REST end points for PAP component to deploy a PDP group. + */ +public class PdpGroupDeployControllerV1 extends PapRestControllerV1 { + + private final PdpGroupDeployProvider provider = new PdpGroupDeployProvider(); + + /** + * Deploys or updates a PDP group. + * + * @param requestId request ID used in ONAP logging + * @param group PDP group configuration + * @return a response + */ + // @formatter:off + @POST + @Path("pdps") + @ApiOperation(value = "Deploy or update PDP Group", + notes = "Deploys or updates a PDP Group, returning optional error details", + response = PdpGroupDeployResponse.class, + tags = {"Policy Administration (PAP) API"}, + authorizations = @Authorization(value = AUTHORIZATION_TYPE), + responseHeaders = { + @ResponseHeader(name = VERSION_MINOR_NAME, description = VERSION_MINOR_DESCRIPTION, + response = String.class), + @ResponseHeader(name = VERSION_PATCH_NAME, description = VERSION_PATCH_DESCRIPTION, + response = String.class), + @ResponseHeader(name = VERSION_LATEST_NAME, description = VERSION_LATEST_DESCRIPTION, + response = String.class), + @ResponseHeader(name = REQUEST_ID_NAME, description = REQUEST_ID_HDR_DESCRIPTION, + response = UUID.class)}, + extensions = {@Extension(name = EXTENSION_NAME, + properties = {@ExtensionProperty(name = API_VERSION_NAME, value = API_VERSION), + @ExtensionProperty(name = LAST_MOD_NAME, value = LAST_MOD_RELEASE)})}) + @ApiResponses(value = {@ApiResponse(code = AUTHENTICATION_ERROR_CODE, message = AUTHENTICATION_ERROR_MESSAGE), + @ApiResponse(code = AUTHORIZATION_ERROR_CODE, message = AUTHORIZATION_ERROR_MESSAGE), + @ApiResponse(code = SERVER_ERROR_CODE, message = SERVER_ERROR_MESSAGE)}) + // @formatter:on + + public Response deploy(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + @ApiParam(value = "PDP Group Configuration", required = true) PdpGroup group) { + + Pair pair = provider.deploy(group); + + return addLoggingHeaders(addVersionControlHeaders(Response.status(pair.getLeft())), requestId) + .entity(pair.getRight()).build(); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java new file mode 100644 index 00000000..da3b2ded --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java @@ -0,0 +1,57 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.rest; + +import javax.ws.rs.core.Response; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.policy.models.pap.concepts.PdpGroup; +import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; + +/** + * Provider for PAP component to deploy PDP groups. + */ +public class PdpGroupDeployProvider { + + /** + * Deploys or updates a PDP group. + * + * @param group PDP group configuration + * @return a pair containing the status and the response + */ + public Pair deploy(PdpGroup group) { + + /* + * TODO Lock for updates - return error if already locked. + */ + + /* + * TODO Make updates - sending initial messages to PDPs and arranging for + * listeners to complete the deployment actions (in the background). The final + * step for the listener is to unlock. + */ + + /* + * TODO Return error if unable to send updates to all PDPs. + */ + + return Pair.of(Response.Status.OK, new PdpGroupDeployResponse()); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/Main.java b/main/src/main/java/org/onap/policy/pap/main/startstop/Main.java index cbe4dcc9..223e322e 100644 --- a/main/src/main/java/org/onap/policy/pap/main/startstop/Main.java +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/Main.java @@ -21,8 +21,9 @@ package org.onap.policy.pap.main.startstop; +import java.io.FileInputStream; import java.util.Arrays; - +import java.util.Properties; import org.onap.policy.pap.main.PolicyPapException; import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.parameters.PapParameterHandler; @@ -74,9 +75,20 @@ public class Main { return; } + // Read the properties + Properties props = new Properties(); + try { + String propFile = arguments.getFullPropertyFilePath(); + try (FileInputStream stream = new FileInputStream(propFile)) { + props.load(stream); + } + } catch (final Exception e) { + LOGGER.error("start of policy pap service failed", e); + return; + } + // Now, create the activator for the policy pap service - activator = new PapActivator(parameterGroup); - PapActivator.setCurrent(activator); + activator = new PapActivator(parameterGroup, props); // Start the activator try { diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java b/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java index 687c5fb0..3334d81a 100644 --- a/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java @@ -21,9 +21,13 @@ package org.onap.policy.pap.main.startstop; +import java.util.Properties; import lombok.Getter; import lombok.Setter; +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.common.utils.services.ServiceManager; +import org.onap.policy.common.utils.services.ServiceManagerException; import org.onap.policy.pap.main.PolicyPapException; import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.rest.PapRestServer; @@ -31,8 +35,8 @@ 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 - * forwarding handlers. + * This class wraps a distributor so that it can be activated as a complete service + * together with all its pap and forwarding handlers. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ @@ -43,12 +47,15 @@ public class PapActivator { private final PapParameterGroup papParameterGroup; /** - * The current activator. This is initialized to a dummy instance used until the real - * one has been configured. + * The current activator. */ @Getter - @Setter - private static volatile PapActivator current = new PapActivator(null); + private static volatile PapActivator current = null; + + /** + * Used to stop the services. + */ + private final ServiceManager manager; @Getter @Setter(lombok.AccessLevel.PRIVATE) @@ -60,9 +67,31 @@ public class PapActivator { * Instantiate the activator for policy pap as a complete service. * * @param papParameterGroup the parameters for the pap service + * @param topicProperties properties used to configure the topics */ - public PapActivator(final PapParameterGroup papParameterGroup) { + public PapActivator(final PapParameterGroup papParameterGroup, Properties topicProperties) { + TopicEndpoint.manager.addTopicSinks(topicProperties); + TopicEndpoint.manager.addTopicSources(topicProperties); + this.papParameterGroup = papParameterGroup; + + // @formatter:off + this.manager = new ServiceManager() + .addAction("topics", + () -> TopicEndpoint.manager.start(), + () -> TopicEndpoint.manager.shutdown()) + .addAction("register parameters", + () -> registerToParameterService(papParameterGroup), + () -> deregisterToParameterService(papParameterGroup)) + .addAction("REST server", + () -> startPapRestServer(), + () -> restServer.stop()) + .addAction("set alive", + () -> setAlive(true), + () -> setAlive(false)); + // @formatter:on + + current = this; } /** @@ -77,12 +106,10 @@ public class PapActivator { try { LOGGER.debug("Policy pap starting as a service . . ."); - startPapRestServer(); - registerToParameterService(papParameterGroup); - setAlive(true); + manager.start(); LOGGER.debug("Policy pap started as a service"); - } catch (final Exception exp) { - LOGGER.error("Policy pap service startup failed", exp); + } catch (final ServiceManagerException exp) { + LOGGER.error("Policy pap service startup failed"); throw new PolicyPapException(exp.getMessage(), exp); } } @@ -98,13 +125,9 @@ public class PapActivator { } try { - deregisterToParameterService(papParameterGroup); - setAlive(false); - - // Stop the pap rest server - restServer.stop(); - } catch (final Exception exp) { - LOGGER.error("Policy pap service termination failed", exp); + manager.stop(); + } catch (final ServiceManagerException exp) { + LOGGER.error("Policy pap service termination failed"); throw new PolicyPapException(exp.getMessage(), exp); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java b/main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java index 4b8bc348..b0bbfd8a 100644 --- a/main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,6 +49,7 @@ public class PapCommandLineArguments { private final Options options; private String configurationFilePath = null; + private String propertyFilePath = null; /** * Construct the options for the CLI editor. @@ -76,6 +78,15 @@ public class PapCommandLineArguments { .required(false) .type(String.class) .build()); + options.addOption(Option.builder("p") + .longOpt("property-file") + .desc("the full path to the topic property file to use, " + + "the property file contains the policy pap topic properties") + .hasArg() + .argName("PROP_FILE") + .required(false) + .type(String.class) + .build()); //@formatter:on } @@ -106,6 +117,7 @@ public class PapCommandLineArguments { public String parse(final String[] args) throws PolicyPapException { // Clear all our arguments setConfigurationFilePath(null); + setPropertyFilePath(null); CommandLine commandLine = null; try { @@ -137,6 +149,10 @@ public class PapCommandLineArguments { setConfigurationFilePath(commandLine.getOptionValue('c')); } + if (commandLine.hasOption('p')) { + setPropertyFilePath(commandLine.getOptionValue('p')); + } + return null; } @@ -147,6 +163,7 @@ public class PapCommandLineArguments { */ public void validate() throws PolicyPapException { validateReadableFile("policy pap configuration", configurationFilePath); + validateReadableFile("policy pap properties", propertyFilePath); } /** @@ -212,6 +229,43 @@ public class PapCommandLineArguments { return configurationFilePath != null && configurationFilePath.length() > 0; } + /** + * Gets the property file path. + * + * @return the property file path + */ + public String getPropertyFilePath() { + return propertyFilePath; + } + + /** + * Gets the full expanded property file path. + * + * @return the property file path + */ + public String getFullPropertyFilePath() { + return ResourceUtils.getFilePath4Resource(getPropertyFilePath()); + } + + /** + * Sets the property file path. + * + * @param propertyFilePath the property file path + */ + public void setPropertyFilePath(final String propertyFilePath) { + this.propertyFilePath = propertyFilePath; + + } + + /** + * Check set property file path. + * + * @return true, if check set property file path + */ + public boolean checkSetPropertyFilePath() { + return propertyFilePath != null && propertyFilePath.length() > 0; + } + /** * Validate readable file. * diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpClientExceptionTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpClientExceptionTest.java deleted file mode 100644 index aa927665..00000000 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpClientExceptionTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP PAP - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.comm; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.onap.policy.common.utils.test.ExceptionsTester; -import org.onap.policy.pap.main.comm.PdpClientException; - -public class PdpClientExceptionTest { - - @Test - public void test() { - assertEquals(5, new ExceptionsTester().test(PdpClientException.class)); - } -} diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpClientTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpClientTest.java deleted file mode 100644 index 22823bfb..00000000 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpClientTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP PAP - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.comm; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.Before; -import org.junit.Test; -import org.mockito.internal.util.reflection.Whitebox; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; -import org.onap.policy.common.endpoints.event.comm.TopicListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; - -public class PdpClientTest { - private static final String SINK_FIELD_NAME = "sink"; - private static final String TOPIC = "my-topic"; - - private PdpClient client; - private TopicSink sink; - private List sinks; - - /** - * Creates mocks and an initial client object. - * - * @throws Exception if an error occurs - */ - @Before - public void setUp() throws Exception { - sink = mock(TopicSink.class); - when(sink.send(anyString())).thenReturn(true); - - sinks = Arrays.asList(sink, null); - - client = new PdpClient2(TOPIC); - } - - /** - * Uses a real NO-OP topic sink. - */ - @Test - public void testGetTopicSinks() throws Exception { - // clear all topics and then configure one topic - TopicEndpoint.manager.shutdown(); - - Properties props = new Properties(); - props.setProperty("noop.sink.topics", TOPIC); - TopicEndpoint.manager.addTopicSinks(props); - - sink = TopicEndpoint.manager.getNoopTopicSink(TOPIC); - assertNotNull(sink); - - AtomicReference evref = new AtomicReference<>(null); - - sink.register(new TopicListener() { - @Override - public void onTopicEvent(CommInfrastructure infra, String topic, String event) { - evref.set(event); - } - }); - - sink.start(); - - client = new PdpClient(TOPIC); - client.send(100); - - assertEquals("100", evref.get()); - } - - @Test - public void testPdpClient_testGetTopic() { - assertEquals(TOPIC, client.getTopic()); - assertSame(sink, Whitebox.getInternalState(client, SINK_FIELD_NAME)); - - // unknown topic -> should throw exception - sinks = new LinkedList<>(); - assertThatThrownBy(() -> new PdpClient2(TOPIC)).isInstanceOf(PdpClientException.class) - .hasMessage("no sinks for topic: my-topic"); - } - - @Test - public void testSend() throws Exception { - client.send(Arrays.asList("abc", "def")); - verify(sink).send("['abc','def']".replace('\'', '"')); - - // sink send fails - when(sink.send(anyString())).thenReturn(false); - assertFalse(client.send("ghi")); - - // sink send throws an exception - RuntimeException ex = new RuntimeException("expected exception"); - when(sink.send(anyString())).thenThrow(ex); - assertFalse(client.send("jkl")); - } - - /** - * PdpClient with some overrides. - */ - private class PdpClient2 extends PdpClient { - - public PdpClient2(String topic) throws PdpClientException { - super(topic); - } - - @Override - protected List getTopicSinks(String topic) { - return sinks; - } - } -} diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java b/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java index 27d8ac2a..8054194b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java @@ -21,6 +21,13 @@ package org.onap.policy.pap.main.parameters; +import java.util.Map; +import java.util.TreeMap; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; + /** * Class to hold/create all parameters for test cases. * @@ -36,21 +43,70 @@ public class CommonTestData { private static final boolean REST_SERVER_AAF = false; public static final String PAP_GROUP_NAME = "PapGroup"; + private static final Coder coder = new StandardCoder(); + + /** + * Converts the contents of a map to a parameter class. + * + * @param source property map + * @param clazz class of object to be created from the map + * @return a new object represented by the map + */ + public T toObject(Map source, Class clazz) { + try { + return coder.decode(coder.encode(source), clazz); + + } catch (CoderException e) { + throw new RuntimeException("cannot create " + clazz.getName() + " from map", e); + } + } + /** - * Returns an instance of RestServerParameters for test cases. + * Returns a property map for a PapParameterGroup map for test cases. + * @param name name of the parameters + * + * @return a property map suitable for constructing an object + */ + public Map getPapParameterGroupMap(String name) { + Map map = new TreeMap<>(); + + map.put("name", name); + map.put("restServerParameters", getRestServerParametersMap(false)); + map.put("pdpGroupDeploymentParameters", getPdpGroupDeploymentParametersMap()); + + return map; + } + + /** + * Returns a property map for a RestServerParameters map for test cases. * * @param isEmpty boolean value to represent that object created should be empty or not - * @return the restServerParameters object + * @return a property map suitable for constructing an object */ - public RestServerParameters getRestServerParameters(final boolean isEmpty) { - final RestServerParameters restServerParameters; + public Map getRestServerParametersMap(final boolean isEmpty) { + Map map = new TreeMap<>(); + map.put("https", REST_SERVER_HTTPS); + map.put("aaf", REST_SERVER_AAF); + if (!isEmpty) { - restServerParameters = new RestServerParameters(REST_SERVER_HOST, REST_SERVER_PORT, REST_SERVER_USER, - REST_SERVER_PASSWORD, REST_SERVER_HTTPS, REST_SERVER_AAF); - } else { - restServerParameters = new RestServerParameters(null, 0, null, null, REST_SERVER_HTTPS, REST_SERVER_AAF); + map.put("host", REST_SERVER_HOST); + map.put("port", REST_SERVER_PORT); + map.put("userName", REST_SERVER_USER); + map.put("password", REST_SERVER_PASSWORD); } - return restServerParameters; + + return map; } + /** + * Returns a property map for a PdpGroupDeploymentParameters map for test cases. + * + * @return a property map suitable for constructing an object + */ + public Map getPdpGroupDeploymentParametersMap() { + Map map = new TreeMap<>(); + map.put("waitResponseMs", "1"); + + return map; + } } diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java index 4759f646..2450a750 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java @@ -25,6 +25,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import java.util.Map; import org.junit.Test; import org.onap.policy.common.parameters.GroupValidationResult; @@ -36,11 +37,17 @@ import org.onap.policy.common.parameters.GroupValidationResult; public class TestPapParameterGroup { CommonTestData commonTestData = new CommonTestData(); + @Test + public void testPapParameterGroup_Named() { + final PapParameterGroup papParameters = new PapParameterGroup("my-name"); + assertEquals("my-name", papParameters.getName()); + } + @Test public void testPapParameterGroup() { - final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false); - final PapParameterGroup papParameters = - new PapParameterGroup(CommonTestData.PAP_GROUP_NAME, restServerParameters); + final PapParameterGroup papParameters = commonTestData.toObject( + commonTestData.getPapParameterGroupMap(CommonTestData.PAP_GROUP_NAME), PapParameterGroup.class); + final RestServerParameters restServerParameters = papParameters.getRestServerParameters(); final GroupValidationResult validationResult = papParameters.validate(); assertTrue(validationResult.isValid()); assertEquals(CommonTestData.PAP_GROUP_NAME, papParameters.getName()); @@ -54,19 +61,18 @@ public class TestPapParameterGroup { @Test public void testPapParameterGroup_NullName() { - final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false); - final PapParameterGroup papParameters = new PapParameterGroup(null, restServerParameters); + final PapParameterGroup papParameters = commonTestData.toObject( + commonTestData.getPapParameterGroupMap(null), PapParameterGroup.class); final GroupValidationResult validationResult = papParameters.validate(); assertFalse(validationResult.isValid()); assertEquals(null, papParameters.getName()); - assertTrue(validationResult.getResult().contains( - "field \"name\" type \"java.lang.String\" value \"null\" INVALID, " + "must be a non-blank string")); + assertTrue(validationResult.getResult().contains("is null")); } @Test public void testPapParameterGroup_EmptyName() { - final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false); - final PapParameterGroup papParameters = new PapParameterGroup("", restServerParameters); + final PapParameterGroup papParameters = commonTestData.toObject( + commonTestData.getPapParameterGroupMap(""), PapParameterGroup.class); final GroupValidationResult validationResult = papParameters.validate(); assertFalse(validationResult.isValid()); assertEquals("", papParameters.getName()); @@ -76,9 +82,8 @@ public class TestPapParameterGroup { @Test public void testPapParameterGroup_SetName() { - final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false); - final PapParameterGroup papParameters = - new PapParameterGroup(CommonTestData.PAP_GROUP_NAME, restServerParameters); + final PapParameterGroup papParameters = commonTestData.toObject( + commonTestData.getPapParameterGroupMap(CommonTestData.PAP_GROUP_NAME), PapParameterGroup.class); papParameters.setName("PapNewGroup"); final GroupValidationResult validationResult = papParameters.validate(); assertTrue(validationResult.isValid()); @@ -87,10 +92,11 @@ public class TestPapParameterGroup { @Test public void testApiParameterGroup_EmptyRestServerParameters() { - final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(true); + Map map = commonTestData.getPapParameterGroupMap(CommonTestData.PAP_GROUP_NAME); + map.put("restServerParameters", commonTestData.getRestServerParametersMap(true)); - final PapParameterGroup papParameters = - new PapParameterGroup(CommonTestData.PAP_GROUP_NAME, restServerParameters); + final PapParameterGroup papParameters = commonTestData.toObject( + map, PapParameterGroup.class); final GroupValidationResult validationResult = papParameters.validate(); assertFalse(validationResult.isValid()); assertTrue(validationResult.getResult() diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java index b0f9521d..363a130a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.main.parameters; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -93,13 +94,7 @@ public class TestPapParameterHandler { final PapCommandLineArguments noArguments = new PapCommandLineArguments(); noArguments.parse(noArgumentString); - try { - new PapParameterHandler().getParameters(noArguments); - fail("test should throw an exception here"); - } catch (final Exception e) { - assertTrue(e.getMessage().contains( - "field \"name\" type \"java.lang.String\" value \"null\" INVALID, must be a non-blank string")); - } + assertThatThrownBy(() -> new PapParameterHandler().getParameters(noArguments)).hasMessageContaining("is null"); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java index 8f522740..25ab1c37 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java @@ -21,25 +21,22 @@ package org.onap.policy.pap.main.rest; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.ServerSocket; import java.security.SecureRandom; -import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map; import java.util.Properties; +import java.util.function.Function; 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 javax.ws.rs.core.Response; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; import org.junit.After; import org.junit.AfterClass; @@ -88,7 +85,7 @@ public class CommonPapRestServer { */ @BeforeClass public static void setUpBeforeClass() throws Exception { - allocPort(); + port = NetworkUtil.allocPort(); httpsPrefix = "https://localhost:" + port + "/"; @@ -140,41 +137,32 @@ public class CommonPapRestServer { * @throws Exception if an error occurs */ protected void testSwagger(final String endpoint) throws Exception { - final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "swagger.yaml"); + final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "swagger.yaml", true); final String resp = invocationBuilder.get(String.class); assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint + ":")); } - /** - * Allocates a port for the server. - * - * @throws IOException if an error occurs - */ - private static void allocPort() throws IOException { - ServerSocket socket = new ServerSocket(); - socket.bind(new InetSocketAddress("localhost", 0)); - - port = socket.getLocalPort(); - socket.close(); - } - /** * Makes a parameter configuration file. * * @throws Exception if an error occurs */ private static void makeConfigFile() throws Exception { - Map params = new HashMap<>(); - params.put("host", "0.0.0.0"); - params.put("port", port); - params.put("userName", "healthcheck"); - params.put("password", "zb!XztG34"); - params.put("https", true); + Map restParams = new HashMap<>(); + restParams.put("host", "0.0.0.0"); + restParams.put("port", port); + restParams.put("userName", "healthcheck"); + restParams.put("password", "zb!XztG34"); + restParams.put("https", true); + + Map pdpGroupDeploy = new HashMap<>(); + pdpGroupDeploy.put("waitResponseMs", "0"); Map config = new HashMap<>(); config.put("name", "PapGroup"); - config.put("restServerParameters", params); + config.put("restServerParameters", restParams); + config.put("pdpGroupDeploymentParameters", pdpGroupDeploy); File file = new File("src/test/resources/parameters/TestConfigParams.json"); file.deleteOnExit(); @@ -198,9 +186,12 @@ public class CommonPapRestServer { systemProps.put("javax.net.ssl.keyStorePassword", "Pol1cy_0nap"); System.setProperties(systemProps); - final String[] papConfigParameters = new String[2]; - papConfigParameters[0] = "-c"; - papConfigParameters[1] = "src/test/resources/parameters/TestConfigParams.json"; + // @formatter:off + final String[] papConfigParameters = { + "-c", "src/test/resources/parameters/TestConfigParams.json", + "-p", "src/test/resources/parameters/topic.properties" + }; + // @formatter:on main = new Main(papConfigParameters); @@ -230,6 +221,19 @@ public class CommonPapRestServer { Whitebox.setInternalState(PapActivator.getCurrent(), "alive", false); } + /** + * Verifies that unauthorized requests fail. + * + * @param endpoint the target end point + * @param sender function that sends the requests to the target + * @throws Exception if an error occurs + */ + protected void checkUnauthRequest(final String endpoint, Function sender) + throws Exception { + assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), + sender.apply(sendNoAuthRequest(endpoint)).getStatus()); + } + /** * Sends a request to an endpoint. * @@ -238,45 +242,40 @@ public class CommonPapRestServer { * @throws Exception if an error occurs */ protected Invocation.Builder sendRequest(final String endpoint) throws Exception { - return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint); + return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, true); } /** - * Sends a request to a fully qualified endpoint. + * Sends a request to an endpoint, without any authorization header. * - * @param endpoint the fully qualified target endpoint + * @param endpoint the target endpoint * @return a request builder * @throws Exception if an error occurs */ - protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint) throws Exception { - - // @formatter:off - 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) {} - } - }; - // @formatter:on + protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception { + return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, false); + } + /** + * Sends a request to a fully qualified endpoint. + * + * @param fullyQualifiedEndpoint the fully qualified target endpoint + * @param includeAuth if authorization header should be included + * @return a request builder + * @throws Exception if an error occurs + */ + protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth) + throws Exception { final SSLContext sc = SSLContext.getInstance("TLSv1.2"); - sc.init(null, noopTrustManager, new SecureRandom()); + sc.init(null, NetworkUtil.getAlwaysTrustingManager(), 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); + + if (includeAuth) { + final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"); + client.register(feature); + } final WebTarget webTarget = client.target(fullyQualifiedEndpoint); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java b/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java new file mode 100644 index 00000000..317ab1c1 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java @@ -0,0 +1,63 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.UUID; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import org.junit.Before; +import org.junit.Test; + +public class PapRestControllerV1Test { + + private PapRestControllerV1 ctlr; + private ResponseBuilder bldr; + + @Before + public void setUp() { + ctlr = new PapRestControllerV1(); + bldr = Response.status(Response.Status.OK); + } + + @Test + public void testAddVersionControlHeaders() { + Response resp = ctlr.addVersionControlHeaders(bldr).build(); + assertEquals("0", resp.getHeaderString(PapRestControllerV1.VERSION_MINOR_NAME)); + assertEquals("0", resp.getHeaderString(PapRestControllerV1.VERSION_PATCH_NAME)); + assertEquals("1.0.0", resp.getHeaderString(PapRestControllerV1.VERSION_LATEST_NAME)); + } + + @Test + public void testAddLoggingHeaders_Null() { + Response resp = ctlr.addLoggingHeaders(bldr, null).build(); + assertNotNull(resp.getHeaderString(PapRestControllerV1.REQUEST_ID_NAME)); + } + + @Test + public void testAddLoggingHeaders_NonNull() { + UUID uuid = UUID.randomUUID(); + Response resp = ctlr.addLoggingHeaders(bldr, uuid).build(); + assertEquals(uuid.toString(), resp.getHeaderString(PapRestControllerV1.REQUEST_ID_NAME)); + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java index 0ddfb3b5..6dd7103b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestHealthCheckRestControllerV1.java @@ -46,6 +46,9 @@ public class TestHealthCheckRestControllerV1 extends CommonPapRestServer { final Invocation.Builder invocationBuilder = sendRequest(HEALTHCHECK_ENDPOINT); final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); validateHealthCheckReport(NAME, SELF, true, 200, ALIVE, report); + + // verify it fails when no authorization info is included + checkUnauthRequest(HEALTHCHECK_ENDPOINT, req -> req.get()); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteControllerV1.java new file mode 100644 index 00000000..107c46ad --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteControllerV1.java @@ -0,0 +1,79 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * ================================================================================ + * 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.assertNull; + +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.Response; +import org.junit.Test; +import org.onap.policy.models.pap.concepts.PdpGroupDeleteResponse; + +public class TestPdpGroupDeleteControllerV1 extends CommonPapRestServer { + + private static final String DELETE_ENDPOINT = "pdps/groups"; + + @Test + public void testSwagger() throws Exception { + super.testSwagger(DELETE_ENDPOINT + "/{name}"); + super.testSwagger(DELETE_ENDPOINT + "/{name}/versions/{version}"); + } + + @Test + public void testDeleteGroup() throws Exception { + String uri = DELETE_ENDPOINT + "/my-name"; + + Invocation.Builder invocationBuilder = sendRequest(uri); + Response rawresp = invocationBuilder.delete(); + PdpGroupDeleteResponse resp = rawresp.readEntity(PdpGroupDeleteResponse.class); + assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); + assertNull(resp.getErrorDetails()); + + rawresp = invocationBuilder.delete(); + resp = rawresp.readEntity(PdpGroupDeleteResponse.class); + assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); + assertNull(resp.getErrorDetails()); + + // verify it fails when no authorization info is included + checkUnauthRequest(uri, req -> req.delete()); + } + + @Test + public void testDeleteGroupVersion() throws Exception { + String uri = DELETE_ENDPOINT + "/my-name/versions/1.2.3"; + + Invocation.Builder invocationBuilder = sendRequest(uri); + Response rawresp = invocationBuilder.delete(); + PdpGroupDeleteResponse resp = rawresp.readEntity(PdpGroupDeleteResponse.class); + assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); + assertNull(resp.getErrorDetails()); + + rawresp = invocationBuilder.delete(); + resp = rawresp.readEntity(PdpGroupDeleteResponse.class); + assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); + assertNull(resp.getErrorDetails()); + + // verify it fails when no authorization info is included + checkUnauthRequest(uri, req -> req.delete()); + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java new file mode 100644 index 00000000..d49f00cc --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployControllerV1.java @@ -0,0 +1,78 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. + * ================================================================================ + * 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.assertNull; + +import java.util.Arrays; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.junit.Test; +import org.onap.policy.models.pap.concepts.PdpGroup; +import org.onap.policy.models.pap.concepts.PdpGroupDeployResponse; +import org.onap.policy.models.pap.concepts.PdpSubGroup; + +public class TestPdpGroupDeployControllerV1 extends CommonPapRestServer { + + private static final String DEPLOY_ENDPOINT = "pdps"; + + @Test + public void testSwagger() throws Exception { + super.testSwagger(DEPLOY_ENDPOINT); + } + + @Test + public void testDeploy() throws Exception { + Entity entgrp = makePdpGroupEntity(); + + Invocation.Builder invocationBuilder = sendRequest(DEPLOY_ENDPOINT); + Response rawresp = invocationBuilder.post(entgrp); + PdpGroupDeployResponse resp = rawresp.readEntity(PdpGroupDeployResponse.class); + assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); + assertNull(resp.getErrorDetails()); + + rawresp = invocationBuilder.post(entgrp); + resp = rawresp.readEntity(PdpGroupDeployResponse.class); + assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); + assertNull(resp.getErrorDetails()); + + // verify it fails when no authorization info is included + checkUnauthRequest(DEPLOY_ENDPOINT, req -> req.post(entgrp)); + } + + private Entity makePdpGroupEntity() { + PdpSubGroup subgrp = new PdpSubGroup(); + subgrp.setPdpType("drools"); + + PdpGroup group = new PdpGroup(); + group.setName("drools-group"); + group.setDescription("my description"); + group.setVersion("my-version"); + group.setPdpSubgroups(Arrays.asList(subgrp)); + + Entity entgrp = Entity.entity(group, MediaType.APPLICATION_JSON); + return entgrp; + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestStatisticsRestControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestStatisticsRestControllerV1.java index de142b51..9874389e 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestStatisticsRestControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestStatisticsRestControllerV1.java @@ -66,6 +66,9 @@ public class TestStatisticsRestControllerV1 extends CommonPapRestServer { invocationBuilder = sendRequest(STATISTICS_ENDPOINT); report = invocationBuilder.get(StatisticsReport.class); validateStatisticsReport(report, 1, 200); + + // verify it fails when no authorization info is included + checkUnauthRequest(STATISTICS_ENDPOINT, req -> req.get()); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java index 1f6b2baf..37da7e9b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java @@ -52,7 +52,8 @@ public class TestMain { @Test public void testMain() throws PolicyPapException { - final String[] papConfigParameters = {"-c", "parameters/PapConfigParameters.json"}; + final String[] papConfigParameters = + {"-c", "parameters/PapConfigParameters.json", "-p", "parameters/topic.properties"}; main = new Main(papConfigParameters); assertTrue(main.getParameters().isValid()); assertEquals(CommonTestData.PAP_GROUP_NAME, main.getParameters().getName()); diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java index 5e611673..059ea0b4 100644 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java @@ -27,6 +27,8 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; +import java.io.FileInputStream; +import java.util.Properties; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -47,14 +49,23 @@ public class TestPapActivator { /** * Initializes an activator. + * * @throws Exception if an error occurs */ @Before public void setUp() throws Exception { - final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters.json" }; + final String[] papConfigParameters = + {"-c", "parameters/PapConfigParameters.json", "-p", "parameters/topic.properties"}; final PapCommandLineArguments arguments = new PapCommandLineArguments(papConfigParameters); final PapParameterGroup parGroup = new PapParameterHandler().getParameters(arguments); - activator = new PapActivator(parGroup); + + Properties props = new Properties(); + String propFile = arguments.getFullConfigurationFilePath(); + try (FileInputStream stream = new FileInputStream(propFile)) { + props.load(stream); + } + + activator = new PapActivator(parGroup, props); } /** @@ -84,7 +95,6 @@ public class TestPapActivator { @Test public void testGetCurrent_testSetCurrent() { - PapActivator.setCurrent(activator); assertSame(activator, PapActivator.getCurrent()); } diff --git a/main/src/test/resources/parameters/topic.properties b/main/src/test/resources/parameters/topic.properties new file mode 100644 index 00000000..11c17dac --- /dev/null +++ b/main/src/test/resources/parameters/topic.properties @@ -0,0 +1,22 @@ +# ============LICENSE_START======================================================= +# ONAP PAP +# ================================================================================ +# Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= + +noop.sink.topics=POLICY-PDP-PAP +noop.sink.topics.POLICY-PDP-PAP.servers=anyserver +noop.source.topics=POLICY-PDP-PAP +noop.source.topics.POLICY-PDP-PAP.servers=anyserver diff --git a/packages/policy-pap-docker/src/main/docker/policy-pap.sh b/packages/policy-pap-docker/src/main/docker/policy-pap.sh index 6bd53780..f72a5b50 100644 --- a/packages/policy-pap-docker/src/main/docker/policy-pap.sh +++ b/packages/policy-pap-docker/src/main/docker/policy-pap.sh @@ -2,6 +2,7 @@ # # ============LICENSE_START======================================================= # Copyright (C) 2019 Nordix Foundation. +# Modifications Copyright (C) 2019 AT&T Intellectual Property. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -27,17 +28,29 @@ TRUSTSTORE="${POLICY_HOME}/etc/ssl/policy-truststore" TRUSTSTORE_PASSWD="Pol1cy_0nap" -if [ "$#" -eq 1 ]; then +if [ "$#" -ge 1 ]; then CONFIG_FILE=$1 else CONFIG_FILE=${CONFIG_FILE} fi +if [ "$#" -ge 2 ]; then + PROP_FILE=$2 +else + PROP_FILE=${PROP_FILE} +fi + if [ -z "$CONFIG_FILE" ] then CONFIG_FILE="$POLICY_PAP_HOME/etc/defaultConfig.json" fi +if [ -z "$PROP_FILE" ] + then + PROP_FILE="$POLICY_PAP_HOME/etc/topic.properties" +fi + echo "Policy pap config file: $CONFIG_FILE" +echo "Policy pap property file: $PROP_FILE" -$JAVA_HOME/bin/java -cp "$POLICY_PAP_HOME/etc:$POLICY_PAP_HOME/lib/*" -Djavax.net.ssl.keyStore="$KEYSTORE" -Djavax.net.ssl.keyStorePassword="$KEYSTORE_PASSWD" -Djavax.net.ssl.trustStore="$TRUSTSTORE" -Djavax.net.ssl.trustStorePassword="$TRUSTSTORE_PASSWD" org.onap.policy.pap.main.startstop.Main -c $CONFIG_FILE +$JAVA_HOME/bin/java -cp "$POLICY_PAP_HOME/etc:$POLICY_PAP_HOME/lib/*" -Djavax.net.ssl.keyStore="$KEYSTORE" -Djavax.net.ssl.keyStorePassword="$KEYSTORE_PASSWD" -Djavax.net.ssl.trustStore="$TRUSTSTORE" -Djavax.net.ssl.trustStorePassword="$TRUSTSTORE_PASSWD" org.onap.policy.pap.main.startstop.Main -c $CONFIG_FILE -p $PROP_FILE diff --git a/packages/policy-pap-tarball/src/main/package/tarball/assembly.xml b/packages/policy-pap-tarball/src/main/package/tarball/assembly.xml index c315a4ba..1bad6c90 100644 --- a/packages/policy-pap-tarball/src/main/package/tarball/assembly.xml +++ b/packages/policy-pap-tarball/src/main/package/tarball/assembly.xml @@ -1,6 +1,7 @@