7f1124f1b318e5e42f593592e538a16994946247
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ElementServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.sdc.be.servlets;
21
22 import com.jcabi.aspects.Loggable;
23 import fj.data.Either;
24 import io.swagger.v3.oas.annotations.Operation;
25 import io.swagger.v3.oas.annotations.Parameter;
26 import io.swagger.v3.oas.annotations.media.ArraySchema;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.servers.Server;
31 import java.io.IOException;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Set;
37 import java.util.stream.Collectors;
38 import javax.inject.Inject;
39 import javax.servlet.ServletContext;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.Consumes;
42 import javax.ws.rs.DELETE;
43 import javax.ws.rs.GET;
44 import javax.ws.rs.HeaderParam;
45 import javax.ws.rs.POST;
46 import javax.ws.rs.Path;
47 import javax.ws.rs.PathParam;
48 import javax.ws.rs.Produces;
49 import javax.ws.rs.QueryParam;
50 import javax.ws.rs.core.Context;
51 import javax.ws.rs.core.MediaType;
52 import javax.ws.rs.core.Response;
53 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
54 import org.openecomp.sdc.be.components.impl.ElementBusinessLogic;
55 import org.openecomp.sdc.be.components.impl.ModelBusinessLogic;
56 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
57 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
58 import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic;
59 import org.openecomp.sdc.be.config.BeEcompErrorManager;
60 import org.openecomp.sdc.be.config.Configuration;
61 import org.openecomp.sdc.be.config.ConfigurationManager;
62 import org.openecomp.sdc.be.dao.api.ActionStatus;
63 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
66 import org.openecomp.sdc.be.impl.ComponentsUtils;
67 import org.openecomp.sdc.be.info.ArtifactTypesInfo;
68 import org.openecomp.sdc.be.model.ArtifactType;
69 import org.openecomp.sdc.be.model.BaseType;
70 import org.openecomp.sdc.be.model.CatalogUpdateTimestamp;
71 import org.openecomp.sdc.be.model.Category;
72 import org.openecomp.sdc.be.model.Component;
73 import org.openecomp.sdc.be.model.PropertyScope;
74 import org.openecomp.sdc.be.model.Tag;
75 import org.openecomp.sdc.be.model.User;
76 import org.openecomp.sdc.be.model.catalog.CatalogComponent;
77 import org.openecomp.sdc.be.model.category.CategoryDefinition;
78 import org.openecomp.sdc.be.model.category.GroupingDefinition;
79 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
80 import org.openecomp.sdc.be.ui.model.UiCategories;
81 import org.openecomp.sdc.be.user.UserBusinessLogic;
82 import org.openecomp.sdc.common.api.Constants;
83 import org.openecomp.sdc.common.log.wrappers.Logger;
84 import org.openecomp.sdc.common.util.Multitenancy;
85 import org.openecomp.sdc.exception.ResponseFormat;
86 import org.springframework.stereotype.Controller;
87 import org.keycloak.representations.AccessToken;
88 @Path("/v1/")
89 /**
90  *
91  * UI oriented servlet - to return elements in specific format UI needs
92  *
93  *
94  */
95 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
96 @io.swagger.v3.oas.annotations.tags.Tag(name = "SDCE-2 APIs")
97 @Server(url = "/sdc2/rest")
98 @Controller
99 public class ElementServlet extends BeGenericServlet {
100
101     private static final Logger log = Logger.getLogger(ElementServlet.class);
102     private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}";
103     private final ComponentsCleanBusinessLogic componentsCleanBusinessLogic;
104     private final ElementBusinessLogic elementBusinessLogic;
105     private final ArtifactsBusinessLogic artifactsBusinessLogic;
106     private final ModelBusinessLogic modelBusinessLogic;
107
108     @Inject
109     public ElementServlet(final ComponentsUtils componentsUtils,
110                           final ComponentsCleanBusinessLogic componentsCleanBusinessLogic, final ElementBusinessLogic elementBusinessLogic,
111                           final ArtifactsBusinessLogic artifactsBusinessLogic, final ModelBusinessLogic modelBusinessLogic) {
112         super(componentsUtils);
113         this.componentsCleanBusinessLogic = componentsCleanBusinessLogic;
114         this.elementBusinessLogic = elementBusinessLogic;
115         this.artifactsBusinessLogic = artifactsBusinessLogic;
116         this.modelBusinessLogic = modelBusinessLogic;
117     }
118     /*
119      ******************************************************************************
120      * NEW CATEGORIES category / \ subcategory subcategory / grouping
121      ******************************************************************************/
122
123     /*
124      *
125      *
126      * CATEGORIES
127      */
128
129     /////////////////////////////////////////////////////////////////////////////////////////////////////
130
131     // retrieve all component categories
132     @GET
133     @Path("/categories/{componentType}")
134     @Consumes(MediaType.APPLICATION_JSON)
135     @Produces(MediaType.APPLICATION_JSON)
136     @Operation(description = "Retrieve the list of all resource/service/product categories/sub-categories/groupings", method = "GET", summary = "Retrieve the list of all resource/service/product categories/sub-categories/groupings.", responses = {
137         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
138         @ApiResponse(responseCode = "200", description = "Returns categories Ok"),
139         @ApiResponse(responseCode = "403", description = "Missing information"),
140         @ApiResponse(responseCode = "400", description = "Invalid component type"),
141         @ApiResponse(responseCode = "409", description = "Restricted operation"),
142         @ApiResponse(responseCode = "500", description = "Internal Server Error")})
143     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
144     public Response getComponentCategories(
145         @Parameter(description = "allowed values are resources / services/ products", schema = @Schema(allowableValues = {
146             ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
147             ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType,
148         @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) {
149         try {
150             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
151             Either<List<CategoryDefinition>, ResponseFormat> either = elementBL.getAllCategories(componentType, userId);
152             if (either.isRight()) {
153                 log.debug("No categories were found for type {}", componentType);
154                 return buildErrorResponse(either.right().value());
155             } else {
156                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
157             }
158         } catch (Exception e) {
159             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component Categories");
160             log.debug("getComponentCategories failed with exception", e);
161             throw e;
162         }
163     }
164
165     @POST
166     @Path("/category/{componentType}")
167     @Consumes(MediaType.APPLICATION_JSON)
168     @Produces(MediaType.APPLICATION_JSON)
169     @Operation(description = "Create new component category", method = "POST", summary = "Create new component category", responses = {
170         @ApiResponse(responseCode = "201", description = "Category created"),
171         @ApiResponse(responseCode = "400", description = "Invalid category data"),
172         @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
173         @ApiResponse(responseCode = "409", description = "Category already exists / User not permitted to perform the action"),
174         @ApiResponse(responseCode = "500", description = "General Error")})
175     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
176     public Response createComponentCategory(
177         @Parameter(description = "allowed values are resources /services / products", schema = @Schema(allowableValues = {
178             ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME,
179             ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType,
180         @Parameter(description = "Category to be created", required = true) String data, @Context final HttpServletRequest request,
181         @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
182         try {
183             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
184             CategoryDefinition category = RepresentationUtils.fromRepresentation(data, CategoryDefinition.class);
185             Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.createCategory(category, componentType, userId);
186             if (createResourceCategory.isRight()) {
187                 return buildErrorResponse(createResourceCategory.right().value());
188             }
189             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
190             return buildOkResponse(responseFormat, createResourceCategory.left().value());
191         } catch (Exception e) {
192             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");
193             log.debug("createResourceCategory failed with exception", e);
194             throw e;
195         }
196     }
197
198     @GET
199     @Path("/category/{componentType}/{categoryName}/baseTypes")
200     @Consumes(MediaType.APPLICATION_JSON)
201     @Produces(MediaType.APPLICATION_JSON)
202     @Operation(description = "Get base types for category", method = "GET", summary = "Get base types for category",
203         responses = {@ApiResponse(responseCode = "200", description = "Returns base types Ok"),
204             @ApiResponse(responseCode = "404", description = "No base types were found"),
205             @ApiResponse(responseCode = "500", description = "Internal Server Error")})
206     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
207     public Response getCategoryBaseTypes(@PathParam(value = "categoryName") final String categoryName,
208                                          @PathParam(value = "componentType") final String componentType,
209                                          @Context final HttpServletRequest request,
210                                          @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
211                                          @Parameter(description = "model", required = false) @QueryParam("model") String modelName) {
212         try {
213             final ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
214             final Either<List<BaseType>, ActionStatus> either = elementBL.getBaseTypes(categoryName, userId, modelName);
215
216             if (either.isRight() || either.left().value() == null) {
217                 log.debug("No base types were found");
218                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
219             } else {
220                 final Map<String, Object> baseTypesMap = new HashMap<>();
221                 baseTypesMap.put("baseTypes", either.left().value());
222                 baseTypesMap.put("required", elementBL.isBaseTypeRequired(categoryName));
223                 baseTypesMap.put("defaultBaseType", elementBL.getDefaultBaseType(categoryName));
224                 baseTypesMap.put("doNotExtendBaseType", elementBL.isDoNotExtendBaseType(categoryName));
225
226                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), baseTypesMap);
227             }
228         } catch (Exception e) {
229             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get base types of category");
230             log.debug("getCategoryBaseTypes failed with exception", e);
231             throw e;
232         }
233     }
234
235     @DELETE
236     @Path("/category/{componentType}/{categoryUniqueId}")
237     @Consumes(MediaType.APPLICATION_JSON)
238     @Produces(MediaType.APPLICATION_JSON)
239     @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", responses = {
240         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))),
241         @ApiResponse(responseCode = "204", description = "Category deleted"),
242         @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
243         @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),
244         @ApiResponse(responseCode = "404", description = "Category not found"), @ApiResponse(responseCode = "500", description = "General Error")})
245     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
246     public Response deleteComponentCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId,
247                                             @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
248                                             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
249         try {
250             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
251             Either<CategoryDefinition, ResponseFormat> createResourceCategory = elementBL.deleteCategory(categoryUniqueId, componentType, userId);
252             if (createResourceCategory.isRight()) {
253                 return buildErrorResponse(createResourceCategory.right().value());
254             }
255             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
256             return buildOkResponse(responseFormat, null);
257         } catch (Exception e) {
258             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create resource category");
259             log.debug("createResourceCategory failed with exception", e);
260             throw e;
261         }
262     }
263
264     /*
265      *
266      *
267      * SUBCATEGORIES
268      *
269      */
270     @POST
271     @Path("/category/{componentType}/{categoryId}/subCategory")
272     @Consumes(MediaType.APPLICATION_JSON)
273     @Produces(MediaType.APPLICATION_JSON)
274     @Operation(description = "Create new component sub-category", method = "POST", summary = "Create new component sub-category for existing category", responses = {
275         @ApiResponse(responseCode = "201", description = "Subcategory created"),
276         @ApiResponse(responseCode = "400", description = "Invalid subcategory data"),
277         @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
278         @ApiResponse(responseCode = "404", description = "Parent category wasn't found"),
279         @ApiResponse(responseCode = "409", description = "Subcategory already exists / User not permitted to perform the action"),
280         @ApiResponse(responseCode = "500", description = "General Error")})
281     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
282     public Response createComponentSubCategory(
283         @Parameter(description = "allowed values are resources / products", schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME,
284             ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType,
285         @Parameter(description = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String categoryId,
286         @Parameter(description = "Subcategory to be created. \ne.g. {\"name\":\"Resource-subcat\"}", required = true) String data,
287         @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
288         try {
289             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
290             SubCategoryDefinition subCategory = RepresentationUtils.fromRepresentation(data, SubCategoryDefinition.class);
291             Either<SubCategoryDefinition, ResponseFormat> createSubcategory = elementBL
292                 .createSubCategory(subCategory, componentType, categoryId, userId);
293             if (createSubcategory.isRight()) {
294                 return buildErrorResponse(createSubcategory.right().value());
295             }
296             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
297             return buildOkResponse(responseFormat, createSubcategory.left().value());
298         } catch (Exception e) {
299             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create sub-category");
300             log.debug("createComponentSubCategory failed with exception", e);
301             throw e;
302         }
303     }
304
305     @DELETE
306     @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}")
307     @Consumes(MediaType.APPLICATION_JSON)
308     @Produces(MediaType.APPLICATION_JSON)
309     @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", responses = {
310         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))),
311         @ApiResponse(responseCode = "204", description = "Category deleted"),
312         @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
313         @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),
314         @ApiResponse(responseCode = "404", description = "Category not found"), @ApiResponse(responseCode = "500", description = "General Error")})
315     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
316     public Response deleteComponentSubCategory(@PathParam(value = "categoryUniqueId") final String categoryUniqueId,
317                                                @PathParam(value = "subCategoryUniqueId") final String subCategoryUniqueId,
318                                                @PathParam(value = "componentType") final String componentType,
319                                                @Context final HttpServletRequest request,
320                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
321         try {
322             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
323             Either<SubCategoryDefinition, ResponseFormat> deleteSubResourceCategory = elementBL
324                 .deleteSubCategory(subCategoryUniqueId, componentType, userId);
325             if (deleteSubResourceCategory.isRight()) {
326                 return buildErrorResponse(deleteSubResourceCategory.right().value());
327             }
328             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
329             return buildOkResponse(responseFormat, null);
330         } catch (Exception e) {
331             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component subcategory");
332             log.debug("deleteComponentSubCategory failed with exception", e);
333             throw e;
334         }
335     }
336
337     /*
338      * GROUPINGS
339      */
340     @POST
341     @Path("/category/{componentType}/{categoryId}/subCategory/{subCategoryId}/grouping")
342     @Consumes(MediaType.APPLICATION_JSON)
343     @Produces(MediaType.APPLICATION_JSON)
344     @Operation(description = "Create new component grouping", method = "POST", summary = "Create new component grouping for existing sub-category", responses = {
345         @ApiResponse(responseCode = "201", description = "Grouping created"),
346         @ApiResponse(responseCode = "400", description = "Invalid grouping data"),
347         @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
348         @ApiResponse(responseCode = "404", description = "Parent category or subcategory were not found"),
349         @ApiResponse(responseCode = "409", description = "Grouping already exists / User not permitted to perform the action"),
350         @ApiResponse(responseCode = "500", description = "General Error")})
351     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
352     public Response createComponentGrouping(@Parameter(description = "allowed values are products", schema = @Schema(allowableValues = {
353         ComponentTypeEnum.PRODUCT_PARAM_NAME}), required = true) @PathParam(value = "componentType") final String componentType,
354                                             @Parameter(description = "Parent category unique ID", required = true) @PathParam(value = "categoryId") final String grandParentCategoryId,
355                                             @Parameter(description = "Parent sub-category unique ID", required = true) @PathParam(value = "subCategoryId") final String parentSubCategoryId,
356                                             @Parameter(description = "Subcategory to be created", required = true) String data,
357                                             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
358         try {
359             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
360             GroupingDefinition grouping = RepresentationUtils.fromRepresentation(data, GroupingDefinition.class);
361             Either<GroupingDefinition, ResponseFormat> createGrouping = elementBL
362                 .createGrouping(grouping, componentType, grandParentCategoryId, parentSubCategoryId, userId);
363             if (createGrouping.isRight()) {
364                 return buildErrorResponse(createGrouping.right().value());
365             }
366             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED);
367             return buildOkResponse(responseFormat, createGrouping.left().value());
368         } catch (Exception e) {
369             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create grouping");
370             log.debug("createComponentGrouping failed with exception", e);
371             throw e;
372         }
373     }
374
375     @DELETE
376     @Path("/category/{componentType}/{categoryUniqueId}/subCategory/{subCategoryUniqueId}/grouping/{groupingUniqueId}")
377     @Consumes(MediaType.APPLICATION_JSON)
378     @Produces(MediaType.APPLICATION_JSON)
379     @Operation(description = "Delete component category", method = "DELETE", summary = "Delete component category", responses = {
380         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Category.class)))),
381         @ApiResponse(responseCode = "204", description = "Category deleted"),
382         @ApiResponse(responseCode = "403", description = "USER_ID header is missing"),
383         @ApiResponse(responseCode = "409", description = "User not permitted to perform the action"),
384         @ApiResponse(responseCode = "404", description = "Category not found"), @ApiResponse(responseCode = "500", description = "General Error")})
385     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
386     public Response deleteComponentGrouping(@PathParam(value = "categoryUniqueId") final String grandParentCategoryUniqueId,
387                                             @PathParam(value = "subCategoryUniqueId") final String parentSubCategoryUniqueId,
388                                             @PathParam(value = "groupingUniqueId") final String groupingUniqueId,
389                                             @PathParam(value = "componentType") final String componentType, @Context final HttpServletRequest request,
390                                             @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
391         try {
392             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
393             Either<GroupingDefinition, ResponseFormat> deleteGrouping = elementBL.deleteGrouping(groupingUniqueId, componentType, userId);
394             if (deleteGrouping.isRight()) {
395                 return buildErrorResponse(deleteGrouping.right().value());
396             }
397             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT);
398             return buildOkResponse(responseFormat, null);
399         } catch (Exception e) {
400             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete component grouping");
401             log.debug("deleteGrouping failed with exception", e);
402             throw e;
403         }
404     }
405     /////////////////////////////////////////////////////////////////////////////////////////////////////
406
407     // retrieve all tags
408     @GET
409     @Path("/tags")
410     @Consumes(MediaType.APPLICATION_JSON)
411     @Produces(MediaType.APPLICATION_JSON)
412     @Operation(description = "Retrieve all tags", method = "GET", summary = "Retrieve all tags", responses = {
413         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
414         @ApiResponse(responseCode = "200", description = "Returns tags Ok"), @ApiResponse(responseCode = "404", description = "No tags were found"),
415         @ApiResponse(responseCode = "500", description = "Internal Server Error")})
416     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
417     public Response getTags(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
418         String url = request.getMethod() + " " + request.getRequestURI();
419         log.debug("(getTags) Start handle request of {}", url);
420         try {
421             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
422             Either<List<Tag>, ActionStatus> either = elementBL.getAllTags(userId);
423             if (either.isRight() || either.left().value() == null) {
424                 log.debug("No tags were found");
425                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
426             } else {
427                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
428             }
429         } catch (Exception e) {
430             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get All Tags");
431             log.debug("getAllTags failed with exception", e);
432             throw e;
433         }
434     }
435     /////////////////////////////////////////////////////////////////////////////////////////////////////
436
437     // retrieve all property scopes
438     @GET
439     @Path("/propertyScopes")
440     @Consumes(MediaType.APPLICATION_JSON)
441     @Produces(MediaType.APPLICATION_JSON)
442     @Operation(description = "Retrieve all propertyScopes", method = "GET", summary = "Retrieve all propertyScopes", responses = {
443         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
444         @ApiResponse(responseCode = "200", description = "Returns propertyScopes Ok"),
445         @ApiResponse(responseCode = "404", description = "No propertyScopes were found"),
446         @ApiResponse(responseCode = "500", description = "Internal Server Error")})
447     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
448     public Response getPropertyScopes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
449         String url = request.getMethod() + " " + request.getRequestURI();
450         log.debug("(getPropertyScopes) Start handle request of {}", url);
451         try {
452             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
453             Either<List<PropertyScope>, ActionStatus> either = elementBL.getAllPropertyScopes(userId);
454             if (either.isRight() || either.left().value() == null) {
455                 log.debug("No property scopes were found");
456                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
457             } else {
458                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), either.left().value());
459             }
460         } catch (Exception e) {
461             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Property Scopes Categories");
462             log.debug("getPropertyScopes failed with exception", e);
463             throw e;
464         }
465     }
466     /////////////////////////////////////////////////////////////////////////////////////////////////////
467
468     // retrieve all artifact types
469     @GET
470     @Path("/artifactTypes")
471     @Consumes(MediaType.APPLICATION_JSON)
472     @Produces(MediaType.APPLICATION_JSON)
473     @Operation(description = "Retrieve all artifactTypes", method = "GET", summary = "Retrieve all artifactTypes", responses = {
474         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
475         @ApiResponse(responseCode = "200", description = "Returns artifactTypes Ok"),
476         @ApiResponse(responseCode = "404", description = "No artifactTypes were found"),
477         @ApiResponse(responseCode = "500", description = "Internal Server Error")})
478     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
479     public Response getArtifactTypes(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
480         String url = request.getMethod() + " " + request.getRequestURI();
481         log.debug("(GET - getArtifactTypes) Start handle request of {}", url);
482         try {
483             ElementBusinessLogic elementBL = getElementBL(request.getSession().getServletContext());
484             Either<List<ArtifactType>, ActionStatus> either = elementBL.getAllArtifactTypes(userId);
485             if (either.isRight() || either.left().value() == null) {
486                 log.debug("No artifact types were found");
487                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
488             } else {
489                 Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()
490                     .getDefaultMinutes();
491                 ArtifactTypesInfo typesResponse = new ArtifactTypesInfo();
492                 typesResponse.setArtifactTypes(either.left().value());
493                 typesResponse.setHeatDefaultTimeout(defaultHeatTimeout);
494                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), typesResponse);
495             }
496         } catch (Exception e) {
497             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Artifact Types");
498             log.debug("getArtifactTypes failed with exception", e);
499             throw e;
500         }
501     }
502     /////////////////////////////////////////////////////////////////////////////////////////////////////
503
504     // retrieve all followed resources and services
505     @GET
506     @Path("/followed")
507     @Consumes(MediaType.APPLICATION_JSON)
508     @Produces(MediaType.APPLICATION_JSON)
509     @Operation(description = "Retrieve all followed", method = "GET", summary = "Retrieve all followed", responses = {
510         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
511         @ApiResponse(responseCode = "200", description = "Returns followed Ok"),
512         @ApiResponse(responseCode = "404", description = "No followed were found"),
513         @ApiResponse(responseCode = "404", description = "User not found"),
514         @ApiResponse(responseCode = "500", description = "Internal Server Error")})
515     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
516     public Response getFollowedResourcesServices(@Context final HttpServletRequest request,
517                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException {
518         try {
519             String url = request.getMethod() + " " + request.getRequestURI();
520             log.debug(START_HANDLE_REQUEST_OF, url);
521             UserBusinessLogic userAdminManager = getUserAdminManager(request.getSession().getServletContext());
522             User userData = userAdminManager.getUser(userId, false);
523             Either<Map<String, List<? extends Component>>, ResponseFormat> followedResourcesServices = getElementBL(
524                 request.getSession().getServletContext()).getFollowed(userData);
525             if (followedResourcesServices.isRight()) {
526                 log.debug("failed to get followed resources services ");
527                 return buildErrorResponse(followedResourcesServices.right().value());
528             }
529             Multitenancy keyaccess= new Multitenancy();
530             if (keyaccess.multiTenancyCheck()) {
531                 AccessToken.Access realmAccess = keyaccess.getAccessToken(request).getRealmAccess();
532                 Set<String> realmroles = realmAccess.getRoles();
533                 Map<String, List<? extends Component>> dataResponse = new HashMap<>();
534                followedResourcesServices.left().value().entrySet().stream()
535                         .forEach(component->{component.setValue(component.getValue().stream().filter(cm->realmroles.stream()
536                                 .anyMatch(role->cm.getTenant().equals(role))).collect(Collectors.toList()));
537                             dataResponse.put(component.getKey(), component.getValue());
538                         });
539                 Object data = RepresentationUtils.toRepresentation(dataResponse);
540                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);
541             }
542             else{
543                 Object data = RepresentationUtils.toRepresentation(followedResourcesServices.left().value());
544                 return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);
545             }
546         } catch (Exception e) {
547             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Followed Resources / Services Categories");
548             log.debug("Getting followed resources/services failed with exception", e);
549             throw e;
550         }
551     }
552     /////////////////////////////////////////////////////////////////////////////////////////////////////
553
554     // retrieve all certified resources and services and their last version
555     @GET
556     @Path("/screen")
557     @Consumes(MediaType.APPLICATION_JSON)
558     @Produces(MediaType.APPLICATION_JSON)
559     @Operation(description = "Retrieve catalog resources and services", method = "GET", summary = "Retrieve catalog resources and services", responses = {
560         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
561         @ApiResponse(responseCode = "200", description = "Returns resources and services Ok"),
562         @ApiResponse(responseCode = "404", description = "No resources and services were found"),
563         @ApiResponse(responseCode = "404", description = "User not found"),
564         @ApiResponse(responseCode = "500", description = "Internal Server Error")})
565     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
566     public Response getCatalogComponents(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
567                                          @QueryParam("excludeTypes") List<OriginTypeEnum> excludeTypes) throws IOException {
568         try {
569             String url = request.getMethod() + " " + request.getRequestURI();
570             log.debug(START_HANDLE_REQUEST_OF, url);
571             Either<Map<String, List<CatalogComponent>>, ResponseFormat> catalogData = getElementBL(request.getSession().getServletContext())
572                 .getCatalogComponents(excludeTypes);
573             if (catalogData.isRight()) {
574                 log.debug("failed to get catalog data");
575                 return buildErrorResponse(catalogData.right().value());
576             }
577             Object data = RepresentationUtils.toRepresentation(catalogData.left().value());
578             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), data);
579         } catch (Exception e) {
580             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Catalog Components");
581             log.debug("Getting catalog components failed with exception", e);
582             throw e;
583         }
584     }
585
586     @DELETE
587     @Path("/inactiveComponents/{componentType}")
588     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
589     public Response deleteMarkedResources(@PathParam("componentType") final String componentType, @Context final HttpServletRequest request) {
590         String url = request.getMethod() + " " + request.getRequestURI();
591         log.debug(START_HANDLE_REQUEST_OF, url);
592         // get modifier id
593         String userId = request.getHeader(Constants.USER_ID_HEADER);
594         User modifier = new User();
595         modifier.setUserId(userId);
596         log.debug("modifier id is {}", userId);
597         NodeTypeEnum nodeType = NodeTypeEnum.getByNameIgnoreCase(componentType);
598         if (nodeType == null) {
599             log.info("componentType is not valid: {}", componentType);
600             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT));
601         }
602         List<NodeTypeEnum> componentsList = new ArrayList<>();
603         componentsList.add(nodeType);
604         try {
605             Map<NodeTypeEnum, Either<List<String>, ResponseFormat>> cleanComponentsResult = componentsCleanBusinessLogic
606                 .cleanComponents(componentsList);
607             Either<List<String>, ResponseFormat> cleanResult = cleanComponentsResult.get(nodeType);
608             if (cleanResult.isRight()) {
609                 log.debug("failed to delete marked components of type {}", nodeType);
610                 return buildErrorResponse(cleanResult.right().value());
611             }
612             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), cleanResult.left().value());
613         } catch (Exception e) {
614             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Marked Components");
615             log.debug("delete marked components failed with exception", e);
616             throw e;
617         }
618     }
619
620     @GET
621     @Path("/ecompPortalMenu")
622     @Consumes(MediaType.APPLICATION_JSON)
623     @Produces(MediaType.APPLICATION_JSON)
624     @Operation(description = "Retrieve ecomp portal menu - MOC", method = "GET", summary = "Retrieve ecomp portal menu", responses = {
625         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
626         @ApiResponse(responseCode = "200", description = "Retrieve ecomp portal menu")})
627     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
628     public Response getListOfCsars(@Context final HttpServletRequest request) {
629         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
630             "[{\"menuId\":1,\"column\":2,\"text\":\"Design\",\"parentMenuId\":null,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":11,\"column\":1,\"text\":\"ProductDesign\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":12,\"column\":2,\"text\":\"Service\",\"parentMenuId\":1,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":21,\"column\":1,\"text\":\"ViewPolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":90,\"column\":1,\"text\":\"4thLevelApp1aR16\",\"parentMenuId\":21,\"url\":\"http://google.com\",\"appid\":null,\"roles\":null}]},{\"menuId\":22,\"column\":2,\"text\":\"UpdatePolicies\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null,\"children\":[{\"menuId\":91,\"column\":1,\"text\":\"4thLevelApp1bR16\",\"parentMenuId\":22,\"url\":\"http://jsonlint.com/\",\"appid\":null,\"roles\":null}]},{\"menuId\":23,\"column\":3,\"text\":\"UpdateRules\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":24,\"column\":4,\"text\":\"CreateSignatures?\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null},{\"menuId\":25,\"column\":5,\"text\":\"Definedata\",\"parentMenuId\":12,\"url\":\"\",\"appid\":null,\"roles\":null}]}]}]");
631     }
632
633     @GET
634     @Path("/catalogUpdateTime")
635     @Consumes(MediaType.APPLICATION_JSON)
636     @Produces(MediaType.APPLICATION_JSON)
637     @Operation(description = "Retrieve previus and current catalog update time", method = "GET", summary = "Retrieve previus and current catalog update time", responses = {
638         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
639         @ApiResponse(responseCode = "200", description = "Retrieve previus and current catalog update time")})
640     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
641     public Response getCatalogUpdateTime(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
642         String url = request.getMethod() + " " + request.getRequestURI();
643         log.debug("(post) Start handle request of {}", url);
644         CatalogUpdateTimestamp catalogUpdateTimestamp = getElementBL(request.getSession().getServletContext()).getCatalogUpdateTime();
645         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), catalogUpdateTimestamp);
646     }
647
648     // retrieve all artifact types, ui configuration and sdc version
649     @GET
650     @Path("/setup/ui")
651     @Consumes(MediaType.APPLICATION_JSON)
652     @Produces(MediaType.APPLICATION_JSON)
653     @Operation(description = "Retrieve all artifactTypes, ui configuration and sdc version", method = "GET", summary = "Retrieve all artifactTypes, ui configuration and sdc version", responses = {
654         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = User.class)))),
655         @ApiResponse(responseCode = "200", description = "Returns artifactTypes, ui configuration and sdc version Ok"),
656         @ApiResponse(responseCode = "404", description = "No artifactTypes were found/no ui configuration were found/no sdc version were found"),
657         @ApiResponse(responseCode = "500", description = "Internal Server Error")})
658     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
659     public Response getConfCategoriesAndVersion(@Context final HttpServletRequest request,
660                                                 @HeaderParam(value = Constants.USER_ID_HEADER) String userId) {
661         String url = request.getMethod() + " " + request.getRequestURI();
662         log.debug("(getConsolidated) Start handle request of {}", url);
663         Map<String, Object> consolidatedObject = new HashMap<>();
664         try {
665             ServletContext servletContext = request.getSession().getServletContext();
666             Map<String, Object> configuration = getConfigurationUi(elementBusinessLogic);
667             if (!configuration.isEmpty()) {
668                 consolidatedObject.put("configuration", configuration);
669             } else {
670                 return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT));
671             }
672             Either<UiCategories, ResponseFormat> either = elementBusinessLogic.getAllCategories(userId);
673             if (either.isRight()) {
674                 log.debug("No categories were found");
675                 return buildErrorResponse(either.right().value());
676             }
677             consolidatedObject.put("categories", either.left().value());
678             consolidatedObject.put("models", modelBusinessLogic.listModels());
679             consolidatedObject.put("version", getVersion(servletContext));
680         } catch (Exception e) {
681             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("getSDCVersion");
682             log.debug("method getConfCategoriesAndVersion failed with unexpected exception", e);
683             throw e;
684         }
685         return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), consolidatedObject);
686     }
687
688     private String getVersion(ServletContext servletContext) {
689         String version = (String) servletContext.getAttribute(Constants.ASDC_RELEASE_VERSION_ATTR);
690         log.debug("sdc version from manifest is: {}", version);
691         return version;
692     }
693
694     private Map<String, Object> getConfigurationUi(final ElementBusinessLogic elementBL) {
695         Either<Configuration.HeatDeploymentArtifactTimeout, ActionStatus> defaultHeatTimeout = elementBL.getDefaultHeatTimeout();
696         Either<Map<String, String>, ActionStatus> resourceTypesMap = elementBL.getResourceTypesMap();
697         Map<String, Object> configuration = new HashMap<>();
698         if (defaultHeatTimeout.isRight() || defaultHeatTimeout.left().value() == null) {
699             log.debug("heat default timeout was not found");
700             return configuration;
701         }
702         if (resourceTypesMap.isRight() || resourceTypesMap.left().value() == null) {
703             log.debug("No resource types were found");
704             return configuration;
705         }
706         configuration.put("artifact", artifactsBusinessLogic.getConfiguration());
707         configuration.put("heatDeploymentTimeout", defaultHeatTimeout.left().value());
708         configuration.put("componentTypes", elementBL.getAllComponentTypesParamNames());
709         configuration.put("roles", elementBL.getAllSupportedRoles());
710         configuration.put("resourceTypes", resourceTypesMap.left().value());
711         configuration.put("environmentContext", ConfigurationManager.getConfigurationManager().getConfiguration().getEnvironmentContext());
712         configuration.put("gab", ConfigurationManager.getConfigurationManager().getConfiguration().getGabConfig());
713         return configuration;
714     }
715 }