a30920427c6e976703b94017c3fe974dac0e8dfa
[sdc/sdc-workflow-designer.git] / workflow-designer-be / src / main / java / org / onap / sdc / workflow / services / impl / WorkflowManagerImpl.java
1 /*
2  * Copyright © 2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.sdc.workflow.services.impl;
18
19 import static org.onap.sdc.workflow.services.types.PagingConstants.DEFAULT_LIMIT;
20 import static org.onap.sdc.workflow.services.types.PagingConstants.DEFAULT_OFFSET;
21 import static org.onap.sdc.workflow.services.types.PagingConstants.MAX_LIMIT;
22
23 import java.util.Collection;
24 import java.util.Comparator;
25 import java.util.List;
26 import java.util.Set;
27 import java.util.function.Predicate;
28 import java.util.stream.Collectors;
29 import org.onap.sdc.workflow.persistence.types.Workflow;
30 import org.onap.sdc.workflow.persistence.types.WorkflowVersionState;
31 import org.onap.sdc.workflow.services.UniqueValueService;
32 import org.onap.sdc.workflow.services.WorkflowManager;
33 import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException;
34 import org.onap.sdc.workflow.services.impl.mappers.VersionStateMapper;
35 import org.onap.sdc.workflow.services.impl.mappers.WorkflowMapper;
36 import org.onap.sdc.workflow.services.types.Page;
37 import org.onap.sdc.workflow.services.types.PagingRequest;
38 import org.onap.sdc.workflow.services.types.RequestSpec;
39 import org.onap.sdc.workflow.services.types.Sort;
40 import org.onap.sdc.workflow.services.types.SortingRequest;
41 import org.openecomp.sdc.logging.api.Logger;
42 import org.openecomp.sdc.logging.api.LoggerFactory;
43 import org.openecomp.sdc.versioning.ItemManager;
44 import org.openecomp.sdc.versioning.dao.types.VersionStatus;
45 import org.openecomp.sdc.versioning.types.Item;
46 import org.openecomp.sdc.versioning.types.ItemStatus;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.beans.factory.annotation.Qualifier;
49 import org.springframework.stereotype.Service;
50
51 @Service("workflowManager")
52 public class WorkflowManagerImpl implements WorkflowManager {
53
54     public static final String WORKFLOW_TYPE = "WORKFLOW";
55     private static final String WORKFLOW_NOT_FOUND_ERROR_MSG = "Workflow with id '%s' does not exist";
56     private static final String WORKFLOW_NAME_UNIQUE_TYPE = "WORKFLOW_NAME";
57     private static final Predicate<Item> WORKFLOW_ITEM_FILTER = item -> WORKFLOW_TYPE.equals(item.getType());
58     private static final String WORKSPACES_SORT_PROPERTY = "name";
59     private static final RequestSpec WORKSPACES_DEFAULT_REQUEST_SPEC =
60             new RequestSpec(new PagingRequest(DEFAULT_OFFSET, DEFAULT_LIMIT),
61                     SortingRequest.builder().sort(new Sort(WORKSPACES_SORT_PROPERTY, true)).build());
62
63     private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowManagerImpl.class);
64
65     private final ItemManager itemManager;
66     private final UniqueValueService uniqueValueService;
67     private final WorkflowMapper workflowMapper;
68     private final VersionStateMapper versionStateMapper;
69
70     @Autowired
71     public WorkflowManagerImpl(ItemManager itemManager,
72             @Qualifier("uniqueValueService") UniqueValueService uniqueValueService, WorkflowMapper workflowMapper,
73             VersionStateMapper versionStateMapper) {
74         this.itemManager = itemManager;
75         this.uniqueValueService = uniqueValueService;
76         this.workflowMapper = workflowMapper;
77         this.versionStateMapper = versionStateMapper;
78     }
79
80     @Override
81     public Page<Workflow> list(Set<WorkflowVersionState> versionStatesFilter, RequestSpec requestSpec) {
82         requestSpec = getRequestSpec(requestSpec);
83
84         Set<VersionStatus> versionStatusesFilter =
85                 versionStatesFilter == null ? null :
86                         versionStatesFilter.stream().map(versionStateMapper::workflowVersionStateToVersionStatus)
87                                            .collect(Collectors.toSet());
88
89         Collection<Item> workflowItems = itemManager.list(getFilter(versionStatusesFilter));
90
91         List<Workflow> workflowsSlice = workflowItems.stream().map(workflowMapper::itemToWorkflow)
92                                                      .sorted(getWorkflowComparator(requestSpec.getSorting()))
93                                                      .skip(requestSpec.getPaging().getOffset())
94                                                      .limit(requestSpec.getPaging().getLimit())
95                                                      .collect(Collectors.toList());
96         return new Page<>(workflowsSlice, requestSpec.getPaging(), workflowItems.size());
97     }
98
99     @Override
100     public Workflow get(Workflow workflow) {
101         Item retrievedItem = itemManager.get(workflow.getId());
102         if (retrievedItem == null) {
103             LOGGER.error(String.format("Workflow with id %s was not found", workflow.getId()));
104             throw new EntityNotFoundException(String.format(WORKFLOW_NOT_FOUND_ERROR_MSG, workflow.getId()));
105         }
106         return this.workflowMapper.itemToWorkflow(retrievedItem);
107     }
108
109     @Override
110     public Workflow create(Workflow workflow) {
111         Item item = workflowMapper.workflowToItem(workflow);
112         item.setStatus(ItemStatus.ACTIVE);
113
114         uniqueValueService.validateUniqueValue(WORKFLOW_NAME_UNIQUE_TYPE, new String[] {workflow.getName()});
115         Item createdItem = itemManager.create(item);
116         uniqueValueService.createUniqueValue(WORKFLOW_NAME_UNIQUE_TYPE, new String[] {workflow.getName()});
117
118         return workflowMapper.itemToWorkflow(createdItem);
119     }
120
121     @Override
122     public void update(Workflow workflow) {
123         Item retrievedItem = itemManager.get(workflow.getId());
124         if (retrievedItem == null) {
125             LOGGER.error(String.format("Workflow with id %s was not found", workflow.getId()));
126             throw new EntityNotFoundException(String.format(WORKFLOW_NOT_FOUND_ERROR_MSG, workflow.getId()));
127         }
128
129         uniqueValueService.updateUniqueValue(WORKFLOW_NAME_UNIQUE_TYPE, retrievedItem.getName(), workflow.getName());
130
131         Item item = workflowMapper.workflowToItem(workflow);
132         item.setId(workflow.getId());
133         item.setStatus(retrievedItem.getStatus());
134         item.setVersionStatusCounters(retrievedItem.getVersionStatusCounters());
135         itemManager.update(item);
136     }
137
138     private static RequestSpec getRequestSpec(RequestSpec requestSpec) {
139         if (requestSpec == null) {
140             return WORKSPACES_DEFAULT_REQUEST_SPEC;
141         }
142         if (requestSpec.getPaging() == null) {
143             requestSpec.setPaging(WORKSPACES_DEFAULT_REQUEST_SPEC.getPaging());
144         } else {
145             handlePagingRequestValues(requestSpec.getPaging());
146         }
147         if (requestSpec.getSorting() == null) {
148             requestSpec.setSorting(WORKSPACES_DEFAULT_REQUEST_SPEC.getSorting());
149         }
150         return requestSpec;
151     }
152
153     private static void handlePagingRequestValues(PagingRequest paging) {
154         if (paging.getOffset() == null) {
155             paging.setOffset(DEFAULT_OFFSET);
156         }
157         if (paging.getLimit() == null) {
158             paging.setLimit(DEFAULT_LIMIT);
159         } else if (paging.getLimit() > MAX_LIMIT) {
160             paging.setLimit(MAX_LIMIT);
161         }
162     }
163
164     private static Comparator<Workflow> getWorkflowComparator(SortingRequest sorting) {
165         Boolean byNameAscending = sorting.getSorts().stream()
166                                   .filter(sort -> WORKSPACES_SORT_PROPERTY.equalsIgnoreCase(sort.getProperty()))
167                                   .findFirst().map(Sort::isAscendingOrder).orElse(true);
168         Comparator<Workflow> byName = Comparator.comparing(Workflow::getName);
169
170         return byNameAscending ? byName : byName.reversed();
171     }
172
173     private static Predicate<Item> getFilter(Set<VersionStatus> versionStatuses) {
174         return WORKFLOW_ITEM_FILTER
175                        .and(item -> versionStatuses == null || item.getVersionStatusCounters().keySet().stream()
176                                                                    .anyMatch(versionStatuses::contains));
177     }
178 }