diff options
Diffstat (limited to 'main')
33 files changed, 2451 insertions, 0 deletions
diff --git a/main/pom.xml b/main/pom.xml new file mode 100644 index 00000000..2a6677d2 --- /dev/null +++ b/main/pom.xml @@ -0,0 +1,81 @@ +<!-- + ============LICENSE_START======================================================= + ONAP Policy Engine - XACML PDP + ================================================================================ + Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + ================================================================================ + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + ============LICENSE_END========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.xacml-pdp</groupId> + <artifactId>policy-xacml-pdp</artifactId> + <version>2.0.0-SNAPSHOT</version> + </parent> + + <artifactId>main</artifactId> + + <name>${project.artifactId}</name> + <description>The main module of Policy PDP-X that handles startup, lifecycle management, and parameters.</description> + + <dependencies> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>capabilities</artifactId> + <version>${policy.common.version}</version> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>policy-endpoints</artifactId> + <version>${policy.common.version}</version> + </dependency> + <dependency> + <groupId>commons-cli</groupId> + <artifactId>commons-cli</artifactId> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>common-parameters</artifactId> + <version>${policy.common.version}</version> + </dependency> + </dependencies> + + <build> + <resources> + <!-- Output the version of the pdpx service --> + <resource> + <directory>src/main/resources</directory> + <filtering>true</filtering> + <includes> + <include>**/version.txt</include> + </includes> + </resource> + <resource> + <directory>src/main/resources</directory> + <filtering>false</filtering> + <excludes> + <exclude>**/version.txt</exclude> + </excludes> + </resource> + </resources> + </build> + +</project> diff --git a/main/src/main/java/org/onap/policy/pdpx/main/PolicyXacmlPdpException.java b/main/src/main/java/org/onap/policy/pdpx/main/PolicyXacmlPdpException.java new file mode 100644 index 00000000..f5699d6d --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/PolicyXacmlPdpException.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main; + +/** + * This exception will be called if an error occurs in policy xacml pdp external service. + */ +public class PolicyXacmlPdpException extends Exception { + + private static final long serialVersionUID = 276444549323645044L; + + /** + * Instantiates a new policy xacml pdp exception with a message. + * + * @param message the message + */ + public PolicyXacmlPdpException(final String message) { + super(message); + } + + /** + * Instantiates a new policy xacml pdp exception with a message and a caused by exception. + * + * @param message the message + * @param exp the exception that caused this exception to be thrown + */ + public PolicyXacmlPdpException(final String message, final Exception exp) { + super(message, exp); + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeException.java b/main/src/main/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeException.java new file mode 100644 index 00000000..7325ac4c --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/PolicyXacmlPdpRuntimeException.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main; + +/** + * This runtime exception will be called if a runtime error occurs when using policy xacml pdp. + */ +public class PolicyXacmlPdpRuntimeException extends RuntimeException { + + private static final long serialVersionUID = -1417471704362517416L; + + /** + * Instantiates a new policy xacml pdp runtime exception with a message. + * + * @param message the message + */ + public PolicyXacmlPdpRuntimeException(final String message) { + super(message); + } + + /** + * Instantiates a new policy xacml pdp runtime exception with a message and a caused by exception. + * + * @param message the message + * @param exp the exception that caused this exception to be thrown + */ + public PolicyXacmlPdpRuntimeException(final String message, final Exception exp) { + super(message, exp); + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/parameters/RestServerParameters.java b/main/src/main/java/org/onap/policy/pdpx/main/parameters/RestServerParameters.java new file mode 100644 index 00000000..e04a0f29 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/parameters/RestServerParameters.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.parameters; + +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ValidationStatus; +import org.onap.policy.common.utils.validation.ParameterValidationUtils; + +/** + * Class to hold all parameters needed for xacml pdp rest server. + * + */ +public class RestServerParameters implements ParameterGroup { + private String name; + private String host; + private int port; + private String userName; + private String password; + + /** + * Constructor for instantiating RestServerParameters. + * + * @param host the host name + * @param port the port + * @param userName the user name + * @param password the password + */ + public RestServerParameters(final String host, final int port, final String userName, final String password) { + super(); + this.host = host; + this.port = port; + this.userName = userName; + this.password = password; + } + + /** + * Return the name of this RestServerParameters instance. + * + * @return name the name of this RestServerParameters + */ + @Override + public String getName() { + return name; + } + + /** + * Return the host of this RestServerParameters instance. + * + * @return the host + */ + public String getHost() { + return host; + } + + /** + * Return the port of this RestServerParameters instance. + * + * @return the port + */ + public int getPort() { + return port; + } + + /** + * Return the user name of this RestServerParameters instance. + * + * @return the userName + */ + public String getUserName() { + return userName; + } + + /** + * Return the password of this RestServerParameters instance. + * + * @return the password + */ + public String getPassword() { + return password; + } + + /** + * Set the name of this RestServerParameters instance. + * + * @param name the name to set + */ + @Override + public void setName(final String name) { + this.name = name; + } + + /** + * Validate the rest server parameters. + * + * @return the result of the validation + */ + @Override + public GroupValidationResult validate() { + final GroupValidationResult validationResult = new GroupValidationResult(this); + if (!ParameterValidationUtils.validateStringParameter(host)) { + validationResult.setResult("host", ValidationStatus.INVALID, + "must be a non-blank string containing hostname/ipaddress of the xacml pdp rest server"); + } + if (!ParameterValidationUtils.validateStringParameter(userName)) { + validationResult.setResult("userName", ValidationStatus.INVALID, + "must be a non-blank string containing userName for xacml pdp rest server credentials"); + } + if (!ParameterValidationUtils.validateStringParameter(password)) { + validationResult.setResult("password", ValidationStatus.INVALID, + "must be a non-blank string containing password for xacml pdp rest server credentials"); + } + if (!ParameterValidationUtils.validateIntParameter(port)) { + validationResult.setResult("port", ValidationStatus.INVALID, + "must be a positive integer containing port of the xacml pdp rest server"); + } + return validationResult; + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/parameters/XacmlPdpParameterGroup.java b/main/src/main/java/org/onap/policy/pdpx/main/parameters/XacmlPdpParameterGroup.java new file mode 100644 index 00000000..2c972641 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/parameters/XacmlPdpParameterGroup.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.parameters; + +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ValidationStatus; +import org.onap.policy.common.utils.validation.ParameterValidationUtils; + +/** + * Class to hold all parameters needed for xacml pdp component. + * + */ +public class XacmlPdpParameterGroup implements ParameterGroup { + private String name; + private RestServerParameters restServerParameters; + + /** + * Create the xacml pdp parameter group. + * + * @param name the parameter group name + */ + public XacmlPdpParameterGroup(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(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 xacml pdp rest server"); + } else { + validationResult.setResult("restServerParameters", restServerParameters.validate()); + } + return validationResult; + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/parameters/XacmlPdpParameterHandler.java b/main/src/main/java/org/onap/policy/pdpx/main/parameters/XacmlPdpParameterHandler.java new file mode 100644 index 00000000..e8ddd1dc --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/parameters/XacmlPdpParameterHandler.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.parameters; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import java.io.FileReader; +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.pdpx.main.PolicyXacmlPdpException; +import org.onap.policy.pdpx.main.startstop.XacmlPdpCommandLineArguments; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + + +/** + * This class handles reading, parsing and validating of policy xacml pdp parameters from JSON + * files. + */ +public class XacmlPdpParameterHandler { + private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpParameterHandler.class); + private static final Gson gson = new GsonBuilder().create(); + + /** + * Read the parameters from the parameter file. + * + * @param arguments the arguments passed to policy xacml pdp + * @return the parameters read from the configuration file + * @throws PolicyXacmlPdpException on parameter exceptions + */ + public XacmlPdpParameterGroup getParameters(final XacmlPdpCommandLineArguments arguments) + throws PolicyXacmlPdpException { + XacmlPdpParameterGroup xacmlPdpParameterGroup = null; + + try { + // Read the parameters from JSON using Gson + xacmlPdpParameterGroup = gson.fromJson(new FileReader(arguments.getFullConfigurationFilePath()), + XacmlPdpParameterGroup.class); + } catch (final Exception e) { + final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath() + + "\"\n" + "(" + e.getClass().getSimpleName() + "):" + e.getMessage(); + LOGGER.error(errorMessage, e); + throw new PolicyXacmlPdpException(errorMessage, e); + } + + // The JSON processing returns null if there is an empty file + if (xacmlPdpParameterGroup == null) { + final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; + LOGGER.error(errorMessage); + throw new PolicyXacmlPdpException(errorMessage); + } + + // validate the parameters + final GroupValidationResult validationResult = xacmlPdpParameterGroup.validate(); + if (!validationResult.isValid()) { + String returnMessage = + "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; + returnMessage += validationResult.getResult(); + + LOGGER.error(returnMessage); + throw new PolicyXacmlPdpException(returnMessage); + } + + return xacmlPdpParameterGroup; + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/rest/HealthCheckProvider.java b/main/src/main/java/org/onap/policy/pdpx/main/rest/HealthCheckProvider.java new file mode 100644 index 00000000..e57ba180 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/rest/HealthCheckProvider.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.rest; + +import org.onap.policy.common.endpoints.report.HealthCheckReport; +import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator; + +/** + * Class to fetch health check of xacml pdp service. + * + */ +public class HealthCheckProvider { + + private static final String NOT_ALIVE = "not alive"; + private static final String ALIVE = "alive"; + private static final String URL = "self"; + private static final String NAME = "Policy Xacml PDP"; + + /** + * Performs the health check of xacml pdp service. + * + * @return Report containing health check status + */ + public HealthCheckReport performHealthCheck() { + final HealthCheckReport report = new HealthCheckReport(); + report.setName(NAME); + report.setUrl(URL); + report.setHealthy(XacmlPdpActivator.isAlive()); + report.setCode(XacmlPdpActivator.isAlive() ? 200 : 500); + report.setMessage(XacmlPdpActivator.isAlive() ? ALIVE : NOT_ALIVE); + return report; + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/rest/StatisticsProvider.java b/main/src/main/java/org/onap/policy/pdpx/main/rest/StatisticsProvider.java new file mode 100644 index 00000000..f3580531 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/rest/StatisticsProvider.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.rest; + +import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager; +import org.onap.policy.pdpx.main.startstop.XacmlPdpActivator; + +/** + * Class to fetch statistics of xacmlPdp service. + * + */ +public class StatisticsProvider { + + /** + * Returns the current statistics of xacmlPdp service. + * + * @return Report containing statistics of xacmlPdp service + */ + public StatisticsReport fetchCurrentStatistics() { + final StatisticsReport report = new StatisticsReport(); + report.setCode(XacmlPdpActivator.isAlive() ? 200 : 500); + report.setTotalPoliciesCount(XacmlPdpStatisticsManager.getTotalPoliciesCount()); + report.setPermitDecisionsCount(XacmlPdpStatisticsManager.getPermitDecisionsCount()); + report.setDenyDecisionsCount(XacmlPdpStatisticsManager.getDenyDecisionsCount()); + report.setIndeterminantDecisionsCount(XacmlPdpStatisticsManager.getIndeterminantDecisionsCount()); + report.setNotApplicableDecisionsCount(XacmlPdpStatisticsManager.getNotApplicableDecisionsCount()); + return report; + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/rest/StatisticsReport.java b/main/src/main/java/org/onap/policy/pdpx/main/rest/StatisticsReport.java new file mode 100644 index 00000000..f37b1d36 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/rest/StatisticsReport.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.rest; + +/** + * Class to represent statistics report of xacmlPdp service. + * + */ +public class StatisticsReport { + + private int code; + private long totalPoliciesCount; + private long permitDecisionsCount; + private long denyDecisionsCount; + private long indeterminantDecisionsCount; + private long notApplicableDecisionsCount; + + + /** + * 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 totalPoliciesCount of this {@link StatisticsReport} instance. + * + * @return the totalPoliciesCount + */ + public long getTotalPoliciesCount() { + return totalPoliciesCount; + } + + /** + * Set totalPoliciesCount in this {@link StatisticsReport} instance. + * + * @param totalPoliciesCount the totalPoliciesCount to set + */ + public void setTotalPoliciesCount(long totalPoliciesCount) { + this.totalPoliciesCount = totalPoliciesCount; + } + + /** + * Returns the permitDecisionsCount of this {@link StatisticsReport} instance. + * + * @return the permitDecisionsCount + */ + public long getPermitDecisionsCount() { + return permitDecisionsCount; + } + + /** + * Set permitDecisionsCount in this {@link StatisticsReport} instance. + * + * @param permitDecisionsCount the permitDecisionsCount to set + */ + public void setPermitDecisionsCount(long permitDecisionsCount) { + this.permitDecisionsCount = permitDecisionsCount; + } + + /** + * Returns the denyDecisionsCount of this {@link StatisticsReport} instance. + * + * @return the denyDecisionsCount + */ + public long getDenyDecisionsCount() { + return denyDecisionsCount; + } + + /** + * Set denyDecisionsCount in this {@link StatisticsReport} instance. + * + * @param denyDecisionsCount the denyDecisionsCount to set + */ + public void setDenyDecisionsCount(long denyDecisionsCount) { + this.denyDecisionsCount = denyDecisionsCount; + } + + /** + * Returns the indeterminantDecisionsCount of this {@link StatisticsReport} instance. + * + * @return the indeterminantDecisionsCount + */ + public long getIndeterminantDecisionsCount() { + return indeterminantDecisionsCount; + } + + /** + * Set indeterminantDecisionsCount in this {@link StatisticsReport} instance. + * + * @param indeterminantDecisionsCount the indeterminantDecisionsCount to set + */ + public void setIndeterminantDecisionsCount(long indeterminantDecisionsCount) { + this.indeterminantDecisionsCount = indeterminantDecisionsCount; + } + + /** + * Returns the notApplicableDecisionsCount of this {@link StatisticsReport} instance. + * + * @return the notApplicableDecisionsCount + */ + public long getNotApplicableDecisionsCount() { + return notApplicableDecisionsCount; + } + + /** + * Set notApplicableDecisionsCount in this {@link StatisticsReport} instance. + * + * @param notApplicableDecisionsCount the notApplicableDecisionsCount to set + */ + public void setNotApplicableDecisionsCount(long notApplicableDecisionsCount) { + this.notApplicableDecisionsCount = notApplicableDecisionsCount; + } + + /** + * {@inheritDoc}. + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("StatisticsReport [code="); + builder.append(getCode()); + builder.append(", totalPoliciesCount="); + builder.append(getTotalPoliciesCount()); + builder.append(", permitDecisionsCount="); + builder.append(getPermitDecisionsCount()); + builder.append(", denyDecisionsCount="); + builder.append(getDenyDecisionsCount()); + builder.append(", indeterminantDecisionsCount="); + builder.append(getIndeterminantDecisionsCount()); + builder.append(", notApplicableDecisionsCount="); + builder.append(getNotApplicableDecisionsCount()); + builder.append("]"); + return builder.toString(); + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpRestController.java b/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpRestController.java new file mode 100644 index 00000000..ae950fda --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpRestController.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.Info; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.annotations.Tag; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.policy.common.endpoints.report.HealthCheckReport; + + + +/** + * Class to provide xacml pdp REST services. + * + */ +@Path("/") +@Api +@Produces(MediaType.APPLICATION_JSON) +@SwaggerDefinition(info = @Info(description = "Policy Xacml PDP Service", version = "v1.0", title = "Policy Xacml PDP"), + consumes = {MediaType.APPLICATION_JSON}, produces = {MediaType.APPLICATION_JSON}, + schemes = {SwaggerDefinition.Scheme.HTTP}, + tags = {@Tag(name = "policy-pdpx", description = "Policy Xacml PDP Service Operations")}) +public class XacmlPdpRestController { + + @GET + @Path("healthcheck") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Perform a system healthcheck", + notes = "Provides healthy status of the Policy Xacml PDP component", + response = HealthCheckReport.class) + public Response healthcheck() { + return Response.status(Response.Status.OK).entity(new HealthCheckProvider().performHealthCheck()).build(); + } + + @GET + @Path("statistics") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Fetch current statistics", + notes = "Provides current statistics of the Policy Xacml PDP component", + response = StatisticsReport.class) + public Response statistics() { + return Response.status(Response.Status.OK).entity(new StatisticsProvider().fetchCurrentStatistics()).build(); + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpRestServer.java b/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpRestServer.java new file mode 100644 index 00000000..3a3992fc --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpRestServer.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.rest; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import org.onap.policy.common.capabilities.Startable; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.pdpx.main.parameters.RestServerParameters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class to manage life cycle of xacml pdp rest server. + * + */ +public class XacmlPdpRestServer implements Startable { + + private static final String SEPARATOR = "."; + private static final String HTTP_SERVER_SERVICES = "http.server.services"; + private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpRestServer.class); + + private List<HttpServletServer> servers = new ArrayList<>(); + + private RestServerParameters restServerParameters; + + /** + * Constructor for instantiating XacmlPdpRestServer. + * + * @param restServerParameters the rest server parameters + */ + public XacmlPdpRestServer(final RestServerParameters restServerParameters) { + this.restServerParameters = restServerParameters; + } + + /** + * {@inheritDoc}. + */ + @Override + public boolean start() { + try { + servers = HttpServletServer.factory.build(getServerProperties()); + for (final HttpServletServer server : servers) { + server.start(); + } + } catch (final Exception exp) { + LOGGER.error("Failed to start xacml pdp http server", exp); + return false; + } + return true; + } + + /** + * Creates the server properties object using restServerParameters. + * + * @return the properties object + */ + private Properties getServerProperties() { + final Properties props = new Properties(); + props.setProperty(HTTP_SERVER_SERVICES, restServerParameters.getName()); + props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".host", + restServerParameters.getHost()); + props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".port", + Integer.toString(restServerParameters.getPort())); + props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".restClasses", + XacmlPdpRestController.class.getCanonicalName()); + props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".managed", "false"); + props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".swagger", "true"); + props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".userName", + restServerParameters.getUserName()); + props.setProperty(HTTP_SERVER_SERVICES + SEPARATOR + restServerParameters.getName() + ".password", + restServerParameters.getPassword()); + return props; + } + + /** + * {@inheritDoc}. + */ + @Override + public boolean stop() { + for (final HttpServletServer server : servers) { + try { + server.stop(); + } catch (final Exception exp) { + LOGGER.error("Failed to stop xacml pdp http server", exp); + } + } + return true; + } + + /** + * {@inheritDoc}. + */ + @Override + public void shutdown() { + stop(); + } + + /** + * {@inheritDoc}. + */ + @Override + public boolean isAlive() { + return !servers.isEmpty(); + } + + /** + * {@inheritDoc}. + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("XacmlPdpRestServer [servers="); + builder.append(servers); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpStatisticsManager.java b/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpStatisticsManager.java new file mode 100644 index 00000000..471ffca4 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/rest/XacmlPdpStatisticsManager.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.rest; + +/** + * Class to hold statistical data for xacmlPdp component. + * + */ +public class XacmlPdpStatisticsManager { + + private static long totalPoliciesCount; + private static long permitDecisionsCount; + private static long denyDecisionsCount; + private static long indeterminantDecisionsCount; + private static long notApplicableDecisionsCount; + + private XacmlPdpStatisticsManager() { + throw new IllegalStateException("Instantiation of the class is not allowed"); + } + + /** + * Method to update the xacml pdp total policies count. + * + * @return the total + */ + public static long updateTotalPoliciesCount() { + return ++totalPoliciesCount; + } + + /** + * Method to update the number of permit decisions. + * + * @return the permitDecisionsCount + */ + public static long updatePermitDecisionsCount() { + return ++permitDecisionsCount; + } + + /** + * Method to update the number of deny decisions. + * + * @return the denyDecisionsCount + */ + public static long updateDenyDecisionsCount() { + return ++denyDecisionsCount; + } + + /** + * Method to update the number of indeterminant decisions. + * + * @return the indeterminantDecisionsCount + */ + public static long updateIndeterminantDecisionsCount() { + return ++indeterminantDecisionsCount; + } + + /** + * Method to update the number of not applicable decisions. + * + * @return the notApplicableDecisionsCount + */ + public static long updateNotApplicableDecisionsCount() { + return ++notApplicableDecisionsCount; + } + + /** + * Returns the current value of totalPoliciesCount. + + * @return the totalPoliciesCount + */ + public static long getTotalPoliciesCount() { + return totalPoliciesCount; + } + + /** + * Returns the current value of permitDecisionsCount. + + * @return the permitDecisionsCount + */ + public static long getPermitDecisionsCount() { + return permitDecisionsCount; + } + + /** + * Returns the current value of denyDecisionsCount. + + * @return the denyDecisionsCount + */ + public static long getDenyDecisionsCount() { + return denyDecisionsCount; + } + + /** + * Returns the current value of indeterminantDecisionsCount. + + * @return the indeterminantDecisionsCount + */ + public static long getIndeterminantDecisionsCount() { + return indeterminantDecisionsCount; + } + + /** + * Returns the current value of notApplicableDecisionsCount. + + * @return the notApplicableDecisionsCount + */ + public static long getNotApplicableDecisionsCount() { + return notApplicableDecisionsCount; + } + + /** + * Reset all the statistics counts to 0. + */ + public static void resetAllStatistics() { + totalPoliciesCount = 0L; + permitDecisionsCount = 0L; + denyDecisionsCount = 0L; + indeterminantDecisionsCount = 0L; + notApplicableDecisionsCount = 0L; + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/startstop/Main.java b/main/src/main/java/org/onap/policy/pdpx/main/startstop/Main.java new file mode 100644 index 00000000..2e3c4461 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/startstop/Main.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.startstop; + +import java.util.Arrays; +import org.onap.policy.pdpx.main.PolicyXacmlPdpException; +import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup; +import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * This class initiates ONAP Policy Framework policy xacml pdp. + * + */ +public class Main { + private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); + + // The policy xacml pdp Activator that activates the policy xacml pdp service + private XacmlPdpActivator activator; + + // The parameters read in from JSON + private XacmlPdpParameterGroup parameterGroup; + + /** + * Instantiates the policy xacml pdp service. + * + * @param args the command line arguments + */ + public Main(final String[] args) { + final String argumentString = Arrays.toString(args); + LOGGER.info("Starting policy xacml pdp service with arguments - " + argumentString); + + // Check the arguments + final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); + try { + // The arguments return a string if there is a message to print and we should exit + final String argumentMessage = arguments.parse(args); + if (argumentMessage != null) { + LOGGER.info(argumentMessage); + return; + } + + // Validate that the arguments are sane + arguments.validate(); + } catch (final PolicyXacmlPdpException e) { + LOGGER.error("start of policy xacml pdp service failed", e); + return; + } + + // Read the parameters + try { + parameterGroup = new XacmlPdpParameterHandler().getParameters(arguments); + } catch (final Exception e) { + LOGGER.error("start of policy xacml pdp service failed", e); + return; + } + + // Now, create the activator for the policy xacml pdp service + activator = new XacmlPdpActivator(parameterGroup); + + // Start the activator + try { + activator.initialize(); + } catch (final PolicyXacmlPdpException e) { + LOGGER.error("start of policy xacml pdp service failed, used parameters are " + Arrays.toString(args), e); + return; + } + + // Add a shutdown hook to shut everything down in an orderly manner + Runtime.getRuntime().addShutdownHook(new PolicyXacmlPdpShutdownHookClass()); + LOGGER.info("Started policy xacml pdp service"); + } + + /** + * Get the parameters specified in JSON. + * + * @return the parameters + */ + public XacmlPdpParameterGroup getParameters() { + return parameterGroup; + } + + /** + * Shut down Execution. + * + * @throws PolicyXacmlPdpException on shutdown errors + */ + public void shutdown() throws PolicyXacmlPdpException { + // clear the parameterGroup variable + parameterGroup = null; + + // clear the xacml pdp activator + if (activator != null) { + activator.terminate(); + } + } + + /** + * The Class PolicyXacmlPdpShutdownHookClass terminates the policy xacml pdp service when its run + * method is called. + */ + private class PolicyXacmlPdpShutdownHookClass extends Thread { + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + try { + // Shutdown the policy xacml pdp service and wait for everything to stop + activator.terminate(); + } catch (final PolicyXacmlPdpException e) { + LOGGER.warn("error occured during shut down of the policy xacml pdp service", e); + } + } + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { + new Main(args); + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/startstop/XacmlPdpActivator.java b/main/src/main/java/org/onap/policy/pdpx/main/startstop/XacmlPdpActivator.java new file mode 100644 index 00000000..d50c4f13 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/startstop/XacmlPdpActivator.java @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.startstop; + +import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.pdpx.main.PolicyXacmlPdpException; +import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup; +import org.onap.policy.pdpx.main.rest.XacmlPdpRestServer; +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 xacml pdp and forwarding handlers. + */ +public class XacmlPdpActivator { + // The logger for this class + private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpActivator.class); + + // The parameters of this policy xacml pdp activator + private final XacmlPdpParameterGroup xacmlPdpParameterGroup; + + private static boolean alive = false; + + private XacmlPdpRestServer restServer; + + /** + * Instantiate the activator for policy xacml pdp as a complete service. + * + * @param xacmlPdpParameterGroup the parameters for the xacml pdp service + */ + public XacmlPdpActivator(final XacmlPdpParameterGroup xacmlPdpParameterGroup) { + this.xacmlPdpParameterGroup = xacmlPdpParameterGroup; + } + + /** + * Initialize xacml pdp as a complete service. + * + * @throws PolicyXacmlPdpException on errors in initializing the service + */ + public void initialize() throws PolicyXacmlPdpException { + LOGGER.debug("Policy xacml pdp starting as a service . . ."); + startXacmlPdpRestServer(); + registerToParameterService(xacmlPdpParameterGroup); + XacmlPdpActivator.setAlive(true); + LOGGER.debug("Policy xacml pdp started as a service"); + } + + /** + * Starts the xacml pdp rest server using configuration parameters. + * + * @throws PolicyXacmlPdpException if server start fails + */ + private void startXacmlPdpRestServer() throws PolicyXacmlPdpException { + xacmlPdpParameterGroup.getRestServerParameters().setName(xacmlPdpParameterGroup.getName()); + restServer = new XacmlPdpRestServer(xacmlPdpParameterGroup.getRestServerParameters()); + if (!restServer.start()) { + throw new PolicyXacmlPdpException("Failed to start xacml pdp rest server. Check log for more details..."); + } + } + + /** + * Terminate policy xacml pdp. + * + * @throws PolicyXacmlPdpException on termination errors + */ + public void terminate() throws PolicyXacmlPdpException { + try { + deregisterToParameterService(xacmlPdpParameterGroup); + XacmlPdpActivator.setAlive(false); + + // Stop the xacml pdp rest server + restServer.stop(); + } catch (final Exception exp) { + LOGGER.error("Policy xacml pdp service termination failed", exp); + throw new PolicyXacmlPdpException(exp.getMessage(), exp); + } + } + + /** + * Get the parameters used by the activator. + * + * @return the parameters of the activator + */ + public XacmlPdpParameterGroup getParameterGroup() { + return xacmlPdpParameterGroup; + } + + /** + * Method to register the parameters to Common Parameter Service. + * + * @param xacmlPdpParameterGroup the xacml pdp parameter group + */ + public void registerToParameterService(final XacmlPdpParameterGroup xacmlPdpParameterGroup) { + ParameterService.register(xacmlPdpParameterGroup); + } + + /** + * Method to deregister the parameters from Common Parameter Service. + * + * @param xacmlPdpParameterGroup the xacml pdp parameter group + */ + public void deregisterToParameterService(final XacmlPdpParameterGroup xacmlPdpParameterGroup) { + ParameterService.deregister(xacmlPdpParameterGroup.getName()); + } + + /** + * Returns the alive status of xacml pdp service. + * + * @return the alive + */ + public static boolean isAlive() { + return alive; + } + + /** + * Change the alive status of xacml pdp service. + * + * @param status the status + */ + private static void setAlive(final boolean status) { + alive = status; + } +} diff --git a/main/src/main/java/org/onap/policy/pdpx/main/startstop/XacmlPdpCommandLineArguments.java b/main/src/main/java/org/onap/policy/pdpx/main/startstop/XacmlPdpCommandLineArguments.java new file mode 100644 index 00000000..1b0f62e3 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pdpx/main/startstop/XacmlPdpCommandLineArguments.java @@ -0,0 +1,244 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.startstop; + +import java.io.File; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URL; +import java.util.Arrays; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.pdpx.main.PolicyXacmlPdpException; +import org.onap.policy.pdpx.main.PolicyXacmlPdpRuntimeException; + + +/** + * This class reads and handles command line parameters for the policy xacml pdp main program. + */ +public class XacmlPdpCommandLineArguments { + private static final String FILE_MESSAGE_PREAMBLE = " file \""; + private static final int HELP_LINE_LENGTH = 120; + + // Apache Commons CLI options + private final Options options; + + // The command line options + private String configurationFilePath = null; + + /** + * Construct the options for the CLI editor. + */ + public XacmlPdpCommandLineArguments() { + //@formatter:off + options = new Options(); + options.addOption(Option.builder("h") + .longOpt("help") + .desc("outputs the usage of this command") + .required(false) + .type(Boolean.class) + .build()); + options.addOption(Option.builder("v") + .longOpt("version") + .desc("outputs the version of policy xacml pdp") + .required(false) + .type(Boolean.class) + .build()); + options.addOption(Option.builder("c") + .longOpt("config-file") + .desc("the full path to the configuration file to use, " + + "the configuration file must be a Json file containing the policy xacml pdp parameters") + .hasArg() + .argName("CONFIG_FILE") + .required(false) + .type(String.class) + .build()); + //@formatter:on + } + + /** + * Construct the options for the CLI editor and parse in the given arguments. + * + * @param args The command line arguments + */ + public XacmlPdpCommandLineArguments(final String[] args) { + // Set up the options with the default constructor + this(); + + // Parse the arguments + try { + parse(args); + } catch (final PolicyXacmlPdpException e) { + throw new PolicyXacmlPdpRuntimeException("parse error on policy xacml pdp parameters", e); + } + } + + /** + * Parse the command line options. + * + * @param args The command line arguments + * @return a string with a message for help and version, or null if there is no message + * @throws PolicyXacmlPdpException on command argument errors + */ + public String parse(final String[] args) throws PolicyXacmlPdpException { + // Clear all our arguments + setConfigurationFilePath(null); + + CommandLine commandLine = null; + try { + commandLine = new DefaultParser().parse(options, args); + } catch (final ParseException e) { + throw new PolicyXacmlPdpException("invalid command line arguments specified : " + e.getMessage()); + } + + // Arguments left over after Commons CLI does its stuff + final String[] remainingArgs = commandLine.getArgs(); + + if (remainingArgs.length > 0) { + throw new PolicyXacmlPdpException("too many command line arguments specified : " + Arrays.toString(args)); + } + + if (remainingArgs.length == 1) { + configurationFilePath = remainingArgs[0]; + } + + if (commandLine.hasOption('h')) { + return help(Main.class.getCanonicalName()); + } + + if (commandLine.hasOption('v')) { + return version(); + } + + if (commandLine.hasOption('c')) { + setConfigurationFilePath(commandLine.getOptionValue('c')); + } + + return null; + } + + /** + * Validate the command line options. + * + * @throws PolicyXacmlPdpException on command argument validation errors + */ + public void validate() throws PolicyXacmlPdpException { + validateReadableFile("policy xacml pdp configuration", configurationFilePath); + } + + /** + * Print version information for policy xacml pdp. + * + * @return the version string + */ + public String version() { + return ResourceUtils.getResourceAsString("version.txt"); + } + + /** + * Print help information for policy xacml pdp. + * + * @param mainClassName the main class name + * @return the help string + */ + public String help(final String mainClassName) { + final HelpFormatter helpFormatter = new HelpFormatter(); + final StringWriter stringWriter = new StringWriter(); + final PrintWriter printWriter = new PrintWriter(stringWriter); + + helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0, + 0, ""); + + return stringWriter.toString(); + } + + /** + * Gets the configuration file path. + * + * @return the configuration file path + */ + public String getConfigurationFilePath() { + return configurationFilePath; + } + + /** + * Gets the full expanded configuration file path. + * + * @return the configuration file path + */ + public String getFullConfigurationFilePath() { + return ResourceUtils.getFilePath4Resource(getConfigurationFilePath()); + } + + /** + * Sets the configuration file path. + * + * @param configurationFilePath the configuration file path + */ + public void setConfigurationFilePath(final String configurationFilePath) { + this.configurationFilePath = configurationFilePath; + + } + + /** + * Check set configuration file path. + * + * @return true, if check set configuration file path + */ + public boolean checkSetConfigurationFilePath() { + return configurationFilePath != null && !configurationFilePath.isEmpty(); + } + + /** + * Validate readable file. + * + * @param fileTag the file tag + * @param fileName the file name + * @throws PolicyXacmlPdpException on the file name passed as a parameter + */ + private void validateReadableFile(final String fileTag, final String fileName) throws PolicyXacmlPdpException { + if (fileName == null || fileName.isEmpty()) { + throw new PolicyXacmlPdpException(fileTag + " file was not specified as an argument"); + } + + // The file name refers to a resource on the local file system + final URL fileUrl = ResourceUtils.getUrl4Resource(fileName); + if (fileUrl == null) { + throw new PolicyXacmlPdpException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + + final File theFile = new File(fileUrl.getPath()); + if (!theFile.exists()) { + throw new PolicyXacmlPdpException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + if (!theFile.isFile()) { + throw new PolicyXacmlPdpException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file"); + } + if (!theFile.canRead()) { + throw new PolicyXacmlPdpException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable"); + } + } +} diff --git a/main/src/main/resources/version.txt b/main/src/main/resources/version.txt new file mode 100644 index 00000000..13927176 --- /dev/null +++ b/main/src/main/resources/version.txt @@ -0,0 +1,4 @@ +ONAP Policy Framework Xacml PDP Service +Version: ${project.version} +Built (UTC): ${maven.build.timestamp} +ONAP https://wiki.onap.org
\ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/pdpx/main/parameters/CommonTestData.java b/main/src/test/java/org/onap/policy/pdpx/main/parameters/CommonTestData.java new file mode 100644 index 00000000..f50871ec --- /dev/null +++ b/main/src/test/java/org/onap/policy/pdpx/main/parameters/CommonTestData.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.parameters; + +/** + * Class to hold/create all parameters for test cases. + * + */ +public class CommonTestData { + + private static final String REST_SERVER_PASSWORD = "zb!XztG34"; + private static final String REST_SERVER_USER = "healthcheck"; + private static final int REST_SERVER_PORT = 6969; + private static final String REST_SERVER_HOST = "0.0.0.0"; + public static final String PDPX_GROUP_NAME = "XacmlPdpGroup"; + + /** + * Returns an instance of RestServerParameters for test cases. + * + * @param isEmpty boolean value to represent that object created should be empty or not + * @return the restServerParameters object + */ + public RestServerParameters getRestServerParameters(final boolean isEmpty) { + final RestServerParameters restServerParameters; + if (!isEmpty) { + restServerParameters = new RestServerParameters(REST_SERVER_HOST, REST_SERVER_PORT, REST_SERVER_USER, + REST_SERVER_PASSWORD); + } else { + restServerParameters = new RestServerParameters(null, 0, null, null); + } + return restServerParameters; + } + +} diff --git a/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java new file mode 100644 index 00000000..4b9db99d --- /dev/null +++ b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterGroup.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.parameters; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.common.parameters.GroupValidationResult; + +/** + * Class to perform unit test of XacmlPdpParameterGroup. + * + */ +public class TestXacmlPdpParameterGroup { + CommonTestData commonTestData = new CommonTestData(); + + @Test + public void testXacmlPdpParameterGroup() { + final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false); + final XacmlPdpParameterGroup pdpxParameters = + new XacmlPdpParameterGroup(CommonTestData.PDPX_GROUP_NAME, restServerParameters); + final GroupValidationResult validationResult = pdpxParameters.validate(); + assertTrue(validationResult.isValid()); + assertEquals(restServerParameters.getHost(), pdpxParameters.getRestServerParameters().getHost()); + assertEquals(restServerParameters.getPort(), pdpxParameters.getRestServerParameters().getPort()); + assertEquals(restServerParameters.getUserName(), pdpxParameters.getRestServerParameters().getUserName()); + assertEquals(restServerParameters.getPassword(), pdpxParameters.getRestServerParameters().getPassword()); + assertEquals(CommonTestData.PDPX_GROUP_NAME, pdpxParameters.getName()); + } + + @Test + public void testXacmlPdpParameterGroup_NullName() { + final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false); + final XacmlPdpParameterGroup pdpxParameters = new XacmlPdpParameterGroup(null, restServerParameters); + final GroupValidationResult validationResult = pdpxParameters.validate(); + assertFalse(validationResult.isValid()); + assertEquals(null, pdpxParameters.getName()); + assertTrue(validationResult.getResult().contains( + "field \"name\" type \"java.lang.String\" value \"null\" INVALID, " + "must be a non-blank string")); + } + + @Test + public void testXacmlPdpParameterGroup_EmptyName() { + final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(false); + + final XacmlPdpParameterGroup pdpxParameters = new XacmlPdpParameterGroup("", restServerParameters); + final GroupValidationResult validationResult = pdpxParameters.validate(); + assertFalse(validationResult.isValid()); + assertEquals("", pdpxParameters.getName()); + assertTrue(validationResult.getResult().contains( + "field \"name\" type \"java.lang.String\" value \"\" INVALID, " + "must be a non-blank string")); + } + + @Test + public void testXacmlPdpParameterGroup_EmptyRestServerParameters() { + final RestServerParameters restServerParameters = commonTestData.getRestServerParameters(true); + + final XacmlPdpParameterGroup pdpxParameters = + new XacmlPdpParameterGroup(CommonTestData.PDPX_GROUP_NAME, restServerParameters); + final GroupValidationResult validationResult = pdpxParameters.validate(); + assertFalse(validationResult.isValid()); + assertTrue(validationResult.getResult() + .contains("\"org.onap.policy.pdpx.main.parameters.RestServerParameters\" INVALID, " + + "parameter group has status INVALID")); + } +} diff --git a/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java new file mode 100644 index 00000000..3955031a --- /dev/null +++ b/main/src/test/java/org/onap/policy/pdpx/main/parameters/TestXacmlPdpParameterHandler.java @@ -0,0 +1,179 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.parameters; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import org.junit.Test; +import org.onap.policy.pdpx.main.PolicyXacmlPdpException; +import org.onap.policy.pdpx.main.startstop.XacmlPdpCommandLineArguments; + +/** + * Class to perform unit test of XacmlPdpParameterHandler. + * + */ +public class TestXacmlPdpParameterHandler { + @Test + public void testParameterHandlerNoParameterFile() throws PolicyXacmlPdpException { + final String[] noArgumentString = {"-c", "parameters/NoParameterFile.json"}; + + final XacmlPdpCommandLineArguments noArguments = new XacmlPdpCommandLineArguments(); + noArguments.parse(noArgumentString); + + assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(noArguments)) + .isInstanceOf(PolicyXacmlPdpException.class); + } + + @Test + public void testParameterHandlerEmptyParameters() throws PolicyXacmlPdpException { + final String[] emptyArgumentString = {"-c", "parameters/EmptyParameters.json"}; + + final XacmlPdpCommandLineArguments emptyArguments = new XacmlPdpCommandLineArguments(); + emptyArguments.parse(emptyArgumentString); + + assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(emptyArguments)) + .hasMessage("no parameters found in \"parameters/EmptyParameters.json\""); + } + + @Test + public void testParameterHandlerBadParameters() throws PolicyXacmlPdpException { + final String[] badArgumentString = {"-c", "parameters/BadParameters.json"}; + + final XacmlPdpCommandLineArguments badArguments = new XacmlPdpCommandLineArguments(); + badArguments.parse(badArgumentString); + + assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(badArguments)) + .hasMessage("error reading parameters from \"parameters/BadParameters.json\"\n" + + "(JsonSyntaxException):java.lang.IllegalStateException: " + + "Expected a string but was BEGIN_ARRAY at line 2 column 14 path $.name"); + + } + + @Test + public void testParameterHandlerInvalidParameters() throws PolicyXacmlPdpException { + final String[] invalidArgumentString = {"-c", "parameters/InvalidParameters.json"}; + + final XacmlPdpCommandLineArguments invalidArguments = new XacmlPdpCommandLineArguments(); + invalidArguments.parse(invalidArgumentString); + + assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(invalidArguments)) + .hasMessage("error reading parameters from \"parameters/InvalidParameters.json\"\n" + + "(JsonSyntaxException):java.lang.IllegalStateException: " + + "Expected a string but was BEGIN_ARRAY at line 2 column 14 path $.name"); + } + + @Test + public void testParameterHandlerNoParameters() throws PolicyXacmlPdpException { + final String[] noArgumentString = {"-c", "parameters/NoParameters.json"}; + + final XacmlPdpCommandLineArguments noArguments = new XacmlPdpCommandLineArguments(); + noArguments.parse(noArgumentString); + + assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(noArguments)) + .hasMessage("validation error(s) on parameters from \"parameters/NoParameters.json\"\nparameter group " + + "\"null\" type \"org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup\" INVALID, " + + "parameter group has status INVALID\n" + + " field \"name\" type \"java.lang.String\" value \"null\" " + + "INVALID, must be a non-blank string\n"); + } + + @Test + public void testParameterHandlerMinumumParameters() throws PolicyXacmlPdpException { + final String[] minArgumentString = {"-c", "parameters/MinimumParameters.json"}; + + final XacmlPdpCommandLineArguments minArguments = new XacmlPdpCommandLineArguments(); + minArguments.parse(minArgumentString); + + final XacmlPdpParameterGroup parGroup = new XacmlPdpParameterHandler().getParameters(minArguments); + assertEquals(CommonTestData.PDPX_GROUP_NAME, parGroup.getName()); + } + + @Test + public void testXacmlPdpParameterGroup() throws PolicyXacmlPdpException { + final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters.json"}; + + final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); + arguments.parse(xacmlPdpConfigParameters); + + final XacmlPdpParameterGroup parGroup = new XacmlPdpParameterHandler().getParameters(arguments); + assertTrue(arguments.checkSetConfigurationFilePath()); + assertEquals(CommonTestData.PDPX_GROUP_NAME, parGroup.getName()); + } + + @Test + public void testXacmlPdpParameterGroup_InvalidName() throws PolicyXacmlPdpException { + final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters_InvalidName.json"}; + + final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); + arguments.parse(xacmlPdpConfigParameters); + + assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(arguments)).hasMessageContaining( + "field \"name\" type \"java.lang.String\" value \" \" INVALID, must be a non-blank string"); + } + + @Test + public void testXacmlPdpParameterGroup_InvalidRestServerParameters() throws PolicyXacmlPdpException, IOException { + final String[] xacmlPdpConfigParameters = + {"-c", "parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json"}; + + final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); + arguments.parse(xacmlPdpConfigParameters); + + final String expectedResult = new String(Files.readAllBytes( + Paths.get("src/test/resources/expectedValidationResults/InvalidRestServerParameters.txt"))); + + assertThatThrownBy(() -> new XacmlPdpParameterHandler().getParameters(arguments)) + .hasMessageContaining("validation error(s) on parameters from " + + "\"parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json\""); + } + + @Test + public void testXacmlPdpVersion() throws PolicyXacmlPdpException { + final String[] xacmlPdpConfigParameters = {"-v"}; + final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); + final String version = arguments.parse(xacmlPdpConfigParameters); + assertTrue(version.startsWith("ONAP Policy Framework Xacml PDP Service")); + } + + @Test + public void testXacmlPdpHelp() throws PolicyXacmlPdpException { + final String[] xacmlPdpConfigParameters = {"-h"}; + final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); + final String help = arguments.parse(xacmlPdpConfigParameters); + assertTrue(help.startsWith("usage:")); + } + + @Test + public void testXacmlPdpInvalidOption() throws PolicyXacmlPdpException { + final String[] xacmlPdpConfigParameters = {"-d"}; + final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(); + try { + arguments.parse(xacmlPdpConfigParameters); + } catch (final Exception exp) { + assertTrue(exp.getMessage().startsWith("invalid command line arguments specified")); + } + } +} diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java new file mode 100644 index 00000000..a116a154 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestStatisticsReport.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.rest; + +import com.openpojo.reflection.filters.FilterClassName; +import com.openpojo.validation.Validator; +import com.openpojo.validation.ValidatorBuilder; +import com.openpojo.validation.rule.impl.SetterMustExistRule; +import com.openpojo.validation.test.impl.GetterTester; +import com.openpojo.validation.test.impl.SetterTester; + +import org.junit.Test; +import org.onap.policy.common.utils.validation.ToStringTester; + +/** + * Class to perform unit testing of {@link StatisticsReport}. + * + */ +public class TestStatisticsReport { + + @Test + public void testStatisticsReport() { + final Validator validator = ValidatorBuilder.create().with(new ToStringTester()).with(new SetterMustExistRule()) + .with(new SetterTester()).with(new GetterTester()).build(); + validator.validate(StatisticsReport.class.getPackage().getName(), + new FilterClassName(StatisticsReport.class.getName())); + } +} diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java new file mode 100644 index 00000000..ce0671a6 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpRestServer.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; +import org.junit.Test; +import org.onap.policy.common.endpoints.report.HealthCheckReport; +import org.onap.policy.pdpx.main.PolicyXacmlPdpException; +import org.onap.policy.pdpx.main.parameters.CommonTestData; +import org.onap.policy.pdpx.main.parameters.RestServerParameters; +import org.onap.policy.pdpx.main.startstop.Main; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Class to perform unit test of HealthCheckMonitor. + * + */ +public class TestXacmlPdpRestServer { + + private static final Logger LOGGER = LoggerFactory.getLogger(TestXacmlPdpRestServer.class); + private static final String NOT_ALIVE = "not alive"; + private static final String ALIVE = "alive"; + private static final String SELF = "self"; + private static final String NAME = "Policy Xacml PDP"; + + @Test + public void testHealthCheckSuccess() throws PolicyXacmlPdpException, InterruptedException { + final String reportString = "Report [name=Policy Xacml PDP, url=self, healthy=true, code=200, message=alive]"; + final Main main = startXacmlPdpService(); + final HealthCheckReport report = performHealthCheck(); + validateReport(NAME, SELF, true, 200, ALIVE, reportString, report); + stopXacmlPdpService(main); + } + + @Test + public void testHealthCheckFailure() throws InterruptedException { + final String reportString = + "Report [name=Policy Xacml PDP, url=self, healthy=false, code=500, message=not alive]"; + final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); + restServerParams.setName(CommonTestData.PDPX_GROUP_NAME); + final XacmlPdpRestServer restServer = new XacmlPdpRestServer(restServerParams); + restServer.start(); + final HealthCheckReport report = performHealthCheck(); + validateReport(NAME, SELF, false, 500, NOT_ALIVE, reportString, report); + assertTrue(restServer.isAlive()); + assertTrue(restServer.toString().startsWith("XacmlPdpRestServer [servers=")); + restServer.shutdown(); + } + + private Main startXacmlPdpService() { + final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters.json"}; + return new Main(xacmlPdpConfigParameters); + } + + private void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException { + main.shutdown(); + } + + private HealthCheckReport performHealthCheck() throws InterruptedException { + HealthCheckReport response = null; + final ClientConfig clientConfig = new ClientConfig(); + + final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"); + clientConfig.register(feature); + + final Client client = ClientBuilder.newClient(clientConfig); + final WebTarget webTarget = client.target("http://localhost:6969/healthcheck"); + + final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); + + final long startTime = System.currentTimeMillis(); + while (response == null && (System.currentTimeMillis() - startTime) < 120000) { + try { + response = invocationBuilder.get(HealthCheckReport.class); + } catch (final Exception exp) { + LOGGER.info("the server is not started yet. We will retry again"); + } + } + return response; + } + + private void validateReport(final String name, final String url, final boolean healthy, final int code, + final String message, final String reportString, final HealthCheckReport report) { + assertEquals(name, report.getName()); + assertEquals(url, report.getUrl()); + assertEquals(healthy, report.isHealthy()); + assertEquals(code, report.getCode()); + assertEquals(message, report.getMessage()); + assertEquals(reportString, report.toString()); + } +} diff --git a/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java new file mode 100644 index 00000000..303a3cfe --- /dev/null +++ b/main/src/test/java/org/onap/policy/pdpx/main/rest/TestXacmlPdpStatistics.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.rest; + +import static org.junit.Assert.assertEquals; + +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.pdpx.main.PolicyXacmlPdpException; +import org.onap.policy.pdpx.main.parameters.CommonTestData; +import org.onap.policy.pdpx.main.parameters.RestServerParameters; +import org.onap.policy.pdpx.main.rest.XacmlPdpStatisticsManager; +import org.onap.policy.pdpx.main.startstop.Main; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class to perform unit test of {@link XacmlPdpRestController}. + * + */ +public class TestXacmlPdpStatistics { + + private static final Logger LOGGER = LoggerFactory.getLogger(TestXacmlPdpStatistics.class); + + + @Test + public void testXacmlPdpStatistics_200() throws PolicyXacmlPdpException, InterruptedException { + final Main main = startXacmlPdpService(); + StatisticsReport report = getXacmlPdpStatistics(); + + validateReport(report, 0, 200); + updateXacmlPdpStatistics(); + report = getXacmlPdpStatistics(); + validateReport(report, 1, 200); + stopXacmlPdpService(main); + XacmlPdpStatisticsManager.resetAllStatistics(); + } + + @Test + public void testXacmlPdpStatistics_500() throws InterruptedException { + final RestServerParameters restServerParams = new CommonTestData().getRestServerParameters(false); + restServerParams.setName(CommonTestData.PDPX_GROUP_NAME); + + final XacmlPdpRestServer restServer = new XacmlPdpRestServer(restServerParams); + restServer.start(); + final StatisticsReport report = getXacmlPdpStatistics(); + + validateReport(report, 0, 500); + restServer.shutdown(); + XacmlPdpStatisticsManager.resetAllStatistics(); + } + + + private Main startXacmlPdpService() { + final String[] XacmlPdpConfigParameters = + { "-c", "parameters/XacmlPdpConfigParameters.json" }; + return new Main(XacmlPdpConfigParameters); + } + + private void stopXacmlPdpService(final Main main) throws PolicyXacmlPdpException { + main.shutdown(); + } + + private StatisticsReport getXacmlPdpStatistics() throws InterruptedException { + StatisticsReport response = null; + final ClientConfig clientConfig = new ClientConfig(); + + final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("healthcheck", "zb!XztG34"); + clientConfig.register(feature); + + final Client client = ClientBuilder.newClient(clientConfig); + final WebTarget webTarget = client.target("http://localhost:6969/statistics"); + + final Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON); + final long startTime = System.currentTimeMillis(); + while (response == null && (System.currentTimeMillis() - startTime) < 120000) { + try { + response = invocationBuilder.get(StatisticsReport.class); + } catch (final Exception exp) { + LOGGER.info("the server is not started yet. We will retry again"); + } + } + return response; + } + + private void updateXacmlPdpStatistics() { + XacmlPdpStatisticsManager.updateTotalPoliciesCount(); + XacmlPdpStatisticsManager.updatePermitDecisionsCount(); + XacmlPdpStatisticsManager.updateDenyDecisionsCount(); + XacmlPdpStatisticsManager.updateIndeterminantDecisionsCount(); + XacmlPdpStatisticsManager.updateNotApplicableDecisionsCount(); + } + + private void validateReport(final StatisticsReport report, final int count, final int code) { + assertEquals(code, report.getCode()); + assertEquals(count, report.getTotalPoliciesCount()); + assertEquals(count, report.getPermitDecisionsCount()); + assertEquals(count, report.getDenyDecisionsCount()); + assertEquals(count, report.getIndeterminantDecisionsCount()); + assertEquals(count, report.getNotApplicableDecisionsCount()); + } +} diff --git a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java new file mode 100644 index 00000000..8178343c --- /dev/null +++ b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestMain.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.startstop; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.pdpx.main.PolicyXacmlPdpException; +import org.onap.policy.pdpx.main.parameters.CommonTestData; + +/** + * Class to perform unit test of Main. + * + */ +public class TestMain { + + @Test + public void testMain() throws PolicyXacmlPdpException { + final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters.json"}; + final Main main = new Main(xacmlPdpConfigParameters); + assertTrue(main.getParameters().isValid()); + assertEquals(CommonTestData.PDPX_GROUP_NAME, main.getParameters().getName()); + main.shutdown(); + } + + @Test + public void testMain_NoArguments() { + final String[] xacmlPdpConfigParameters = {}; + final Main main = new Main(xacmlPdpConfigParameters); + assertNull(main.getParameters()); + } + + @Test + public void testMain_InvalidArguments() { + final String[] xacmlPdpConfigParameters = {"parameters/XacmlPdpConfigParameters.json"}; + final Main main = new Main(xacmlPdpConfigParameters); + assertNull(main.getParameters()); + } + + @Test + public void testMain_Help() { + final String[] xacmlPdpConfigParameters = {"-h"}; + Main.main(xacmlPdpConfigParameters); + } + + @Test + public void testMain_InvalidParameters() { + final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters_InvalidName.json"}; + final Main main = new Main(xacmlPdpConfigParameters); + assertNull(main.getParameters()); + } +} diff --git a/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java new file mode 100644 index 00000000..7a514f70 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pdpx/main/startstop/TestXacmlPdpActivator.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * 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.pdpx.main.startstop; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.BeforeClass; + +import org.junit.Test; +import org.onap.policy.pdpx.main.PolicyXacmlPdpException; +import org.onap.policy.pdpx.main.parameters.CommonTestData; +import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup; +import org.onap.policy.pdpx.main.parameters.XacmlPdpParameterHandler; + + +/** + * Class to perform unit test of XacmlPdpActivator. + * + */ +public class TestXacmlPdpActivator { + private static XacmlPdpActivator activator = null; + + /** + * Setup the tests. + * @throws PolicyXacmlPdpException when Xacml PDP Exceptional condition occurs + */ + @BeforeClass + public static void setup() throws PolicyXacmlPdpException { + final String[] xacmlPdpConfigParameters = {"-c", "parameters/XacmlPdpConfigParameters.json"}; + + final XacmlPdpCommandLineArguments arguments = new XacmlPdpCommandLineArguments(xacmlPdpConfigParameters); + + final XacmlPdpParameterGroup parGroup = new XacmlPdpParameterHandler().getParameters(arguments); + + activator = new XacmlPdpActivator(parGroup); + activator.initialize(); + } + + @Test + public void testXacmlPdpActivator() throws PolicyXacmlPdpException { + assertTrue(activator.getParameterGroup().isValid()); + assertEquals(CommonTestData.PDPX_GROUP_NAME, activator.getParameterGroup().getName()); + } + + @After + public void teardown() throws PolicyXacmlPdpException { + activator.terminate(); + } +} diff --git a/main/src/test/resources/expectedValidationResults/InvalidRestServerParameters.txt b/main/src/test/resources/expectedValidationResults/InvalidRestServerParameters.txt new file mode 100644 index 00000000..957da6d6 --- /dev/null +++ b/main/src/test/resources/expectedValidationResults/InvalidRestServerParameters.txt @@ -0,0 +1,7 @@ +validation error(s) on parameters from "parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json" +parameter group "XacmlPdpGroup" type "org.onap.policy.pdpx.main.parameters.XacmlPdpParameterGroup" INVALID, parameter group has status INVALID + parameter group "null" type "org.onap.policy.pdpx.main.parameters.RestServerParameters" INVALID, parameter group has status INVALID + field "host" type "java.lang.String" value "" INVALID, must be a non-blank string containing hostname/ipaddress of the xacml pdp rest server + field "port" type "int" value "-1" INVALID, must be a positive integer containing port of the xacml pdp rest server + field "userName" type "java.lang.String" value "" INVALID, must be a non-blank string containing userName for xacml pdp rest server credentials + field "password" type "java.lang.String" value "" INVALID, must be a non-blank string containing password for xacml pdp rest server credentials diff --git a/main/src/test/resources/parameters/BadParameters.json b/main/src/test/resources/parameters/BadParameters.json new file mode 100644 index 00000000..f2abd509 --- /dev/null +++ b/main/src/test/resources/parameters/BadParameters.json @@ -0,0 +1,3 @@ +{ + "name": [] +}
\ No newline at end of file diff --git a/main/src/test/resources/parameters/EmptyParameters.json b/main/src/test/resources/parameters/EmptyParameters.json new file mode 100644 index 00000000..e69de29b --- /dev/null +++ b/main/src/test/resources/parameters/EmptyParameters.json diff --git a/main/src/test/resources/parameters/InvalidParameters.json b/main/src/test/resources/parameters/InvalidParameters.json new file mode 100644 index 00000000..f2abd509 --- /dev/null +++ b/main/src/test/resources/parameters/InvalidParameters.json @@ -0,0 +1,3 @@ +{ + "name": [] +}
\ No newline at end of file diff --git a/main/src/test/resources/parameters/MinimumParameters.json b/main/src/test/resources/parameters/MinimumParameters.json new file mode 100644 index 00000000..798731ae --- /dev/null +++ b/main/src/test/resources/parameters/MinimumParameters.json @@ -0,0 +1,9 @@ +{ + "name": "XacmlPdpGroup", + "restServerParameters": { + "host": "0.0.0.0", + "port": 6969, + "userName": "healthcheck", + "password": "zb!XztG34" + } +} diff --git a/main/src/test/resources/parameters/NoParameters.json b/main/src/test/resources/parameters/NoParameters.json new file mode 100644 index 00000000..bbe1ee13 --- /dev/null +++ b/main/src/test/resources/parameters/NoParameters.json @@ -0,0 +1,8 @@ +{ + "restServerParameters": { + "host": "0.0.0.0", + "port": 6969, + "userName": "healthcheck", + "password": "zb!XztG34" + } +}
\ No newline at end of file diff --git a/main/src/test/resources/parameters/XacmlPdpConfigParameters.json b/main/src/test/resources/parameters/XacmlPdpConfigParameters.json new file mode 100644 index 00000000..798731ae --- /dev/null +++ b/main/src/test/resources/parameters/XacmlPdpConfigParameters.json @@ -0,0 +1,9 @@ +{ + "name": "XacmlPdpGroup", + "restServerParameters": { + "host": "0.0.0.0", + "port": 6969, + "userName": "healthcheck", + "password": "zb!XztG34" + } +} diff --git a/main/src/test/resources/parameters/XacmlPdpConfigParameters_InvalidName.json b/main/src/test/resources/parameters/XacmlPdpConfigParameters_InvalidName.json new file mode 100644 index 00000000..8949a3c4 --- /dev/null +++ b/main/src/test/resources/parameters/XacmlPdpConfigParameters_InvalidName.json @@ -0,0 +1,9 @@ +{ + "name": " ", + "restServerParameters": { + "host": "0.0.0.0", + "port": 6969, + "userName": "healthcheck", + "password": "zb!XztG34" + } +} diff --git a/main/src/test/resources/parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json b/main/src/test/resources/parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json new file mode 100644 index 00000000..8b8e5c67 --- /dev/null +++ b/main/src/test/resources/parameters/XacmlPdpConfigParameters_InvalidRestServerParameters.json @@ -0,0 +1,9 @@ +{ + "name": "XacmlPdpGroup", + "restServerParameters": { + "host": "", + "port": -1, + "userName": "", + "password": "" + } +} |