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