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