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