re base code
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / vendor-software-products-rest / vnf-repository-rest-services / src / main / java / org / openecomp / sdcrests / vsp / rest / services / VnfPackageRepositoryImpl.java
1 /*
2  * Copyright 2017 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.sdcrests.vsp.rest.services;
18
19 import org.apache.http.HttpStatus;
20 import org.onap.config.api.Configuration;
21 import org.onap.config.api.ConfigurationManager;
22 import org.openecomp.sdc.common.http.client.api.HttpRequest;
23 import org.openecomp.sdc.common.http.client.api.HttpResponse;
24 import org.openecomp.sdc.logging.api.Logger;
25 import org.openecomp.sdc.logging.api.LoggerFactory;
26 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
27 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
28 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
29 import org.openecomp.sdc.versioning.VersioningManager;
30 import org.openecomp.sdc.versioning.VersioningManagerFactory;
31 import org.openecomp.sdc.versioning.dao.types.Version;
32 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
33 import org.openecomp.sdcrests.vsp.rest.VnfPackageRepository;
34 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
35 import org.springframework.context.annotation.Scope;
36 import org.springframework.stereotype.Service;
37
38 import javax.inject.Named;
39 import javax.ws.rs.core.Response;
40 import java.io.BufferedInputStream;
41 import java.io.ByteArrayInputStream;
42 import java.io.InputStream;
43 import java.nio.charset.StandardCharsets;
44
45 import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
46 import static org.openecomp.core.utilities.file.FileUtils.getFileExtension;
47 import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName;
48
49 /**
50  * The class implements the API interface with VNF Repository (VNFSDK) such as
51  * i) Get all the VNF Package Meta-data ii) Download the VNF Package iii) Import
52  * VNF package to SDC catalog (Download & validate)
53  * 
54  * @version Amsterdam release (ONAP 1.0)
55  */
56 @Named
57 @Service("vnfPackageRepository")
58 @Scope(value = "prototype")
59 public class VnfPackageRepositoryImpl implements VnfPackageRepository {
60
61     private static final Logger LOGGER = LoggerFactory.getLogger(VnfPackageRepositoryImpl.class);
62
63     private static boolean initFlag = false;
64
65     // Default VNF Repository configuration
66     private static final String CONFIG_NAMESPACE = "vnfrepo";
67
68     // Default address for VNF repository docker
69     private static final String DEF_DOCKER_COMPOSE_ADDR = "127.0.0.1";
70
71     private static String ipAddress = DEF_DOCKER_COMPOSE_ADDR;
72
73     // Default Download package URI and Get VNF package meta-data URI -
74     // configurable
75     private static String getVnfPkgUri = "/onapapi/vnfsdk-marketplace/v1/PackageResource/csars";
76
77     private static String downldPkgUri = "/onapapi/vnfsdk-marketplace/v1/PackageResource/csars/%s/files";
78
79     // Default port for VNF Repository
80     private static String port = "8702";
81
82     @Override
83     public Response getVnfPackages(String vspId, String versionId, String user) throws Exception {
84
85         LOGGER.debug("Get VNF Packages from Repository:{}", vspId);
86
87         // Step 1: Create REST client and configuration and prepare URI
88         init();
89
90         // Step 2: Build URI based on the IP address and port allocated
91         HttpResponse<String> rsp = HttpRequest.get(getVnfPkgUri);
92         if(HttpStatus.SC_OK != rsp.getStatusCode()) {
93             LOGGER.error("Failed to query VNF package metadata:uri={}, Response={}", getVnfPkgUri, rsp);
94             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
95         }
96
97         // Step 3: Send the response to the client
98         LOGGER.debug("Response from VNF Repository: {}", rsp.getResponse());
99
100         return Response.ok(rsp.getResponse()).build();
101     }
102
103     @Override
104     public Response importVnfPackage(String vspId, String versionId, String csarId, String user) throws Exception {
105
106         LOGGER.debug("Import VNF Packages from Repository:{}", csarId);
107
108         // Step 1: Create REST client and configuration and prepare URI
109         init();
110
111         // Step 2: Build URI based on the IP address and port allocated
112         String uri = String.format(downldPkgUri, csarId);
113         HttpResponse<String> rsp = HttpRequest.get(uri);
114         if(HttpStatus.SC_OK != rsp.getStatusCode()) {
115             LOGGER.error("Failed to download package from VNF Repository:uri={}, Response={}", uri, rsp);
116             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
117         }
118         LOGGER.debug("Response from VNF Repository for download package is success ");
119
120         // Step 3: Import the file to SDC and validate and send the response
121         try (InputStream fileStream = new BufferedInputStream(
122                 new ByteArrayInputStream(rsp.getResponse().getBytes(StandardCharsets.ISO_8859_1)))) {
123
124             String filename = "temp_" + csarId + ".csar";
125             OrchestrationTemplateCandidateManager candidateManager =
126                     OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
127             UploadFileResponse uploadFileResponse = candidateManager.upload(vspId, getVersion(vspId, versionId),
128                     fileStream, getFileExtension(filename), getNetworkPackageName(filename));
129
130             UploadFileResponseDto uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
131                     .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
132
133             return Response.ok(uploadFileResponseDto).build();
134         } catch(Exception e) {
135             // Exception while uploading file
136
137             LOGGER.error("Exception while uploading VNF package received from VNF Repository:", e);
138             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
139         }
140     }
141
142     @Override
143     public Response downloadVnfPackage(String vspId, String versionId, String csarId, String user) throws Exception {
144
145         LOGGER.debug("Download VNF Packages from Repository:csarId={}", csarId);
146
147         // Step 1: Create REST client and configuration and prepare URI
148         init();
149
150         // Step 2: Build URI based on the IP address and port allocated
151         String uri = String.format(downldPkgUri, csarId);
152         HttpResponse<String> rsp = HttpRequest.get(uri);
153         if(HttpStatus.SC_OK != rsp.getStatusCode()) {
154             LOGGER.error("Failed to download package from VNF Repository:uri={}, Response={}", uri, rsp);
155             return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
156         }
157
158         // Step 3:Send response to the client
159         String filename = "temp_" + csarId + ".csar";
160         Response.ResponseBuilder response = Response.ok(rsp.getResponse().getBytes(StandardCharsets.ISO_8859_1));
161         response.header(CONTENT_DISPOSITION, "attachment; filename=" + filename);
162
163         LOGGER.debug("Response from VNF Repository for download package is success ");
164
165         return response.build();
166     }
167
168     private Version getVersion(String vspId, String versionId) {
169         // Get list of Versions from the rest call
170         VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface();
171
172         // Find the corresponding version from versionId
173         return versioningManager.list(vspId).stream().filter(ver -> ver.getId() != versionId).findAny()
174                 .orElse(new Version(versionId));
175     }
176
177     private static void setVnfRepoConfig() {
178
179         try {
180             // Step 1: Fetch the on-boarding configuration
181             Configuration config = ConfigurationManager.lookup();
182
183             String vnfRepoHost = config.getAsString(CONFIG_NAMESPACE, "vnfRepoHost");
184             if(null != vnfRepoHost) {
185                 ipAddress = vnfRepoHost;
186             }
187
188             String vnfRepoPort = config.getAsString(CONFIG_NAMESPACE, "vnfRepoPort");
189             if(null != vnfRepoPort) {
190                 port = vnfRepoPort;
191             }
192
193             String getVnfUri = config.getAsString(CONFIG_NAMESPACE, "getVnfUri");
194             if(null != getVnfUri) {
195                 getVnfPkgUri = getVnfUri;
196             }
197
198             String downloadVnfUri = config.getAsString(CONFIG_NAMESPACE, "downloadVnfUri");
199             if(null != downloadVnfUri) {
200                 downldPkgUri = downloadVnfUri;
201             }
202
203         } catch(Exception e) {
204             LOGGER.error("Failed to load configuration, Exception caught, using default configuration", e);
205         }
206
207         getVnfPkgUri =
208                 new StringBuilder("http://").append(ipAddress).append(":").append(port).append(getVnfPkgUri).toString();
209
210         downldPkgUri =
211                 new StringBuilder("http://").append(ipAddress).append(":").append(port).append(downldPkgUri).toString();
212     }
213
214     private static synchronized void init() throws Exception {
215         if(!initFlag) {
216             // Step 1: Initialize configuration
217             setVnfRepoConfig();
218
219             initFlag = true;
220         }
221     }
222 }