re base code
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / ArtifactServlet.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.apache.commons.codec.binary.Base64;
27 import org.apache.commons.lang3.tuple.ImmutablePair;
28 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic;
29 import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum;
30 import org.openecomp.sdc.be.config.BeEcompErrorManager;
31 import org.openecomp.sdc.be.dao.api.ActionStatus;
32 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
33 import org.openecomp.sdc.be.model.ArtifactDefinition;
34 import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
35 import org.openecomp.sdc.be.model.Operation;
36 import org.openecomp.sdc.common.api.Constants;
37 import org.openecomp.sdc.common.log.wrappers.Logger;
38 import org.openecomp.sdc.exception.ResponseFormat;
39
40 import javax.inject.Singleton;
41 import javax.servlet.ServletContext;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.ws.rs.*;
44 import javax.ws.rs.core.Context;
45 import javax.ws.rs.core.MediaType;
46 import javax.ws.rs.core.Response;
47 import java.util.Map;
48 /**
49  * Root resource (exposed at "/" path)
50  */
51 @Loggable(prepend = true, value = Loggable.DEBUG, trim = false)
52 @Path("/v1/catalog")
53 @Api(value = "Resource Artifact Servlet", description = "Resource Artifact Servlet")
54 @Singleton
55 public class ArtifactServlet extends BeGenericServlet {
56
57     private static final Logger log = Logger.getLogger(ArtifactServlet.class);
58
59     // *************** Resources
60     @POST
61     @Path("/resources/{resourceId}/artifacts")
62     @Consumes(MediaType.APPLICATION_JSON)
63     @Produces(MediaType.APPLICATION_JSON)
64     @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
65     @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
66             @ApiResponse(code = 409, message = "Artifact already exist") })
67     public Response loadArtifact(@PathParam("resourceId") final String resourceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
68
69         String url = request.getMethod() + " " + request.getRequestURI();
70         log.debug("Start handle request of {}" , url);
71         try {
72             return handleUploadRequest(data, request, resourceId, ComponentTypeEnum.RESOURCE);
73         } catch (Exception e) {
74             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifact");
75             log.debug("loadArtifact unexpected exception", e);
76             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
77         }
78     }
79
80     @POST
81     @Path("/resources/{resourceId}/artifacts/{artifactId}")
82     @Consumes(MediaType.APPLICATION_JSON)
83     @Produces(MediaType.APPLICATION_JSON)
84     @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
85     @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
86     public Response updateArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
87             @Context final HttpServletRequest request) {
88
89         String url = request.getMethod() + " " + request.getRequestURI();
90         log.debug("Start handle request of {}" , url);
91         try {
92             return handleUpdateRequest(data, request, resourceId, artifactId, ComponentTypeEnum.RESOURCE);
93         } catch (Exception e) {
94             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifact");
95             log.debug("updateArtifact unexpected exception", e);
96             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
97         }
98     }
99
100     @DELETE
101     @Path("/resources/{resourceId}/artifacts/{artifactId}")
102     @Consumes(MediaType.APPLICATION_JSON)
103     @Produces(MediaType.APPLICATION_JSON)
104     @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class)
105     @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
106     public Response deleteArtifact(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
107
108         String url = request.getMethod() + " " + request.getRequestURI();
109         log.debug("Start handle request of {}" , url);
110         try {
111             return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, null, null);
112         } catch (Exception e) {
113             log.debug("deleteArtifact unexpected exception", e);
114             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
115         }
116     }
117
118     // *************** Services
119     @POST
120     @Path("/services/{serviceId}/artifacts")
121     @Consumes(MediaType.APPLICATION_JSON)
122     @Produces(MediaType.APPLICATION_JSON)
123     @ApiOperation(value = "Create Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
124     @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
125             @ApiResponse(code = 409, message = "Artifact already exist") })
126     public Response loadInformationArtifact(@PathParam("serviceId") final String serviceId, @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
127
128         String url = request.getMethod() + " " + request.getRequestURI();
129         log.debug("Start handle request of {}" , url);
130         try {
131             return handleUploadRequest(data, request, serviceId, ComponentTypeEnum.SERVICE);
132         } catch (Exception e) {
133             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadInformationArtifact");
134             log.debug("loadInformationArtifact unexpected exception", e);
135             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
136         }
137     }
138
139     @POST
140     @Path("/services/{serviceId}/artifacts/{artifactId}")
141     @Consumes(MediaType.APPLICATION_JSON)
142     @Produces(MediaType.APPLICATION_JSON)
143     @ApiOperation(value = "Update Artifact", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
144     @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
145     public Response updateInformationArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
146             @Context final HttpServletRequest request) {
147
148         String url = request.getMethod() + " " + request.getRequestURI();
149         log.debug("Start handle request of {}" , url);
150         try {
151             return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
152         } catch (Exception e) {
153             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateInformationArtifact");
154             log.debug("updateInformationArtifact unexpected exception", e);
155             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
156         }
157     }
158
159     // *************** Services api artifacts
160     @POST
161     @Path("/services/{serviceId}/artifacts/api/{artifactId}")
162     @Consumes(MediaType.APPLICATION_JSON)
163     @Produces(MediaType.APPLICATION_JSON)
164     @ApiOperation(value = "Update Api Artifact", httpMethod = "POST", notes = "Returns created ArtifactDefinition", response = Response.class)
165     @ApiResponses(value = { @ApiResponse(code = 200, message = "Api Artifact Updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
166     public Response updateApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @ApiParam(value = "json describe the artifact", required = true) String data,
167             @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
168
169         String url = request.getMethod() + " " + request.getRequestURI();
170         log.debug("Start handle request of {}" , url);
171         try {
172             return handleUpdateRequest(data, request, serviceId, artifactId, ComponentTypeEnum.SERVICE);
173         } catch (Exception e) {
174             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateApiArtifact");
175             log.debug("updateApiArtifact unexpected exception", e);
176             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
177         }
178     }
179
180     @DELETE
181     @Path("/services/{serviceId}/artifacts/api/{artifactId}")
182     @Consumes(MediaType.APPLICATION_JSON)
183     @Produces(MediaType.APPLICATION_JSON)
184     @ApiOperation(value = "Delete Api Artifact", httpMethod = "DELETE", notes = "Returns Deleted ArtifactDefinition", response = Response.class)
185     @ApiResponses(value = { @ApiResponse(code = 204, message = "Api Artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation") })
186     public Response deleteApiArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId,
187             @HeaderParam(value = Constants.MD5_HEADER) String origMd5) {
188
189         String url = request.getMethod() + " " + request.getRequestURI();
190         log.debug("Start handle request of {}" , url);
191         try {
192             return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
193         } catch (Exception e) {
194             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteApiArtifact");
195             log.debug("deleteApiArtifact unexpected exception", e);
196             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
197         }
198     }
199
200     @DELETE
201     @Path("/services/{serviceId}/artifacts/{artifactId}")
202     @Consumes(MediaType.APPLICATION_JSON)
203     @Produces(MediaType.APPLICATION_JSON)
204     @ApiOperation(value = "Delete Artifact", httpMethod = "DELETE", notes = "Returns delete artifact", response = Response.class)
205     @ApiResponses(value = { @ApiResponse(code = 201, message = "Service artifact deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
206     public Response deleteInformationalArtifact(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
207
208         String url = request.getMethod() + " " + request.getRequestURI();
209         log.debug("Start handle request of {}" , url);
210         try {
211             return handleDeleteRequest(request, serviceId, artifactId, ComponentTypeEnum.SERVICE, null, null);
212         } catch (Exception e) {
213             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteInformationalArtifact");
214             log.debug("deleteInformationalArtifact unexpected exception", e);
215             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
216         }
217     }
218
219     /*
220      * DOWNLOAD Artifacts by json body in base 64 (because of userId problem with href)
221      */
222
223     @GET
224     @Path("/services/{serviceId}/artifacts/{artifactId}")
225     @Consumes(MediaType.APPLICATION_JSON)
226     @Produces(MediaType.APPLICATION_JSON)
227     @ApiOperation(value = "Download service Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
228     @ApiResponses(value = { @ApiResponse(code = 200, message = "Service artifact downloaded"), @ApiResponse(code = 404, message = "Service/Artifact not found") })
229     public Response downloadServiceArtifactBase64(@PathParam("serviceId") final String serviceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
230
231         String url = request.getMethod() + " " + request.getRequestURI();
232         log.debug("Start handle request of {}" , url);
233         try {
234             return handleDownloadRequest(request, serviceId, artifactId, null, ComponentTypeEnum.SERVICE, null);
235         } catch (Exception e) {
236             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadServiceArtifactBase64");
237             log.debug("downloadServiceArtifactBase64 unexpected exception", e);
238             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
239         }
240     }
241
242     @GET
243     @Path("/resources/{resourceId}/artifacts/{artifactId}")
244     @Consumes(MediaType.APPLICATION_JSON)
245     @Produces(MediaType.APPLICATION_JSON)
246     @ApiOperation(value = "Download resource Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
247     @ApiResponses(value = { @ApiResponse(code = 200, message = "Resource artifact downloaded"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
248     public Response downloadResourceArtifactBase64(@PathParam("resourceId") final String resourceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
249
250         String url = request.getMethod() + " " + request.getRequestURI();
251         log.debug("Start handle request of {}" , url);
252         try {
253             return handleDownloadRequest(request, resourceId, artifactId, null, ComponentTypeEnum.RESOURCE, null);
254         } catch (Exception e) {
255             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceArtifactBase64");
256             log.debug("downloadResourceArtifactBase64 unexpected exception", e);
257             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
258         }
259     }
260
261     @GET
262     @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifacts/{artifactId}")
263     @Consumes(MediaType.APPLICATION_JSON)
264     @Produces(MediaType.APPLICATION_JSON)
265     @ApiOperation(value = "Download component Artifact in Base64", httpMethod = "GET", notes = "Returns downloaded artifact", response = Response.class)
266     @ApiResponses(value = { @ApiResponse(code = 200, message = "ResourceInstance artifact downloaded"), @ApiResponse(code = 404, message = "ResourceInstance/Artifact not found") })
267     public Response downloadResourceInstanceArtifactBase64(
268             @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
269             @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId, @Context final HttpServletRequest request) {
270
271         String url = request.getMethod() + " " + request.getRequestURI();
272         log.debug("Start handle request of {}" , url);
273         try {
274             return handleDownloadRequest(request, componentInstanceId, artifactId, componentId, ComponentTypeEnum.RESOURCE_INSTANCE, containerComponentType);
275         } catch (Exception e) {
276             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
277             log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
278             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
279         }
280     }
281
282     // *************** Resource lifecycle ( interfces )
283
284     @POST
285     @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts")
286     @Consumes(MediaType.APPLICATION_JSON)
287     @Produces(MediaType.APPLICATION_JSON)
288     @ApiOperation(value = "Create Artifact and Attach to interface", httpMethod = "POST", notes = "Returns created resource", response = Response.class)
289     @ApiResponses(value = { @ApiResponse(code = 201, message = "Resource created"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
290             @ApiResponse(code = 409, message = "Artifact already exist") })
291     public Response loadArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation,
292             @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @ApiParam(value = "json describe the artifact", required = true) String data,
293             @Context final HttpServletRequest request) {
294
295         String url = request.getMethod() + " " + request.getRequestURI();
296         log.debug("Start handle request of {}" , url);
297         try {
298             return handleArtifactRequest(data, request, resourceId, interfaceType, operation, null, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.CREATE, null, null);
299         } catch (Exception e) {
300             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("loadArtifactToInterface");
301             log.debug("loadArtifactToInterface unexpected exception", e);
302             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
303         }
304
305     }
306
307     @DELETE
308     @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")
309     @Consumes(MediaType.APPLICATION_JSON)
310     @Produces(MediaType.APPLICATION_JSON)
311     @ApiOperation(value = "delete Artifact from interface", httpMethod = "delete", notes = "delete matching artifact from interface", response = Response.class)
312     @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
313             @ApiResponse(code = 409, message = "Artifact already exist") })
314     public Response deleteArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId,
315             @Context final HttpServletRequest request) {
316
317         String url = request.getMethod() + " " + request.getRequestURI();
318         log.debug("Start handle request of {}" , url);
319         try {
320             return handleDeleteRequest(request, resourceId, artifactId, ComponentTypeEnum.RESOURCE, interfaceType, operation);
321         } catch (Exception e) {
322             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("deleteArtifactToInterface");
323             log.debug("deleteArtifactToInterface unexpected exception", e);
324             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
325         }
326     }
327
328     @POST
329     @Path("/resources/{resourceId}/{interfaceType}/{operation}/artifacts/{artifactId}")
330     @Consumes(MediaType.APPLICATION_JSON)
331     @Produces(MediaType.APPLICATION_JSON)
332     @ApiOperation(value = "update Artifact  Attach to interface", httpMethod = "post", notes = "updates artifact by interface", response = Response.class)
333     @ApiResponses(value = { @ApiResponse(code = 201, message = "delete artifact under interface deleted"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"),
334             @ApiResponse(code = 409, message = "Artifact already exist") })
335     public Response updateArtifactToInterface(@PathParam("resourceId") final String resourceId, @PathParam("interfaceType") final String interfaceType, @PathParam("operation") final String operation, @PathParam("artifactId") final String artifactId,
336             @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5, @Context final HttpServletRequest request,
337             @ApiParam(value = "json describe the artifact", required = true) String data) {
338
339         String url = request.getMethod() + " " + request.getRequestURI();
340         log.debug("Start handle request of {}" , url);
341         try {
342             return handleArtifactRequest(data, request, resourceId, interfaceType, operation, artifactId, ComponentTypeEnum.RESOURCE, ArtifactOperationEnum.UPDATE, null, null);
343         } catch (Exception e) {
344             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateArtifactToInterface");
345             log.debug("updateArtifactToInterface unexpected exception", e);
346             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
347         }
348     }
349
350     @POST
351     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}/heatParams")
352     @Consumes(MediaType.APPLICATION_JSON)
353     @Produces(MediaType.APPLICATION_JSON)
354     @ApiOperation(value = "Update Resource Instance HEAT_ENV parameters", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
355     @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
356     public Response updateRIArtifact(
357             @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
358             @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
359             @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
360
361         String url = request.getMethod() + " " + request.getRequestURI();
362         log.debug("Start handle request of {}" , url);
363         try {
364             return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType);
365         } catch (Exception e) {
366             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("updateRIArtifact");
367             log.debug("updateRIArtifact unexpected exception", e);
368             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
369         }
370     }
371
372     @POST
373     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")
374     @Consumes(MediaType.APPLICATION_JSON)
375     @Produces(MediaType.APPLICATION_JSON)
376     @ApiOperation(value = "Update Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
377     @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
378     public Response updateComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
379             @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
380             @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
381             @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
382
383         String url = request.getMethod() + " " + request.getRequestURI();
384         log.debug("Start handle request of {}" , url);
385         try {
386             return handleArtifactRequest(data, request, componentInstanceId, null, null, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.UPDATE, componentId, containerComponentType);
387         } catch (Exception e) {
388             log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
389             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
390         }
391     }
392
393     @POST
394     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts")
395     @Consumes(MediaType.APPLICATION_JSON)
396     @Produces(MediaType.APPLICATION_JSON)
397     @ApiOperation(value = "Load Resource Instance artifact payload", httpMethod = "POST", notes = "Returns updated artifact", response = Response.class)
398     @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
399     public Response loadComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
400             @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
401             @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @ApiParam(value = "json describe the artifact", required = true) String data,
402             @Context final HttpServletRequest request) {
403
404         String url = request.getMethod() + " " + request.getRequestURI();
405         log.debug("Start handle request of {}" , url);
406         try {
407             return handleArtifactRequest(data, request, componentInstanceId, null, null, null, ComponentTypeEnum.RESOURCE_INSTANCE, ArtifactOperationEnum.CREATE, componentId, containerComponentType);
408         } catch (Exception e) {
409             log.debug("loadResourceInstanceHeatEnvArtifact unexpected exception", e);
410             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
411         }
412     }
413
414     @DELETE
415     @Path("/{containerComponentType}/{componentId}/resourceInstance/{componentInstanceId}/artifacts/{artifactId}")
416     @Consumes(MediaType.APPLICATION_JSON)
417     @Produces(MediaType.APPLICATION_JSON)
418     @ApiOperation(value = "Delete Resource Instance artifact", httpMethod = "POST", notes = "Returns deleted artifact", response = Response.class)
419     @ApiResponses(value = { @ApiResponse(code = 200, message = "Artifact updated"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content") })
420     public Response deleteComponentInstanceArtifact(@HeaderParam(value = Constants.USER_ID_HEADER) String userId, @HeaderParam(value = Constants.MD5_HEADER) String origMd5,
421             @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
422             @PathParam("componentId") final String componentId, @PathParam("componentInstanceId") final String componentInstanceId, @PathParam("artifactId") final String artifactId,
423             @ApiParam(value = "json describe the artifact", required = true) String data, @Context final HttpServletRequest request) {
424
425         String url = request.getMethod() + " " + request.getRequestURI();
426         log.debug("Start handle request of {}" , url);
427         try {
428             return handleDeleteRequest(request, componentInstanceId, artifactId, ComponentTypeEnum.RESOURCE_INSTANCE, null, null, componentId);
429         } catch (Exception e) {
430             log.debug("deleteArtifact unexpected exception", e);
431             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
432         }
433     }
434
435
436     @GET
437     @Path("/{containerComponentType}/{componentId}/artifactsByType/{artifactGroupType}")
438     @Consumes(MediaType.APPLICATION_JSON)
439     @Produces(MediaType.APPLICATION_JSON)
440     @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class)
441     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
442     public Response getComponentArtifacts(
443             @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
444             @PathParam("componentId") final String componentId, @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
445
446         String url = request.getMethod() + " " + request.getRequestURI();
447         log.debug("Start handle request of {}" , url);
448         try {
449             return handleGetArtifactsRequest(request, componentId, null, artifactGroupType, containerComponentType);
450         } catch (Exception e) {
451             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
452             log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
453             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
454         }
455     }
456
457     @GET
458     @Path("/{containerComponentType}/{componentId}/resourceInstances/{componentInstanceId}/artifactsByType/{artifactGroupType}")
459     @Consumes(MediaType.APPLICATION_JSON)
460     @Produces(MediaType.APPLICATION_JSON)
461     @ApiOperation(value = "Get component Artifacts", httpMethod = "GET", notes = "Returns artifacts", response = Response.class)
462     @ApiResponses(value = { @ApiResponse(code = 200, message = "Component artifacts"), @ApiResponse(code = 404, message = "Resource/Artifact not found") })
463     public Response getComponentInstanceArtifacts(
464             @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType,
465             @PathParam("componentId") final String componentId,  @PathParam("componentInstanceId") final String componentInstanceId,  @PathParam("artifactGroupType") final String artifactGroupType, @Context final HttpServletRequest request) {
466
467         String url = request.getMethod() + " " + request.getRequestURI();
468         log.debug("Start handle request of {}" , url);
469         try {
470             return handleGetArtifactsRequest(request,componentInstanceId , componentId, artifactGroupType, containerComponentType);
471         } catch (Exception e) {
472             BeEcompErrorManager.getInstance().logBeRestApiGeneralError("downloadResourceInstanceArtifactBase64");
473             log.debug("downloadResourceInstanceArtifactBase64 unexpected exception", e);
474             return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR));
475         }
476     }
477
478
479     // ////////// API END ///////////////////////////
480
481     // ************ private *********************
482
483     private Response handleUploadRequest(String data, HttpServletRequest request, String componentId, ComponentTypeEnum componentType) {
484         return handleArtifactRequest(data, componentId, null, componentType, ArtifactOperationEnum.CREATE);
485     }
486
487     private Response handleUpdateRequest(String data, HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType) {
488         return handleArtifactRequest(data, componentId, artifactId, componentType, ArtifactOperationEnum.UPDATE);
489     }
490
491     private Response handleDownloadRequest(HttpServletRequest request, String componentId, String artifactId, String parentId, ComponentTypeEnum componentType, String containerComponentType) {
492         String userId = request.getHeader(Constants.USER_ID_HEADER);
493         ServletContext context = request.getSession().getServletContext();
494         ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
495         Either<ImmutablePair<String, byte[]>, ResponseFormat> actionResult = artifactsLogic.handleDownloadRequestById(componentId, artifactId, userId, componentType, parentId, containerComponentType);
496
497         Response response;
498         if (actionResult.isRight()) {
499             response = buildErrorResponse(actionResult.right().value());
500         } else {
501             byte[] file = actionResult.left().value().getRight();
502             String base64Contents = new String(Base64.encodeBase64(file));
503             String artifactName = actionResult.left().value().getLeft();
504             ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK);
505             ArtifactUiDownloadData artifactUiDownloadData = new ArtifactUiDownloadData();
506             artifactUiDownloadData.setArtifactName(artifactName);
507             artifactUiDownloadData.setBase64Contents(base64Contents);
508             response = buildOkResponse(responseFormat, artifactUiDownloadData);
509         }
510         return response;
511     }
512
513     private Response handleGetArtifactsRequest(HttpServletRequest request, String componentId, String parentId, String artifactGroupType, String containerComponentType) {
514         String userId = request.getHeader(Constants.USER_ID_HEADER);
515         ServletContext context = request.getSession().getServletContext();
516         ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
517         ComponentTypeEnum componentTypeEnum  = parentId == null || parentId.isEmpty()? ComponentTypeEnum.findByParamName(containerComponentType): ComponentTypeEnum.RESOURCE_INSTANCE;
518         Either<Map<String, ArtifactDefinition>, ResponseFormat> actionResult = artifactsLogic.handleGetArtifactsByType(containerComponentType, parentId, componentTypeEnum, componentId, artifactGroupType, userId);
519
520         Response response;
521         if (actionResult.isRight()) {
522             response = buildErrorResponse(actionResult.right().value());
523         } else {
524
525             response =  buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResult.left().value());
526         }
527
528         return response;
529     }
530
531
532     private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName) {
533         return handleDeleteRequest(request, componentId, artifactId, componentType, interfaceType, operationName, null);
534     }
535
536     private Response handleDeleteRequest(HttpServletRequest request, String componentId, String artifactId, ComponentTypeEnum componentType, String interfaceType, String operationName, String parentId) {
537         String userId = request.getHeader(Constants.USER_ID_HEADER);
538         ServletContext context = request.getSession().getServletContext();
539         ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
540         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType, artifactsLogic.new ArtifactOperationInfo (false, false, ArtifactOperationEnum.DELETE), artifactId, null, null, null, interfaceType, operationName,
541                 parentId, null);
542         Response response;
543         if (actionResult.isRight()) {
544             response = buildErrorResponse(actionResult.right().value());
545         } else {
546             Either<ArtifactDefinition, Operation> result = actionResult.left().value();
547             if (result.isLeft()) {
548                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());
549             } else {
550                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());
551             }
552         }
553         return response;
554
555     }
556
557     private Response handleArtifactRequest(String data, HttpServletRequest request, String componentId, String interfaceName, String operationName, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operationEnum, String parentId,
558             String containerComponentType) {
559         ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
560         String origMd5 = request.getHeader(Constants.MD5_HEADER);
561
562         String userId = request.getHeader(Constants.USER_ID_HEADER);
563
564         ServletContext context = request.getSession().getServletContext();
565         ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context);
566         Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = artifactsLogic.handleArtifactRequest(componentId, userId, componentType,
567                 artifactsLogic.new ArtifactOperationInfo (false, false,operationEnum), artifactId, artifactInfo, origMd5, data, interfaceName, operationName, parentId,
568                 containerComponentType);
569         Response response;
570         if (actionResult.isRight()) {
571             response = buildErrorResponse(actionResult.right().value());
572         } else {
573             Either<ArtifactDefinition, Operation> result = actionResult.left().value();
574             if (result.isLeft()) {
575                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.left().value());
576             } else {
577                 response = buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result.right().value());
578             }
579         }
580         return response;
581
582     }
583
584     private Response handleArtifactRequest(String data, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationEnum operation) {
585         return handleArtifactRequest(data, servletRequest, componentId, null, null, artifactId, componentType, operation, null, null);
586     }
587
588 }