2 * Copyright 2017 Huawei Technologies Co., Ltd.
3 * Modifications Copyright 2018 European Support Limited
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 package org.openecomp.sdcrests.vsp.rest.services;
19 import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION;
20 import static org.openecomp.core.utilities.file.FileUtils.getFileExtension;
21 import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName;
23 import java.nio.ByteBuffer;
24 import java.nio.charset.StandardCharsets;
25 import java.security.KeyManagementException;
26 import java.security.NoSuchAlgorithmException;
27 import java.security.cert.X509Certificate;
28 import java.util.List;
29 import java.util.Objects;
30 import java.util.Optional;
31 import javax.inject.Named;
32 import javax.net.ssl.SSLContext;
33 import javax.net.ssl.TrustManager;
34 import javax.net.ssl.X509TrustManager;
35 import javax.ws.rs.client.Client;
36 import javax.ws.rs.client.ClientBuilder;
37 import javax.ws.rs.core.Response;
38 import org.onap.config.api.ConfigurationManager;
39 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
40 import org.openecomp.sdc.common.errors.CoreException;
41 import org.openecomp.sdc.common.errors.ErrorCode;
42 import org.openecomp.sdc.common.errors.ErrorCodeAndMessage;
43 import org.openecomp.sdc.common.errors.GeneralErrorBuilder;
44 import org.openecomp.sdc.logging.api.Logger;
45 import org.openecomp.sdc.logging.api.LoggerFactory;
46 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
47 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
48 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
49 import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo;
50 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
51 import org.openecomp.sdc.versioning.VersioningManager;
52 import org.openecomp.sdc.versioning.VersioningManagerFactory;
53 import org.openecomp.sdc.versioning.dao.types.Version;
54 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
55 import org.openecomp.sdcrests.vsp.rest.VnfPackageRepository;
56 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
57 import org.springframework.context.annotation.Scope;
58 import org.springframework.stereotype.Service;
61 * Enables integration API interface with VNF Repository (VNFSDK).
63 * <li>Get all the VNF Package Meta-data.</li>
64 * <li>Download a VNF Package.</li>
65 * <li>Import a VNF package to SDC catalog (Download & validate).</li>
68 * @version Amsterdam release (ONAP 1.0)
71 @Service("vnfPackageRepository")
72 @Scope(value = "prototype")
73 public class VnfPackageRepositoryImpl implements VnfPackageRepository {
75 private static final Logger LOGGER = LoggerFactory.getLogger(VnfPackageRepositoryImpl.class);
76 private static final Client CLIENT = ignoreSSLClient();
78 private static Client ignoreSSLClient() {
80 SSLContext sslcontext = SSLContext.getInstance("TLS");
81 sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
82 public void checkClientTrusted(X509Certificate[] c, String s) {
85 public void checkServerTrusted(X509Certificate[] c, String s) {
88 public X509Certificate[] getAcceptedIssuers() {
89 return new X509Certificate[0];
91 }}, new java.security.SecureRandom());
92 return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier((a, b) -> true).build();
93 } catch (NoSuchAlgorithmException | KeyManagementException e) {
94 LOGGER.error("Failed to initialize SSL unsecure context", e);
96 return ClientBuilder.newClient();
99 private final Configuration config;
101 public VnfPackageRepositoryImpl(Configuration config) {
102 this.config = config;
105 public VnfPackageRepositoryImpl() {
106 this(new FileConfiguration());
110 public Response getVnfPackages(String vspId, String versionId, String user) {
111 LOGGER.debug("Get VNF Packages from Repository: {}", vspId);
112 final String getVnfPackageUri = config.getGetUri();
113 Response remoteResponse = CLIENT.target(getVnfPackageUri).request().get();
114 if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
115 return handleUnexpectedStatus("querying VNF package metadata", getVnfPackageUri, remoteResponse);
117 LOGGER.debug("Response from VNF Repository: {}", remoteResponse);
118 return Response.ok(remoteResponse.readEntity(String.class)).build();
122 public Response importVnfPackage(String vspId, String versionId, String csarId, String user) {
123 LOGGER.debug("Import VNF Packages from Repository: {}", csarId);
124 final String downloadPackageUri = String.format(config.getDownloadUri(), csarId);
125 Response remoteResponse = CLIENT.target(downloadPackageUri).request().get();
126 if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
127 return handleUnexpectedStatus("downloading VNF package", downloadPackageUri, remoteResponse);
129 LOGGER.debug("Response from VNF Repository for download package is success. URI={}", downloadPackageUri);
130 byte[] payload = remoteResponse.readEntity(String.class).getBytes(StandardCharsets.ISO_8859_1);
131 return uploadVnfPackage(vspId, versionId, csarId, payload);
134 private Response uploadVnfPackage(final String vspId, final String versionId, final String csarId, final byte[] payload) {
136 final OrchestrationTemplateCandidateManager candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance()
138 final String filename = formatFilename(csarId);
139 final String fileExtension = getFileExtension(filename);
140 final OnboardPackageInfo onboardPackageInfo = new OnboardPackageInfo(getNetworkPackageName(filename), fileExtension,
141 ByteBuffer.wrap(payload), OnboardingTypesEnum.getOnboardingTypesEnum(fileExtension));
142 final VspDetails vspDetails = new VspDetails(vspId, getVersion(vspId, versionId));
143 final UploadFileResponse response = candidateManager.upload(vspDetails, onboardPackageInfo);
144 final UploadFileResponseDto uploadFileResponse = new MapUploadFileResponseToUploadFileResponseDto()
145 .applyMapping(response, UploadFileResponseDto.class);
146 return Response.ok(uploadFileResponse).build();
147 } catch (final Exception e) {
148 ErrorCode error = new GeneralErrorBuilder().build();
149 LOGGER.error("Exception while uploading package received from VNF Repository", new CoreException(error, e));
150 return generateInternalServerError(error);
155 public Response downloadVnfPackage(String vspId, String versionId, String csarId, String user) {
156 LOGGER.debug("Download VNF package from repository: csarId={}", csarId);
157 final String downloadPackageUri = String.format(config.getDownloadUri(), csarId);
158 Response remoteResponse = CLIENT.target(downloadPackageUri).request().get();
159 if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) {
160 return handleUnexpectedStatus("downloading VNF package", downloadPackageUri, remoteResponse);
162 byte[] payload = remoteResponse.readEntity(String.class).getBytes(StandardCharsets.ISO_8859_1);
163 Response.ResponseBuilder response = Response.ok(payload);
164 response.header(CONTENT_DISPOSITION, "attachment; filename=" + formatFilename(csarId));
165 LOGGER.debug("Response from VNF Repository for download package is success. URI={}", downloadPackageUri);
166 return response.build();
169 private Version getVersion(String vspId, String versionId) {
170 VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface();
171 return findVersion(versioningManager.list(vspId), versionId).orElse(new Version(versionId));
174 Optional<Version> findVersion(List<Version> versions, String requestedVersion) {
175 return versions.stream().filter(ver -> Objects.equals(ver.getId(), requestedVersion)).findAny();
178 private static Response handleUnexpectedStatus(String action, String uri, Response response) {
179 ErrorCode error = new GeneralErrorBuilder().build();
180 if (LOGGER.isErrorEnabled()) {
181 String body = response.hasEntity() ? response.readEntity(String.class) : "";
182 LOGGER.error("Unexpected response status while {}: URI={}, status={}, body={}", action, uri, response.getStatus(), body,
183 new CoreException(error));
185 return generateInternalServerError(error);
188 private static Response generateInternalServerError(ErrorCode error) {
189 ErrorCodeAndMessage payload = new ErrorCodeAndMessage(Response.Status.INTERNAL_SERVER_ERROR, error);
190 return Response.serverError().entity(payload).build();
193 private static String formatFilename(String csarId) {
194 return "temp_" + csarId + ".csar";
197 interface Configuration {
201 String getDownloadUri();
204 static class FileConfiguration implements Configuration {
207 public String getGetUri() {
208 return LazyFileConfiguration.INSTANCE.getGetUri();
212 public String getDownloadUri() {
213 return LazyFileConfiguration.INSTANCE.getDownloadUri();
216 private static class LazyFileConfiguration implements Configuration {
218 private static final String CONFIG_NAMESPACE = "vnfrepo";
219 private static final String DEFAULT_HOST = "localhost";
220 private static final String DEFAULT_PORT = "8702";
221 private static final String DEFAULT_URI_PREFIX = "/onapapi/vnfsdk-marketplace/v1/PackageResource/csars";
222 private static final String DEFAULT_LIST_URI = DEFAULT_URI_PREFIX + "/";
223 private static final String DEFAULT_DOWNLOAD_URI = DEFAULT_URI_PREFIX + "/%s/files";
224 private static final LazyFileConfiguration INSTANCE = new LazyFileConfiguration();
225 private final String getUri;
226 private final String downloadUri;
228 private LazyFileConfiguration() {
229 org.onap.config.api.Configuration config = ConfigurationManager.lookup();
230 String host = readConfig(config, "vnfRepoHost", DEFAULT_HOST);
231 String port = readConfig(config, "vnfRepoPort", DEFAULT_PORT);
232 String listPackagesUri = readConfig(config, "getVnfUri", DEFAULT_LIST_URI);
233 String downloadPackageUri = readConfig(config, "downloadVnfUri", DEFAULT_DOWNLOAD_URI);
234 this.getUri = formatUri(host, port, listPackagesUri);
235 this.downloadUri = formatUri(host, port, downloadPackageUri);
238 private String readConfig(org.onap.config.api.Configuration config, String key, String defaultValue) {
240 String value = config.getAsString(CONFIG_NAMESPACE, key);
241 return (value == null) ? defaultValue : value;
242 } catch (Exception e) {
243 LOGGER.error("Failed to read VNF repository configuration key '{}', default value '{}' will be used", key, defaultValue, e);
248 private static String formatUri(String host, String port, String path) {
249 return "https://" + host + ":" + port + (path.startsWith("/") ? path : "/" + path);
252 public String getGetUri() {
256 public String getDownloadUri() {