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