efdae4de96266cd895a7b5b825990d1b6445d6fe
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / TypesFetchServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.sdc.be.servlets;
21
22 import com.jcabi.aspects.Loggable;
23 import fj.data.Either;
24 import io.swagger.v3.oas.annotations.Operation;
25 import io.swagger.v3.oas.annotations.Parameter;
26 import io.swagger.v3.oas.annotations.media.ArraySchema;
27 import io.swagger.v3.oas.annotations.media.Content;
28 import io.swagger.v3.oas.annotations.media.Schema;
29 import io.swagger.v3.oas.annotations.responses.ApiResponse;
30 import io.swagger.v3.oas.annotations.servers.Server;
31 import io.swagger.v3.oas.annotations.tags.Tag;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Optional;
37 import java.util.stream.Collectors;
38 import javax.inject.Inject;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.ws.rs.Consumes;
41 import javax.ws.rs.DefaultValue;
42 import javax.ws.rs.GET;
43 import javax.ws.rs.HeaderParam;
44 import javax.ws.rs.Path;
45 import javax.ws.rs.Produces;
46 import javax.ws.rs.QueryParam;
47 import javax.ws.rs.core.Context;
48 import javax.ws.rs.core.MediaType;
49 import javax.ws.rs.core.Response;
50 import org.apache.commons.codec.binary.Base64;
51 import org.apache.commons.collections4.ListUtils;
52 import org.openecomp.sdc.be.components.impl.ArtifactTypeBusinessLogic;
53 import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic;
54 import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic;
55 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
56 import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic;
57 import org.openecomp.sdc.be.components.impl.RelationshipTypeBusinessLogic;
58 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
59 import org.openecomp.sdc.be.components.impl.ResourceImportManager;
60 import org.openecomp.sdc.be.components.impl.aaf.AafPermission;
61 import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed;
62 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
63 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
64 import org.openecomp.sdc.be.config.BeEcompErrorManager;
65 import org.openecomp.sdc.be.dao.api.ActionStatus;
66 import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum;
67 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
68 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
69 import org.openecomp.sdc.be.exception.BusinessException;
70 import org.openecomp.sdc.be.impl.ComponentsUtils;
71 import org.openecomp.sdc.be.impl.ServletUtils;
72 import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
73 import org.openecomp.sdc.be.model.CapabilityTypeDefinition;
74 import org.openecomp.sdc.be.model.Component;
75 import org.openecomp.sdc.be.model.DataTypeDefinition;
76 import org.openecomp.sdc.be.model.InterfaceDefinition;
77 import org.openecomp.sdc.be.model.Model;
78 import org.openecomp.sdc.be.model.RelationshipTypeDefinition;
79 import org.openecomp.sdc.be.model.User;
80 import org.openecomp.sdc.be.model.operations.impl.DataTypeOperation;
81 import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
82 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
83 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
84 import org.openecomp.sdc.common.api.Constants;
85 import org.openecomp.sdc.common.datastructure.Wrapper;
86 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
87 import org.openecomp.sdc.common.log.wrappers.Logger;
88 import org.openecomp.sdc.common.util.ValidationUtils;
89 import org.openecomp.sdc.exception.ResponseFormat;
90 import org.springframework.stereotype.Controller;
91
92 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
93 @Path("/v1/catalog")
94 @Tag(name = "SDCE-2 APIs")
95 @Server(url = "/sdc2/rest")
96 @Controller
97 public class TypesFetchServlet extends AbstractValidationsServlet {
98
99     private static final Logger log = Logger.getLogger(TypesFetchServlet.class);
100     private static final String FAILED_TO_GET_ALL_NON_ABSTRACT = "failed to get all non abstract {}";
101     private static final String START_HANDLE_REQUEST_OF_MODIFIER_ID_IS = "Start handle request of {} | modifier id is {}";
102     private static final String DATATYPE_FILE_TYPE = ".yml";
103     private final RelationshipTypeBusinessLogic relationshipTypeBusinessLogic;
104     private final CapabilitiesBusinessLogic capabilitiesBusinessLogic;
105     private final InterfaceOperationBusinessLogic interfaceOperationBusinessLogic;
106     private final ResourceBusinessLogic resourceBusinessLogic;
107     private final ArtifactTypeBusinessLogic artifactTypeBusinessLogic;
108     private final ModelOperation modelOperation;
109     private final DataTypeOperation dataTypeOperation;
110     private final ToscaExportHandler toscaExportUtils;
111
112     @Inject
113     public TypesFetchServlet(
114         ComponentInstanceBusinessLogic componentInstanceBL,
115         ComponentsUtils componentsUtils,
116         ServletUtils servletUtils,
117         ResourceImportManager resourceImportManager,
118         RelationshipTypeBusinessLogic relationshipTypeBusinessLogic,
119         CapabilitiesBusinessLogic capabilitiesBusinessLogic,
120         InterfaceOperationBusinessLogic interfaceOperationBusinessLogic,
121         ResourceBusinessLogic resourceBusinessLogic,
122         ArtifactTypeBusinessLogic artifactTypeBusinessLogic,
123         ModelOperation modelOperation,
124         DataTypeOperation dataTypeOperation,
125         ToscaExportHandler toscaExportUtils
126     ) {
127         super(
128             componentInstanceBL,
129             componentsUtils,
130             servletUtils,
131             resourceImportManager
132         );
133         this.relationshipTypeBusinessLogic = relationshipTypeBusinessLogic;
134         this.capabilitiesBusinessLogic = capabilitiesBusinessLogic;
135         this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic;
136         this.resourceBusinessLogic = resourceBusinessLogic;
137         this.artifactTypeBusinessLogic = artifactTypeBusinessLogic;
138         this.modelOperation = modelOperation;
139         this.dataTypeOperation = dataTypeOperation;
140         this.toscaExportUtils = toscaExportUtils;
141     }
142
143     @GET
144     @Path("dataTypes")
145     @Consumes(MediaType.APPLICATION_JSON)
146     @Produces(MediaType.APPLICATION_JSON)
147     @Operation(description = "Get data types", method = "GET", summary = "Returns data types", responses = {
148         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
149         @ApiResponse(responseCode = "200", description = "datatypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
150         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
151         @ApiResponse(responseCode = "404", description = "Data types not found")})
152     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
153     public Response getAllDataTypesServlet(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
154                                            @Parameter(description = "model") @QueryParam("model") String modelName) {
155         Wrapper<Response> responseWrapper = new Wrapper<>();
156         Wrapper<User> userWrapper = new Wrapper<>();
157         init();
158         validateUserExist(responseWrapper, userWrapper, userId);
159         if (responseWrapper.isEmpty()) {
160             String url = request.getMethod() + " " + request.getRequestURI();
161             log.debug("Start handle request of {} - modifier id is {}", url, userId);
162             resourceBusinessLogic.getApplicationDataTypeCache().refreshDataTypesCacheIfStale();
163             final Map<String, DataTypeDefinition> dataTypes = resourceBusinessLogic.getComponentsUtils()
164                 .getAllDataTypes(resourceBusinessLogic.getApplicationDataTypeCache(), modelName);
165             String dataTypeJson = gson.toJson(dataTypes);
166             Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
167             responseWrapper.setInnerElement(okResponse);
168         }
169         return responseWrapper.getInnerElement();
170     }
171
172     @GET
173     @Path("allDataTypes")
174     @Consumes(MediaType.APPLICATION_JSON)
175     @Produces(MediaType.APPLICATION_JSON)
176     @Operation(description = "Get data types", method = "GET", summary = "Returns all data types from all models", responses = {
177         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
178         @ApiResponse(responseCode = "200", description = "allDataTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
179         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
180         @ApiResponse(responseCode = "404", description = "Data types not found")})
181     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
182     public Response getAllDataTypesFromAllModels(@Context final HttpServletRequest request,
183                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
184                                                  @QueryParam("excludePrimitives") @DefaultValue("false") String excludePrimitives) {
185         Wrapper<Response> responseWrapper = new Wrapper<>();
186         Wrapper<User> userWrapper = new Wrapper<>();
187         init();
188         validateUserExist(responseWrapper, userWrapper, userId);
189         if (responseWrapper.isEmpty()) {
190             final boolean exclude = Boolean.parseBoolean(excludePrimitives);
191             String url = request.getMethod() + " " + request.getRequestURI();
192             log.debug("Start handle request of {} - modifier id is {}", url, userId);
193             resourceBusinessLogic.getApplicationDataTypeCache().refreshDataTypesCacheIfStale();
194             final List<Map<String, DataTypeDefinition>> dataTypesList = new ArrayList<>();
195             List<Model> models = modelOperation.findAllModels();
196             models.add(new Model(null));
197             models.forEach(model -> {
198                 final Map<String, DataTypeDefinition> dataTypes = resourceBusinessLogic.getComponentsUtils()
199                     .getAllDataTypes(resourceBusinessLogic.getApplicationDataTypeCache(), model.getName());
200                 if (exclude) {
201                     dataTypesList.add(dataTypes.entrySet().stream().filter(entry -> !ToscaPropertyType.isScalarType(entry.getKey()))
202                         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
203                 } else {
204                     dataTypesList.add(dataTypes);
205                 }
206             });
207             String dataTypeJson = gson.toJson(dataTypesList);
208             Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
209             responseWrapper.setInnerElement(okResponse);
210         }
211         return responseWrapper.getInnerElement();
212     }
213
214     @GET
215     @Path("downloadDataType")
216     @Consumes(MediaType.APPLICATION_JSON)
217     @Produces(MediaType.APPLICATION_JSON)
218     @Operation(description = "Get data types", method = "GET", summary = "Returns all data types from all models", responses = {
219         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
220         @ApiResponse(responseCode = "200", description = "allDataTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
221         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
222         @ApiResponse(responseCode = "404", description = "Data types not found")})
223     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
224     public Response downloadDataType(@Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
225                                      @Parameter(description = "dataTypeId") @QueryParam("dataTypeId") String dataTypeId) {
226         Wrapper<Response> responseWrapper = new Wrapper<>();
227         Wrapper<User> userWrapper = new Wrapper<>();
228         init();
229         validateUserExist(responseWrapper, userWrapper, userId);
230         Response response;
231         try {
232             String url = request.getMethod() + " " + request.getRequestURI();
233             log.info(START_HANDLE_REQUEST_OF_MODIFIER_ID_IS, url, userId);
234             response = handleDataTypeDownloadRequest(dataTypeId);
235         } catch (Exception e) {
236             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64");
237             log.debug("downloadResourceArtifactBase64 unexpected exception", e);
238             throw e;
239         }
240         return response;
241     }
242
243     @GET
244     @Path("interfaceLifecycleTypes")
245     @Consumes(MediaType.APPLICATION_JSON)
246     @Produces(MediaType.APPLICATION_JSON)
247     @Operation(description = "Get interface lifecycle types", method = "GET", summary = "Returns interface lifecycle types", responses = {
248         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
249         @ApiResponse(responseCode = "200", description = "Interface lifecycle types"),
250         @ApiResponse(responseCode = "403", description = "Restricted operation"),
251         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
252         @ApiResponse(responseCode = "404", description = "Interface lifecycle types not found")})
253     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
254     public Response getInterfaceLifecycleTypes(@Context final HttpServletRequest request,
255                                                @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
256                                                @Parameter(description = "model") @QueryParam("model") String modelName) {
257         Wrapper<Response> responseWrapper = new Wrapper<>();
258         Wrapper<User> userWrapper = new Wrapper<>();
259         try {
260             validateUserExist(responseWrapper, userWrapper, userId);
261             if (responseWrapper.isEmpty()) {
262                 String url = request.getMethod() + " " + request.getRequestURI();
263                 log.info(START_HANDLE_REQUEST_OF_MODIFIER_ID_IS, url, userId);
264                 Either<Map<String, InterfaceDefinition>, ResponseFormat> allInterfaceLifecycleTypes = interfaceOperationBusinessLogic
265                     .getAllInterfaceLifecycleTypes(modelName);
266                 if (allInterfaceLifecycleTypes.isRight()) {
267                     log.info("Failed to get all interface lifecycle types. Reason - {}", allInterfaceLifecycleTypes.right().value());
268                     Response errorResponse = buildErrorResponse(allInterfaceLifecycleTypes.right().value());
269                     responseWrapper.setInnerElement(errorResponse);
270                 } else {
271                     String interfaceLifecycleTypeJson = gson.toJson(allInterfaceLifecycleTypes.left().value());
272                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), interfaceLifecycleTypeJson);
273                     responseWrapper.setInnerElement(okResponse);
274                 }
275             }
276             return responseWrapper.getInnerElement();
277         } catch (Exception e) {
278             log.debug("get all interface lifecycle types failed with exception", e);
279             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
280             return buildErrorResponse(responseFormat);
281         }
282     }
283
284     @GET
285     @Path("capabilityTypes")
286     @Consumes(MediaType.APPLICATION_JSON)
287     @Produces(MediaType.APPLICATION_JSON)
288     @Operation(description = "Get capability types", method = "GET", summary = "Returns capability types", responses = {
289         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
290         @ApiResponse(responseCode = "200", description = "capabilityTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
291         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
292         @ApiResponse(responseCode = "404", description = "Capability types not found")})
293     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
294     public Response getAllCapabilityTypesServlet(@Context final HttpServletRequest request,
295                                                  @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
296                                                  @Parameter(description = "model") @QueryParam("model") String modelName) {
297         Wrapper<Response> responseWrapper = new Wrapper<>();
298         Wrapper<User> userWrapper = new Wrapper<>();
299         try {
300             init();
301             validateUserExist(responseWrapper, userWrapper, userId);
302             modelName = ValidationUtils.sanitizeInputString(modelName);
303             if (responseWrapper.isEmpty()) {
304                 String url = request.getMethod() + " " + request.getRequestURI();
305                 log.debug(START_HANDLE_REQUEST_OF_MODIFIER_ID_IS, url, userId);
306                 Either<Map<String, CapabilityTypeDefinition>, ResponseFormat> allDataTypes = capabilitiesBusinessLogic.getAllCapabilityTypes(
307                     modelName);
308                 if (allDataTypes.isRight()) {
309                     log.info("Failed to get all capability types. Reason - {}", allDataTypes.right().value());
310                     Response errorResponse = buildErrorResponse(allDataTypes.right().value());
311                     responseWrapper.setInnerElement(errorResponse);
312                 } else {
313                     Map<String, CapabilityTypeDefinition> dataTypes = allDataTypes.left().value();
314                     String dataTypeJson = gson.toJson(dataTypes);
315                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
316                     responseWrapper.setInnerElement(okResponse);
317                 }
318             }
319             return responseWrapper.getInnerElement();
320         } catch (Exception e) {
321             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Capability Types");
322             log.debug("get all capability types failed with exception", e);
323             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
324             return buildErrorResponse(responseFormat);
325         }
326     }
327
328     @GET
329     @Path("relationshipTypes")
330     @Consumes(MediaType.APPLICATION_JSON)
331     @Produces(MediaType.APPLICATION_JSON)
332     @Operation(description = "Get relationship types", method = "GET", summary = "Returns relationship types", responses = {
333         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
334         @ApiResponse(responseCode = "200", description = "relationshipTypes"),
335         @ApiResponse(responseCode = "403", description = "Restricted operation"),
336         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
337         @ApiResponse(responseCode = "404", description = "Relationship types not found")})
338     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
339     public Response getAllRelationshipTypesServlet(@Context final HttpServletRequest request,
340                                                    @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
341                                                    @Parameter(description = "model") @QueryParam("model") String modelName) {
342         Wrapper<Response> responseWrapper = new Wrapper<>();
343         Wrapper<User> userWrapper = new Wrapper<>();
344         try {
345             init();
346             validateUserExist(responseWrapper, userWrapper, userId);
347             modelName = ValidationUtils.sanitizeInputString(modelName);
348             if (responseWrapper.isEmpty()) {
349                 String url = request.getMethod() + " " + request.getRequestURI();
350                 log.debug(START_HANDLE_REQUEST_OF_MODIFIER_ID_IS, url, userId);
351                 Either<Map<String, RelationshipTypeDefinition>, ResponseFormat> allDataTypes = relationshipTypeBusinessLogic
352                     .getAllRelationshipTypes(modelName);
353                 if (allDataTypes.isRight()) {
354                     log.info("Failed to get all relationship types. Reason - {}", allDataTypes.right().value());
355                     Response errorResponse = buildErrorResponse(allDataTypes.right().value());
356                     responseWrapper.setInnerElement(errorResponse);
357                 } else {
358                     Map<String, RelationshipTypeDefinition> dataTypes = allDataTypes.left().value();
359                     String dataTypeJson = gson.toJson(dataTypes);
360                     Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), dataTypeJson);
361                     responseWrapper.setInnerElement(okResponse);
362                 }
363             }
364             return responseWrapper.getInnerElement();
365         } catch (Exception e) {
366             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Relationship Types");
367             log.debug("get all relationship types failed with exception", e);
368             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
369             return buildErrorResponse(responseFormat);
370         }
371     }
372
373     @GET
374     @Path("nodeTypes")
375     @Consumes(MediaType.APPLICATION_JSON)
376     @Produces(MediaType.APPLICATION_JSON)
377     @Operation(description = "Get node types", method = "GET", summary = "Returns node types", responses = {
378         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
379         @ApiResponse(responseCode = "200", description = "nodeTypes"), @ApiResponse(responseCode = "403", description = "Restricted operation"),
380         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
381         @ApiResponse(responseCode = "404", description = "Node types not found")})
382     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
383     public Response getAllNodeTypesServlet(
384         @Context final HttpServletRequest request,
385         @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
386         @Parameter(description = "model") @QueryParam("model") String modelName
387     ) {
388         Wrapper<Response> responseWrapper = new Wrapper<>();
389         Wrapper<User> userWrapper = new Wrapper<>();
390         Either<Map<String, Component>, Response> response;
391         Map<String, Component> componentMap;
392         try {
393             init();
394             validateUserExist(responseWrapper, userWrapper, userId);
395             modelName = ValidationUtils.sanitizeInputString(modelName);
396             if (responseWrapper.isEmpty()) {
397                 String url = request.getMethod() + " " + request.getRequestURI();
398                 log.debug(START_HANDLE_REQUEST_OF_MODIFIER_ID_IS, url, userId);
399                 response = getComponent(resourceBusinessLogic, true, userId, modelName);
400                 if (response.isRight()) {
401                     return response.right().value();
402                 }
403                 componentMap = new HashMap<>(response.left().value());
404                 response = getComponent(resourceBusinessLogic, false, userId, modelName);
405                 if (response.isRight()) {
406                     return response.right().value();
407                 }
408                 componentMap.putAll(response.left().value());
409                 String nodeTypesJson = gson.toJson(componentMap);
410                 Response okResponse = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeTypesJson);
411                 responseWrapper.setInnerElement(okResponse);
412             }
413             return responseWrapper.getInnerElement();
414         } catch (Exception e) {
415             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Node Types");
416             log.debug("get all node types failed with exception", e);
417             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR);
418             return buildErrorResponse(responseFormat);
419         }
420     }
421
422     @GET
423     @Path("/artifactTypes")
424     @Operation(description = "Get Tosca ArtifactTypes", method = "GET", summary = "Returns tosca artifact types", responses = {
425         @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))),
426         @ApiResponse(responseCode = "200", description = "Listing successful"),
427         @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"),
428         @ApiResponse(responseCode = "403", description = "Restricted operation"),
429         @ApiResponse(responseCode = "404", description = "Tosca Artifact Types not found")})
430     @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE)
431     public Response getAllToscaArtifactTypes(@Parameter(description = "Model name") @QueryParam("model") String model,
432                                              @Context final HttpServletRequest request, @HeaderParam(Constants.USER_ID_HEADER) String creator) {
433         try {
434             return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK),
435                 artifactTypeBusinessLogic.getAllToscaArtifactTypes(model));
436         } catch (final BusinessException e) {
437             throw e;
438         } catch (final Exception e) {
439             final var errorMsg = "Unexpected error while listing the Tosca Artifact types";
440             BeEcompErrorManager.getInstance().logBeRestApiGeneralError(errorMsg);
441             log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, this.getClass().getName(), errorMsg, e);
442             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
443         }
444
445     }
446
447     private Either<Map<String, Component>, Response> getComponent(
448         ComponentBusinessLogic resourceBL,
449         boolean isAbstract, String userId,
450         final String modelName
451     ) {
452         Either<List<Component>, ResponseFormat> actionResponse;
453         List<Component> componentList;
454         actionResponse = resourceBL
455             .getLatestVersionNotAbstractComponentsMetadata(isAbstract, HighestFilterEnum.HIGHEST_ONLY, ComponentTypeEnum.RESOURCE, null, userId,
456                 modelName, false);
457         if (actionResponse.isRight()) {
458             log.debug(FAILED_TO_GET_ALL_NON_ABSTRACT, ComponentTypeEnum.RESOURCE.getValue());
459             return Either.right(buildErrorResponse(actionResponse.right().value()));
460         }
461         componentList = actionResponse.left().value();
462         return Either.left(ListUtils.emptyIfNull(componentList).stream().filter(component ->
463                 ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getToscaResourceName() != null)
464             .collect(Collectors.toMap(
465                 component -> ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition())
466                     .getToscaResourceName(), component -> component, (component1, component2) -> component1)));
467     }
468
469     private Response handleDataTypeDownloadRequest(final String dataTypeId) {
470         Optional<DataTypeDefinition> dataTypeDefinition = dataTypeOperation.handleDataTypeDownloadRequestById(dataTypeId);
471         Either<byte[], ComponentException> toscaExportDataType = toscaExportUtils.exportDataType(dataTypeDefinition.get()).left()
472             .map(toscaRepresentation -> {
473                 log.debug("Tosca yaml exported for Datatype {} ", dataTypeDefinition.get().getUniqueId());
474                 return toscaRepresentation.getMainYaml();
475             }).right().map(toscaError -> {
476                 log.debug("Failed export tosca yaml for DataType {} error {}", dataTypeDefinition.get().getUniqueId(), toscaError);
477                 return new ByActionStatusComponentException(componentsUtils.convertFromToscaError(toscaError));
478             });
479         byte[] file = toscaExportDataType.left().value();
480         String base64Contents = new String(Base64.encodeBase64(file));
481         String artifactName = dataTypeDefinition.get().getName() + DATATYPE_FILE_TYPE;
482         ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
483         ArtifactUiDownloadData artifactUiDownloadData = new ArtifactUiDownloadData();
484         artifactUiDownloadData.setArtifactName(artifactName);
485         artifactUiDownloadData.setBase64Contents(base64Contents);
486         return buildOkResponse(responseFormat, artifactUiDownloadData);
487     }
488 }