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