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