diff options
Diffstat (limited to 'main/src/main/java/org/onap')
14 files changed, 1350 insertions, 1 deletions
diff --git a/main/src/main/java/org/onap/policy/pap/main/CustomImplicitNamingStrategy.java b/main/src/main/java/org/onap/policy/pap/main/CustomImplicitNamingStrategy.java new file mode 100644 index 00000000..7505039b --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/CustomImplicitNamingStrategy.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main; + +import org.hibernate.boot.model.naming.Identifier; +import org.hibernate.boot.model.naming.ImplicitJoinColumnNameSource; +import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl; + +public class CustomImplicitNamingStrategy extends ImplicitNamingStrategyJpaCompliantImpl { + + private static final long serialVersionUID = 8666774028328486896L; + + @Override + public Identifier determineJoinColumnName(ImplicitJoinColumnNameSource source) { + String name = source.getReferencedColumnName().getText(); + return toIdentifier(name, source.getBuildingContext()); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/PolicyPapApplication.java b/main/src/main/java/org/onap/policy/pap/main/PolicyPapApplication.java index 4a13c74d..ede40126 100644 --- a/main/src/main/java/org/onap/policy/pap/main/PolicyPapApplication.java +++ b/main/src/main/java/org/onap/policy/pap/main/PolicyPapApplication.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2021 Bell Canada. All rights reserved. + * Copyright (C) 2021-2022 Bell Canada. 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. @@ -25,10 +25,14 @@ import com.google.gson.GsonBuilder; import org.onap.policy.common.gson.GsonMessageBodyHandler; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.context.annotation.Bean; @SpringBootApplication(exclude = {JacksonAutoConfiguration.class}) +@EntityScan( + basePackages = {"org.onap.policy.models.pap.persistence.concepts", + "org.onap.policy.models.pdp.persistence.concepts", "org.onap.policy.models.tosca.simple.concepts"}) public class PolicyPapApplication { public static void main(String[] args) { diff --git a/main/src/main/java/org/onap/policy/pap/main/repository/PdpGroupRepository.java b/main/src/main/java/org/onap/policy/pap/main/repository/PdpGroupRepository.java new file mode 100644 index 00000000..62cac117 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/repository/PdpGroupRepository.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.repository; + +import java.util.List; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.pdp.persistence.concepts.JpaPdpGroup; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PdpGroupRepository extends JpaRepository<JpaPdpGroup, PfConceptKey> { + + List<JpaPdpGroup> findByKeyName(String pdpGroup); + + List<JpaPdpGroup> findByPdpGroupState(PdpState pdpState); + + List<JpaPdpGroup> findByKeyNameAndPdpGroupState(String pdpGroup, PdpState pdpState); +} diff --git a/main/src/main/java/org/onap/policy/pap/main/repository/PdpRepository.java b/main/src/main/java/org/onap/policy/pap/main/repository/PdpRepository.java new file mode 100644 index 00000000..9b8bda47 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/repository/PdpRepository.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.repository; + +import org.onap.policy.models.base.PfReferenceKey; +import org.onap.policy.models.pdp.persistence.concepts.JpaPdp; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PdpRepository extends JpaRepository<JpaPdp, PfReferenceKey> { + +} diff --git a/main/src/main/java/org/onap/policy/pap/main/repository/PdpStatisticsRepository.java b/main/src/main/java/org/onap/policy/pap/main/repository/PdpStatisticsRepository.java new file mode 100644 index 00000000..c93fea60 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/repository/PdpStatisticsRepository.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.repository; + +import java.util.Date; +import java.util.List; +import org.onap.policy.models.base.PfGeneratedIdKey; +import org.onap.policy.models.pdp.persistence.concepts.JpaPdpStatistics; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PdpStatisticsRepository extends JpaRepository<JpaPdpStatistics, PfGeneratedIdKey> { + + List<JpaPdpStatistics> findByTimeStampBetween(Date startTime, Date endTime, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByTimeStampGreaterThanEqual(Date startTime, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByTimeStampLessThanEqual(Date endTime, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupName(String pdpGroup, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndTimeStampBetween(String pdpGroup, Date startTime, Date endTime, + Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndTimeStampGreaterThanEqual(String pdpGroup, Date startTime, + Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndTimeStampLessThanEqual(String pdpGroup, Date endTime, + Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndPdpSubGroupName(String pdpGroup, String pdpSubGroup, + Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndPdpSubGroupNameAndTimeStampBetween(String pdpGroup, String pdpSubGroup, + Date startTime, Date endTime, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndPdpSubGroupNameAndTimeStampGreaterThanEqual(String pdpGroup, + String pdpSubGroup, Date startTime, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndPdpSubGroupNameAndTimeStampLessThanEqual(String pdpGroup, + String pdpSubGroup, Date endTime, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndPdpSubGroupNameAndKeyName(String pdpGroup, String pdpSubGroup, + String pdp, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndPdpSubGroupNameAndKeyNameAndTimeStampGreaterThanEqual(String pdpGroup, + String pdpSubGroup, String pdp, Date startTime, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndPdpSubGroupNameAndKeyNameAndTimeStampLessThanEqual(String pdpGroup, + String pdpSubGroup, String pdp, Date endTime, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByPdpGroupNameAndPdpSubGroupNameAndKeyNameAndTimeStampBetween(String pdpGroup, + String pdpSubGroup, String pdp, Date startTime, Date endTime, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByKeyName(String pdp, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByKeyNameAndTimeStampGreaterThanEqual(String pdp, Date startTime, + Pageable topRecordsSize); + + List<JpaPdpStatistics> findByKeyNameAndTimeStampLessThanEqual(String pdp, Date startTime, Pageable topRecordsSize); + + List<JpaPdpStatistics> findByKeyNameAndTimeStampBetween(String pdp, Date startTime, Date endTime, + Pageable topRecordsSize); + +} diff --git a/main/src/main/java/org/onap/policy/pap/main/repository/PdpSubGroupRepository.java b/main/src/main/java/org/onap/policy/pap/main/repository/PdpSubGroupRepository.java new file mode 100644 index 00000000..a3bc6090 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/repository/PdpSubGroupRepository.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.repository; + +import org.onap.policy.models.base.PfReferenceKey; +import org.onap.policy.models.pdp.persistence.concepts.JpaPdpSubGroup; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PdpSubGroupRepository extends JpaRepository<JpaPdpSubGroup, PfReferenceKey> { + +} diff --git a/main/src/main/java/org/onap/policy/pap/main/repository/PolicyAuditRepository.java b/main/src/main/java/org/onap/policy/pap/main/repository/PolicyAuditRepository.java new file mode 100644 index 00000000..f140fc6b --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/repository/PolicyAuditRepository.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.repository; + +import java.util.Date; +import java.util.List; +import org.onap.policy.models.base.PfGeneratedIdKey; +import org.onap.policy.models.pap.persistence.concepts.JpaPolicyAudit; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PolicyAuditRepository extends JpaRepository<JpaPolicyAudit, PfGeneratedIdKey> { + + List<JpaPolicyAudit> findByTimeStampBetween(Date startTime, Date endTime, Pageable topRecordsSize); + + List<JpaPolicyAudit> findByTimeStampGreaterThanEqual(Date startTime, Pageable topRecordsSize); + + List<JpaPolicyAudit> findByTimeStampLessThanEqual(Date endTime, Pageable topRecordsSize); + + List<JpaPolicyAudit> findByPdpGroup(String pdpGroup, Pageable topRecordsSize); + + List<JpaPolicyAudit> findByPdpGroupAndTimeStampGreaterThanEqual(String pdpGroup, Date startTime, + Pageable topRecordsSize); + + List<JpaPolicyAudit> findByPdpGroupAndTimeStampLessThanEqual(String pdpGroup, Date endTime, + Pageable topRecordsSize); + + List<JpaPolicyAudit> findByPdpGroupAndTimeStampBetween(String pdpGroup, Date startTime, Date endTime, + Pageable topRecordsSize); + + List<JpaPolicyAudit> findByPdpGroupAndKeyNameAndKeyVersion(String pdpGroup, String policyName, String policyVersion, + Pageable topRecordsSize); + + List<JpaPolicyAudit> findByPdpGroupAndKeyNameAndKeyVersionAndTimeStampGreaterThanEqual(String pdpGroup, + String policyName, String policyVersion, Date startTime, Pageable topRecordsSize); + + List<JpaPolicyAudit> findByPdpGroupAndKeyNameAndKeyVersionAndTimeStampLessThanEqual(String pdpGroup, + String policyName, String policyVersion, Date endTime, Pageable topRecordsSize); + + List<JpaPolicyAudit> findByPdpGroupAndKeyNameAndKeyVersionAndTimeStampBetween(String pdpGroup, String policyName, + String policyVersion, Date startTime, Date endTime, Pageable topRecordsSize); + + List<JpaPolicyAudit> findByKeyNameAndKeyVersion(String policyName, String policyVersion, Pageable topRecordsSize); + + List<JpaPolicyAudit> findByKeyNameAndKeyVersionAndTimeStampGreaterThanEqual(String policyName, String policyVersion, + Date startTime, Pageable topRecordsSize); + + List<JpaPolicyAudit> findByKeyNameAndKeyVersionAndTimeStampLessThanEqual(String policyName, String policyVersion, + Date endTime, Pageable topRecordsSize); + + List<JpaPolicyAudit> findByKeyNameAndKeyVersionAndTimeStampBetween(String policyName, String policyVersion, + Date startTime, Date endTime, Pageable topRecordsSize); +} diff --git a/main/src/main/java/org/onap/policy/pap/main/repository/PolicyStatusRepository.java b/main/src/main/java/org/onap/policy/pap/main/repository/PolicyStatusRepository.java new file mode 100644 index 00000000..7e0e6639 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/repository/PolicyStatusRepository.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.repository; + +import java.util.List; +import org.onap.policy.models.base.PfReferenceKey; +import org.onap.policy.models.pdp.persistence.concepts.JpaPdpPolicyStatus; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface PolicyStatusRepository extends JpaRepository<JpaPdpPolicyStatus, PfReferenceKey> { + + List<JpaPdpPolicyStatus> findByPdpGroup(String pdpGroup); + + List<JpaPdpPolicyStatus> findByPdpGroupAndKeyParentKeyName(String pdpGroup, String policyName); + + List<JpaPdpPolicyStatus> findByPdpGroupAndKeyParentKeyNameAndKeyParentKeyVersion(String pdpGroup, String policyName, + String policyVersion); + + List<JpaPdpPolicyStatus> findByKeyParentKeyName(String policyName); + + List<JpaPdpPolicyStatus> findByKeyParentKeyNameAndKeyParentKeyVersion(String policyName, String policyVersion); +} diff --git a/main/src/main/java/org/onap/policy/pap/main/repository/ToscaServiceTemplateRepository.java b/main/src/main/java/org/onap/policy/pap/main/repository/ToscaServiceTemplateRepository.java new file mode 100644 index 00000000..443949d4 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/repository/ToscaServiceTemplateRepository.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.repository; + +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ToscaServiceTemplateRepository extends JpaRepository<JpaToscaServiceTemplate, PfConceptKey> { + +} diff --git a/main/src/main/java/org/onap/policy/pap/main/service/PdpGroupService.java b/main/src/main/java/org/onap/policy/pap/main/service/PdpGroupService.java new file mode 100644 index 00000000..f3b1d6f9 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/service/PdpGroupService.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.service; + +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfKey; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.base.PfReferenceKey; +import org.onap.policy.models.pdp.concepts.Pdp; +import org.onap.policy.models.pdp.concepts.PdpGroup; +import org.onap.policy.models.pdp.concepts.PdpGroupFilter; +import org.onap.policy.models.pdp.concepts.PdpGroups; +import org.onap.policy.models.pdp.concepts.PdpSubGroup; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.pdp.persistence.concepts.JpaPdp; +import org.onap.policy.models.pdp.persistence.concepts.JpaPdpGroup; +import org.onap.policy.models.pdp.persistence.concepts.JpaPdpSubGroup; +import org.onap.policy.pap.main.repository.PdpGroupRepository; +import org.onap.policy.pap.main.repository.PdpRepository; +import org.onap.policy.pap.main.repository.PdpSubGroupRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +@RequiredArgsConstructor +public class PdpGroupService { + + private final PdpGroupRepository pdpGroupRepository; + private final PdpSubGroupRepository pdpSubGroupRepository; + private final PdpRepository pdpRepository; + + /** + * Get all PDP groups. + * + * @return the PDP groups found + */ + public List<PdpGroup> getPdpGroups() { + return asPdpGroups(pdpGroupRepository.findAll()); + } + + /** + * Get PDP groups by name. + * + * @param pdpGroup the name of group + * @return the PDP groups found + */ + public List<PdpGroup> getPdpGroupByName(@NonNull String pdpGroup) { + return asPdpGroups(pdpGroupRepository.findByKeyName(pdpGroup)); + } + + /** + * Get PDP groups by state. + * + * @param pdpState the state of pdpGroup + * @return the PDP groups found + */ + public List<PdpGroup> getPdpGroupByState(@NonNull PdpState pdpState) { + return asPdpGroups(pdpGroupRepository.findByPdpGroupState(pdpState)); + } + + /** + * Get PDP groups by name and state. + * + * @param pdpGroup the name of group + * @param state the state of pdpGroup + * @return the PDP groups found + */ + public List<PdpGroup> getPdpGroupByNameAndState(@NonNull String pdpGroup, @NonNull PdpState state) { + return asPdpGroups(pdpGroupRepository.findByKeyNameAndPdpGroupState(pdpGroup, state)); + } + + /** + * Get filtered PDP groups. + * + * @param filter the filter for the PDP groups to get + * @return the PDP groups found + */ + public List<PdpGroup> getFilteredPdpGroups(@NonNull final PdpGroupFilter filter) { + return filter.filter(asPdpGroups(pdpGroupRepository.findAll())); + } + + /** + * Creates PDP groups. + * + * @param pdpGroups the PDP groups to create + * @return the PDP groups created + */ + public PdpGroups savePdpGroups(@NonNull final List<PdpGroup> pdpGroups) { + + // Return the created PDP groups + List<PdpGroup> returnPdpGroupList = new ArrayList<>(); + + for (PdpGroup pdpGroup : pdpGroups) { + var jpaPdpGroup = new JpaPdpGroup(); + try { + jpaPdpGroup.fromAuthorative(pdpGroup); + + BeanValidationResult validationResult = jpaPdpGroup.validate("PDP group"); + if (!validationResult.isValid()) { + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult()); + } + + returnPdpGroupList.add(pdpGroupRepository.save(jpaPdpGroup).toAuthorative()); + } catch (Exception exc) { + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, + "Failed saving PdpGroup. " + exc.getMessage(), exc); + } + } + PdpGroups returnPdpGroups = new PdpGroups(); + returnPdpGroups.setGroups(returnPdpGroupList); + return returnPdpGroups; + } + + /** + * Delete a PDP group. + * + * @param pdpGroup the name of the pdpGroup to delete + */ + public void deletePdpGroup(String pdpGroup) { + try { + pdpGroupRepository.deleteById(new PfConceptKey(pdpGroup, "0.0.0")); + } catch (Exception exc) { + String errorMessage = "delete of PDP group \"" + pdpGroup + "\" failed, PDP group does not exist"; + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage, exc); + } + } + + /** + * Convert JPA PDP group list to an authorative PDP group list. + * + * @param jpaPdpGroupList the list to convert + * @return the authorative list + */ + private List<PdpGroup> asPdpGroups(List<JpaPdpGroup> jpaPdpGroupList) { + List<PdpGroup> pdpGroupList = new ArrayList<>(jpaPdpGroupList.size()); + for (JpaPdpGroup jpaPdpGroup : jpaPdpGroupList) { + pdpGroupList.add(jpaPdpGroup.toAuthorative()); + } + return pdpGroupList; + } + + /** + * Update a PDP. + * + * @param pdpGroupName the name of the PDP group of the PDP subgroup + * @param pdpSubGroup the PDP subgroup to be updated + * @param pdp the PDP to be updated + */ + public void updatePdp(@NonNull final String pdpGroupName, @NonNull final String pdpSubGroup, + @NonNull final Pdp pdp) { + + final var pdpKey = new PfReferenceKey(pdpGroupName, PfKey.NULL_KEY_VERSION, pdpSubGroup, pdp.getInstanceId()); + final var jpaPdp = new JpaPdp(pdpKey); + jpaPdp.fromAuthorative(pdp); + + BeanValidationResult validationResult = jpaPdp.validate("PDP"); + if (!validationResult.isValid()) { + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult()); + } + + pdpRepository.save(jpaPdp); + } + + /** + * Update a PDP subgroup. + * + * @param pdpGroupName the name of the PDP group of the PDP subgroup + * @param pdpSubGroup the PDP subgroup to be updated + */ + public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final PdpSubGroup pdpSubGroup) { + + final var subGroupKey = new PfReferenceKey(pdpGroupName, PfKey.NULL_KEY_VERSION, pdpSubGroup.getPdpType()); + final var jpaPdpSubgroup = new JpaPdpSubGroup(subGroupKey); + jpaPdpSubgroup.fromAuthorative(pdpSubGroup); + + BeanValidationResult validationResult = jpaPdpSubgroup.validate("PDP sub group"); + if (!validationResult.isValid()) { + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult()); + } + pdpSubGroupRepository.save(jpaPdpSubgroup); + } + +} diff --git a/main/src/main/java/org/onap/policy/pap/main/service/PdpStatisticsService.java b/main/src/main/java/org/onap/policy/pap/main/service/PdpStatisticsService.java new file mode 100644 index 00000000..79112cd2 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/service/PdpStatisticsService.java @@ -0,0 +1,250 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.service; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.ws.rs.core.Response; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.models.base.PfGeneratedIdKey; +import org.onap.policy.models.base.PfKey; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.pdp.concepts.PdpStatistics; +import org.onap.policy.models.pdp.persistence.concepts.JpaPdpStatistics; +import org.onap.policy.pap.main.repository.PdpStatisticsRepository; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +@RequiredArgsConstructor +public class PdpStatisticsService { + + private static final String TIMESTAMP = "timeStamp"; + private static final int DEFAULT_RECORD_COUNT = 10; + private static final int MAX_RECORD_COUNT = 100; + + private final PdpStatisticsRepository pdpStatisticsRepository; + + /** + * Creates PDP statistics. + * + * @param pdpStatisticsList a specification of the PDP statistics to create + * @return the PDP statistics created + */ + public List<PdpStatistics> createPdpStatistics(@NonNull final List<PdpStatistics> pdpStatisticsList) { + for (PdpStatistics pdpStatistics : pdpStatisticsList) { + var jpaPdpStatistics = new JpaPdpStatistics(); + jpaPdpStatistics.fromAuthorative(pdpStatistics); + BeanValidationResult validationResult = jpaPdpStatistics.validate("pdp statistics"); + if (!validationResult.isValid()) { + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult()); + } + pdpStatisticsRepository.save(jpaPdpStatistics); + pdpStatistics.setGeneratedId(jpaPdpStatistics.getKey().getGeneratedId()); + } + + // Return the created PDP statistics + List<PdpStatistics> pdpStatistics = new ArrayList<>(pdpStatisticsList.size()); + + for (PdpStatistics pdpStatisticsItem : pdpStatisticsList) { + var jpaPdpStatistics = + pdpStatisticsRepository.getById(new PfGeneratedIdKey(pdpStatisticsItem.getPdpInstanceId(), + PfKey.NULL_KEY_VERSION, pdpStatisticsItem.getGeneratedId())); + pdpStatistics.add(jpaPdpStatistics.toAuthorative()); + } + return pdpStatistics; + } + + /** + * Fetch PdpStatistics from db. + * + * @param pdpGroup the name of the group + * @param pdpSubGroup the name of the subgroup + * @param pdp the pdp instance id + * @param recordCount the number of records to return + * @param startTime start time of the records to be returned + * @param endTime end time of the records to be returned + * @return pdpStatistics grouped by pdpGroup + */ + public Map<String, Map<String, List<PdpStatistics>>> fetchDatabaseStatistics(String pdpGroup, String pdpSubGroup, + String pdp, int recordCount, Instant startTime, Instant endTime) { + + Pageable recordSize = getRecordSize(recordCount); + if (startTime != null && endTime != null) { + return generatePdpStatistics(asPdpStatisticsList(pdpStatisticsRepository + .findByPdpGroupNameAndPdpSubGroupNameAndKeyNameAndTimeStampBetween(pdpGroup, pdpSubGroup, pdp, + convertInstantToDate(startTime), convertInstantToDate(endTime), recordSize))); + } else if (startTime == null && endTime == null) { + return generatePdpStatistics( + asPdpStatisticsList(pdpStatisticsRepository.findByPdpGroupNameAndPdpSubGroupNameAndKeyName(pdpGroup, + pdpSubGroup, pdp, recordSize))); + } else if (startTime != null) { + return generatePdpStatistics(asPdpStatisticsList( + pdpStatisticsRepository.findByPdpGroupNameAndPdpSubGroupNameAndKeyNameAndTimeStampGreaterThanEqual( + pdpGroup, pdpSubGroup, pdp, convertInstantToDate(startTime), recordSize))); + } else { + return generatePdpStatistics(asPdpStatisticsList( + pdpStatisticsRepository.findByPdpGroupNameAndPdpSubGroupNameAndKeyNameAndTimeStampLessThanEqual( + pdpGroup, pdpSubGroup, pdp, convertInstantToDate(endTime), recordSize))); + } + } + + /** + * Fetch PdpStatistics from db. + * + * @param pdpGroup the name of the group + * @param pdpSubGroup the name of the subgroup + * @param recordCount the number of records to return + * @param startTime start time of the records to be returned + * @param endTime end time of the records to be returned + * @return pdpStatistics grouped by pdpGroup + */ + public Map<String, Map<String, List<PdpStatistics>>> fetchDatabaseStatistics(String pdpGroup, String pdpSubGroup, + int recordCount, Instant startTime, Instant endTime) { + + Pageable recordSize = getRecordSize(recordCount); + if (startTime != null && endTime != null) { + return generatePdpStatistics(asPdpStatisticsList( + pdpStatisticsRepository.findByPdpGroupNameAndPdpSubGroupNameAndTimeStampBetween(pdpGroup, pdpSubGroup, + convertInstantToDate(startTime), convertInstantToDate(endTime), recordSize))); + } else if (startTime == null && endTime == null) { + return generatePdpStatistics(asPdpStatisticsList(pdpStatisticsRepository + .findByPdpGroupNameAndPdpSubGroupName(pdpGroup, pdpSubGroup, recordSize))); + } else if (startTime != null) { + return generatePdpStatistics(asPdpStatisticsList( + pdpStatisticsRepository.findByPdpGroupNameAndPdpSubGroupNameAndTimeStampGreaterThanEqual(pdpGroup, + pdpSubGroup, convertInstantToDate(startTime), recordSize))); + } else { + return generatePdpStatistics(asPdpStatisticsList( + pdpStatisticsRepository.findByPdpGroupNameAndPdpSubGroupNameAndTimeStampLessThanEqual(pdpGroup, + pdpSubGroup, convertInstantToDate(endTime), recordSize))); + } + } + + /** + * Fetch PdpStatistics from db. + * + * @param pdpGroup the name of the group + * @param recordCount the number of records to return + * @param startTime start time of the records to be returned + * @param endTime end time of the records to be returned + * @return pdpStatistics grouped by pdpGroup + */ + public Map<String, Map<String, List<PdpStatistics>>> fetchDatabaseStatistics(String pdpGroup, int recordCount, + Instant startTime, Instant endTime) { + + Pageable recordSize = getRecordSize(recordCount); + if (startTime != null && endTime != null) { + return generatePdpStatistics( + asPdpStatisticsList(pdpStatisticsRepository.findByPdpGroupNameAndTimeStampBetween(pdpGroup, + convertInstantToDate(startTime), convertInstantToDate(endTime), recordSize))); + } else if (startTime == null && endTime == null) { + return generatePdpStatistics( + asPdpStatisticsList(pdpStatisticsRepository.findByPdpGroupName(pdpGroup, recordSize))); + } else if (startTime != null) { + return generatePdpStatistics( + asPdpStatisticsList(pdpStatisticsRepository.findByPdpGroupNameAndTimeStampGreaterThanEqual(pdpGroup, + convertInstantToDate(startTime), recordSize))); + } else { + return generatePdpStatistics( + asPdpStatisticsList(pdpStatisticsRepository.findByPdpGroupNameAndTimeStampLessThanEqual(pdpGroup, + convertInstantToDate(endTime), recordSize))); + } + } + + /** + * Fetch PdpStatistics from db. + * + * @param recordCount the number of records to return + * @param startTime start time of the records to be returned + * @param endTime end time of the records to be returned + * @return pdpStatistics grouped by pdpGroup + */ + public Map<String, Map<String, List<PdpStatistics>>> fetchDatabaseStatistics(int recordCount, Instant startTime, + Instant endTime) { + + Pageable recordSize = getRecordSize(recordCount); + if (startTime != null && endTime != null) { + return generatePdpStatistics(asPdpStatisticsList(pdpStatisticsRepository.findByTimeStampBetween( + convertInstantToDate(startTime), convertInstantToDate(endTime), recordSize))); + } else if (startTime == null && endTime == null) { + return generatePdpStatistics( + asPdpStatisticsList(pdpStatisticsRepository.findAll(recordSize).toList())); + } else if (startTime != null) { + return generatePdpStatistics(asPdpStatisticsList(pdpStatisticsRepository + .findByTimeStampGreaterThanEqual(convertInstantToDate(startTime), recordSize))); + } else { + return generatePdpStatistics(asPdpStatisticsList(pdpStatisticsRepository + .findByTimeStampLessThanEqual(convertInstantToDate(endTime), recordSize))); + } + } + + private Pageable getRecordSize(int recordCount) { + if (recordCount < 1) { + recordCount = DEFAULT_RECORD_COUNT; + } else if (recordCount > MAX_RECORD_COUNT) { + recordCount = MAX_RECORD_COUNT; + } + return PageRequest.of(0, recordCount, Sort.by(TIMESTAMP).descending()); + } + + /** + * generate the statistics of pap component by group/subgroup. + * + */ + private Map<String, Map<String, List<PdpStatistics>>> generatePdpStatistics(List<PdpStatistics> pdpStatisticsList) { + Map<String, Map<String, List<PdpStatistics>>> groupMap = new HashMap<>(); + if (pdpStatisticsList != null) { + pdpStatisticsList.stream().forEach(s -> { + String curGroup = s.getPdpGroupName(); + String curSubGroup = s.getPdpSubGroupName(); + groupMap.computeIfAbsent(curGroup, curGroupMap -> new HashMap<>()) + .computeIfAbsent(curSubGroup, curSubGroupList -> new ArrayList<>()).add(s); + }); + } + return groupMap; + } + + /** + * Convert JPA PDP statistics list to an PDP statistics list. + * + * @param jpaPdpStatisticsList the list to convert + * @return the PDP statistics list + */ + private List<PdpStatistics> asPdpStatisticsList(List<JpaPdpStatistics> jpaPdpStatisticsList) { + return jpaPdpStatisticsList.stream().map(JpaPdpStatistics::toAuthorative).collect(Collectors.toList()); + } + + private Date convertInstantToDate(Instant instant) { + return (instant == null ? null : Date.from(instant)); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/service/PolicyAuditService.java b/main/src/main/java/org/onap/policy/pap/main/service/PolicyAuditService.java new file mode 100644 index 00000000..d2926fa1 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/service/PolicyAuditService.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.service; + +import java.time.Instant; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; +import javax.ws.rs.core.Response; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.pap.concepts.PolicyAudit; +import org.onap.policy.models.pap.persistence.concepts.JpaPolicyAudit; +import org.onap.policy.pap.main.repository.PolicyAuditRepository; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +@RequiredArgsConstructor +public class PolicyAuditService { + + private static final Integer DEFAULT_MAX_RECORDS = 100; + private static final Integer DEFAULT_MIN_RECORDS = 10; + + private final PolicyAuditRepository policyAuditRepository; + + /** + * Create audit records. + * + * @param audits list of policy audit + */ + public void createAuditRecords(@NonNull final List<PolicyAudit> audits) { + List<JpaPolicyAudit> jpaAudits = audits.stream().map(JpaPolicyAudit::new).collect(Collectors.toList()); + + var result = new BeanValidationResult("createAuditRecords", jpaAudits); + + var count = 0; + for (JpaPolicyAudit jpaAudit : jpaAudits) { + result.addResult(jpaAudit.validate(String.valueOf(count++))); + } + + if (!result.isValid()) { + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, result.getResult()); + } + + policyAuditRepository.saveAll(jpaAudits); + } + + /** + * Collect the audit records. + * + * @param recordCount the number of records to return + * @param startTime start time of the records to be returned + * @param endTime end time of the records to be returned + * @return list of {@link PolicyAudit} records found + */ + public List<PolicyAudit> getAuditRecords(int recordCount, Instant startTime, Instant endTime) { + Pageable recordSize = getRecordSize(recordCount); + if (startTime != null && endTime != null) { + return asPolicyAuditList( + policyAuditRepository.findByTimeStampBetween(Date.from(startTime), Date.from(endTime), recordSize)); + } else if (startTime == null && endTime == null) { + return asPolicyAuditList(policyAuditRepository.findAll(recordSize).toList()); + } else if (startTime != null) { + return asPolicyAuditList( + policyAuditRepository.findByTimeStampGreaterThanEqual(Date.from(startTime), recordSize)); + } else { + return asPolicyAuditList( + policyAuditRepository.findByTimeStampLessThanEqual(Date.from(endTime), recordSize)); + } + } + + /** + * Collect the audit records. + * + * @param pdpGroup the name of the group + * @param recordCount the number of records to return + * @param startTime start time of the records to be returned + * @param endTime end time of the records to be returned + * @return list of {@link PolicyAudit} records found + */ + public List<PolicyAudit> getAuditRecords(String pdpGroup, int recordCount, Instant startTime, Instant endTime) { + Pageable recordSize = getRecordSize(recordCount); + if (startTime != null && endTime != null) { + return asPolicyAuditList(policyAuditRepository.findByPdpGroupAndTimeStampBetween(pdpGroup, + Date.from(startTime), Date.from(endTime), recordSize)); + } else if (startTime == null && endTime == null) { + return asPolicyAuditList(policyAuditRepository.findByPdpGroup(pdpGroup, recordSize)); + } else if (startTime != null) { + return asPolicyAuditList(policyAuditRepository.findByPdpGroupAndTimeStampGreaterThanEqual(pdpGroup, + Date.from(startTime), recordSize)); + } else { + return asPolicyAuditList(policyAuditRepository.findByPdpGroupAndTimeStampLessThanEqual(pdpGroup, + Date.from(endTime), recordSize)); + } + } + + /** + * Collect the audit records. + * + * @param pdpGroup the name of the group + * @param policyName the name of the policy + * @param policyVersion the version of the policy + * @param recordCount the number of records to return + * @param startTime start time of the records to be returned + * @param endTime end time of the records to be returned + * @return list of {@link PolicyAudit} records found + */ + public List<PolicyAudit> getAuditRecords(String pdpGroup, String policyName, String policyVersion, int recordCount, + Instant startTime, Instant endTime) { + Pageable recordSize = getRecordSize(recordCount); + if (startTime != null && endTime != null) { + return asPolicyAuditList(policyAuditRepository.findByPdpGroupAndKeyNameAndKeyVersionAndTimeStampBetween( + pdpGroup, policyName, policyVersion, Date.from(startTime), Date.from(endTime), recordSize)); + } else if (startTime == null && endTime == null) { + return asPolicyAuditList(policyAuditRepository.findByPdpGroupAndKeyNameAndKeyVersion(pdpGroup, policyName, + policyVersion, recordSize)); + } else if (startTime != null) { + return asPolicyAuditList( + policyAuditRepository.findByPdpGroupAndKeyNameAndKeyVersionAndTimeStampGreaterThanEqual(pdpGroup, + policyName, policyVersion, Date.from(startTime), recordSize)); + } else { + return asPolicyAuditList( + policyAuditRepository.findByPdpGroupAndKeyNameAndKeyVersionAndTimeStampLessThanEqual(pdpGroup, + policyName, policyVersion, Date.from(endTime), recordSize)); + } + } + + /** + * Collect the audit records. + * + * @param policyName the name of the policy + * @param policyVersion the version of the policy + * @param recordCount the number of records to return + * @param startTime start time of the records to be returned + * @param endTime end time of the records to be returned + * @return list of {@link PolicyAudit} records found + */ + public List<PolicyAudit> getAuditRecords(String policyName, String policyVersion, int recordCount, + Instant startTime, Instant endTime) { + Pageable recordSize = getRecordSize(recordCount); + if (startTime != null && endTime != null) { + return asPolicyAuditList(policyAuditRepository.findByKeyNameAndKeyVersionAndTimeStampBetween(policyName, + policyVersion, Date.from(startTime), Date.from(endTime), recordSize)); + } else if (startTime == null && endTime == null) { + return asPolicyAuditList( + policyAuditRepository.findByKeyNameAndKeyVersion(policyName, policyVersion, recordSize)); + } else if (startTime != null) { + return asPolicyAuditList(policyAuditRepository.findByKeyNameAndKeyVersionAndTimeStampGreaterThanEqual( + policyName, policyVersion, Date.from(startTime), recordSize)); + } else { + return asPolicyAuditList(policyAuditRepository.findByKeyNameAndKeyVersionAndTimeStampLessThanEqual( + policyName, policyVersion, Date.from(endTime), recordSize)); + } + } + + private Pageable getRecordSize(int recordCount) { + if (recordCount < 1) { + recordCount = DEFAULT_MIN_RECORDS; + } else if (recordCount > DEFAULT_MAX_RECORDS) { + recordCount = DEFAULT_MAX_RECORDS; + } + return PageRequest.of(0, recordCount, Sort.by("timeStamp").descending()); + } + + private List<PolicyAudit> asPolicyAuditList(List<JpaPolicyAudit> jpaPolicyAuditList) { + return jpaPolicyAuditList.stream().map(JpaPolicyAudit::toAuthorative).collect(Collectors.toList()); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/service/PolicyStatusService.java b/main/src/main/java/org/onap/policy/pap/main/service/PolicyStatusService.java new file mode 100644 index 00000000..09870314 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/service/PolicyStatusService.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.service; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import javax.ws.rs.core.Response; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; +import org.onap.policy.models.pdp.persistence.concepts.JpaPdpPolicyStatus; +import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; +import org.onap.policy.pap.main.repository.PolicyStatusRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional +@RequiredArgsConstructor +public class PolicyStatusService { + + private final PolicyStatusRepository policyStatusRepository; + + /** + * Gets all status for policies in a group. + * + * @param pdpGroup the group's name + * @return the policy status list found + */ + public List<PdpPolicyStatus> getGroupPolicyStatus(@NonNull String pdpGroup) { + return asPolicyStatusList(policyStatusRepository.findByPdpGroup(pdpGroup)); + } + + /** + * Gets all status for policies. + * + * @return the policy status list found + */ + public List<PdpPolicyStatus> getAllPolicyStatus() { + return asPolicyStatusList(policyStatusRepository.findAll()); + } + + /** + * Gets all status for a policy. + * + * @param policy the policy + * @return the policy status list found + */ + public List<PdpPolicyStatus> getAllPolicyStatus(@NonNull ToscaConceptIdentifierOptVersion policy) { + + if (policy.getVersion() != null) { + return asPolicyStatusList(policyStatusRepository + .findByKeyParentKeyNameAndKeyParentKeyVersion(policy.getName(), policy.getVersion())); + + } else { + return asPolicyStatusList(policyStatusRepository.findByKeyParentKeyName(policy.getName())); + } + } + + /** + * Gets all status for a policy in a group. + * + * @param pdpGroup the group's name + * @param policy the policy + * @return the policy status list found + */ + public List<PdpPolicyStatus> getAllPolicyStatus(@NonNull String pdpGroup, + @NonNull ToscaConceptIdentifierOptVersion policy) { + if (policy.getVersion() != null) { + return asPolicyStatusList(policyStatusRepository.findByPdpGroupAndKeyParentKeyNameAndKeyParentKeyVersion( + pdpGroup, policy.getName(), policy.getVersion())); + } else { + return asPolicyStatusList( + policyStatusRepository.findByPdpGroupAndKeyParentKeyName(pdpGroup, policy.getName())); + } + } + + /** + * Creates, updates, and deletes collections of policy status. + * + * @param createObjs the objects to create + * @param updateObjs the objects to update + * @param deleteObjs the objects to delete + */ + public void cudPolicyStatus(Collection<PdpPolicyStatus> createObjs, Collection<PdpPolicyStatus> updateObjs, + Collection<PdpPolicyStatus> deleteObjs) { + try { + policyStatusRepository.deleteAll(fromAuthorativeStatus(deleteObjs, "deletePdpPolicyStatusList")); + policyStatusRepository.saveAll(fromAuthorativeStatus(createObjs, "createPdpPolicyStatusList")); + policyStatusRepository.saveAll(fromAuthorativeStatus(updateObjs, "updatePdpPolicyStatusList")); + } catch (Exception exc) { + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, + "Policy status operation failed." + exc.getMessage(), exc); + } + } + + /** + * Converts a collection of authorative policy status to a collection of JPA policy + * status. Validates the resulting list. + * + * @param objs authorative policy status to convert + * @param fieldName name of the field containing the collection + * @return a list of JPA policy status + */ + private List<JpaPdpPolicyStatus> fromAuthorativeStatus(Collection<PdpPolicyStatus> objs, String fieldName) { + if (objs == null) { + return Collections.emptyList(); + } + + List<JpaPdpPolicyStatus> jpas = objs.stream().map(JpaPdpPolicyStatus::new).collect(Collectors.toList()); + + // validate the objects + var result = new BeanValidationResult(fieldName, jpas); + + var count = 0; + for (JpaPdpPolicyStatus jpa : jpas) { + result.addResult(jpa.validate(String.valueOf(count++))); + } + + if (!result.isValid()) { + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, result.getResult()); + } + + return jpas; + } + + private List<PdpPolicyStatus> asPolicyStatusList(List<JpaPdpPolicyStatus> jpaPdpPolicyStatusList) { + return jpaPdpPolicyStatusList.stream().map(JpaPdpPolicyStatus::toAuthorative).collect(Collectors.toList()); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/service/ToscaServiceTemplateService.java b/main/src/main/java/org/onap/policy/pap/main/service/ToscaServiceTemplateService.java new file mode 100644 index 00000000..cebee1b5 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/service/ToscaServiceTemplateService.java @@ -0,0 +1,175 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2022 Bell Canada. 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.pap.main.service; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import javax.ws.rs.core.Response; +import lombok.RequiredArgsConstructor; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider; +import org.onap.policy.models.tosca.utils.ToscaUtils; +import org.onap.policy.pap.main.repository.ToscaServiceTemplateRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@Transactional(readOnly = true) +@RequiredArgsConstructor +public class ToscaServiceTemplateService { + + private static final Logger LOGGER = LoggerFactory.getLogger(ToscaServiceTemplateService.class); + + private final ToscaServiceTemplateRepository serviceTemplateRepository; + + /** + * Get policies. + * + * @param name the name of the policy to get, null to get all policies + * @param version the version of the policy to get, null to get all versions of a policy + * @return the policies found + * @throws PfModelException on errors getting policies + */ + public List<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException { + + LOGGER.debug("->getPolicyList: name={}, version={}", name, version); + + List<ToscaPolicy> policyList; + + try { + List<Map<String, ToscaPolicy>> policies = getToscaServiceTemplate(name, version, "policy").toAuthorative() + .getToscaTopologyTemplate().getPolicies(); + policyList = policies.stream().flatMap(policy -> policy.values().stream()).collect(Collectors.toList()); + } catch (PfModelRuntimeException pfme) { + return handlePfModelRuntimeException(pfme); + } catch (Exception exc) { + String errorMsg = "Failed to fetch policy with name " + name + " and version " + version + "."; + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMsg, exc); + } + + LOGGER.debug("<-getPolicyList: name={}, version={}, policyList={}", name, version, policyList); + return policyList; + } + + /** + * Get policy types. + * + * @param name the name of the policy type to get, set to null to get all policy types + * @param version the version of the policy type to get, set to null to get all versions + * @return the policy types found + * @throws PfModelException on errors getting policy types + */ + public List<ToscaPolicyType> getPolicyTypeList(final String name, final String version) throws PfModelException { + + LOGGER.debug("->getPolicyTypeList: name={}, version={}", name, version); + + List<ToscaPolicyType> policyTypeList; + + try { + policyTypeList = new ArrayList<>( + getToscaServiceTemplate(name, version, "policyType").toAuthorative().getPolicyTypes().values()); + } catch (PfModelRuntimeException pfme) { + return handlePfModelRuntimeException(pfme); + } catch (Exception exc) { + String errorMsg = "Failed to fetch policy type with name " + name + " and version " + version + "."; + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMsg, exc); + } + + LOGGER.debug("<-getPolicyTypeList: name={}, version={}, policyTypeList={}", name, version, policyTypeList); + return policyTypeList; + } + + private JpaToscaServiceTemplate getToscaServiceTemplate(final String name, final String version, final String type) + throws PfModelException { + + Optional<JpaToscaServiceTemplate> serviceTemplate = serviceTemplateRepository + .findById(new PfConceptKey(JpaToscaServiceTemplate.DEFAULT_NAME, JpaToscaServiceTemplate.DEFAULT_VERSION)); + if (serviceTemplate.isEmpty()) { + throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "service template not found in database"); + } + + LOGGER.debug("<-getServiceTemplate: serviceTemplate={}", serviceTemplate.get()); + JpaToscaServiceTemplate dbServiceTemplate = serviceTemplate.get(); + + JpaToscaServiceTemplate returnServiceTemplate; + if (type.equals("policy")) { + returnServiceTemplate = getToscaPolicies(name, version, dbServiceTemplate); + } else { + returnServiceTemplate = getToscaPolicyTypes(name, version, dbServiceTemplate); + } + return returnServiceTemplate; + } + + private JpaToscaServiceTemplate getToscaPolicies(final String name, final String version, + JpaToscaServiceTemplate dbServiceTemplate) throws PfModelException { + if (!ToscaUtils.doPoliciesExist(dbServiceTemplate)) { + throw new PfModelRuntimeException(Response.Status.NOT_FOUND, + "policies for " + name + ":" + version + " do not exist"); + } + + JpaToscaServiceTemplate returnServiceTemplate = + new SimpleToscaProvider().getCascadedPolicies(dbServiceTemplate, name, version); + + LOGGER.debug("<-getPolicies: name={}, version={}, serviceTemplate={}", name, version, returnServiceTemplate); + return returnServiceTemplate; + } + + private JpaToscaServiceTemplate getToscaPolicyTypes(final String name, final String version, + JpaToscaServiceTemplate dbServiceTemplate) throws PfModelException { + if (!ToscaUtils.doPolicyTypesExist(dbServiceTemplate)) { + throw new PfModelRuntimeException(Response.Status.NOT_FOUND, + "policy types for " + name + ":" + version + " do not exist"); + } + + JpaToscaServiceTemplate returnServiceTemplate = + new SimpleToscaProvider().getCascadedPolicyTypes(dbServiceTemplate, name, version); + + LOGGER.debug("<-getPolicyTypes: name={}, version={}, serviceTemplate={}", name, version, returnServiceTemplate); + return returnServiceTemplate; + } + + /** + * Handle a PfModelRuntimeException on a list call. + * + * @param pfme the model exception + * @return an empty list on 404 + */ + private <T extends ToscaEntity> List<T> handlePfModelRuntimeException(final PfModelRuntimeException pfme) { + if (Response.Status.NOT_FOUND.equals(pfme.getErrorResponse().getResponseCode())) { + LOGGER.trace("request did not find any results", pfme); + return Collections.emptyList(); + } else { + throw pfme; + } + } +} |