Sync Integ to Master
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / operations / impl / OnboardingClient.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.model.operations.impl;
22
23 import java.io.File;
24 import java.io.FileFilter;
25 import java.io.IOException;
26 import java.nio.file.Files;
27 import java.util.Map;
28 import java.util.Properties;
29
30 import org.apache.commons.io.filefilter.WildcardFileFilter;
31 import org.apache.http.HttpStatus;
32 import org.openecomp.sdc.be.config.Configuration.OnboardingConfig;
33 import org.openecomp.sdc.be.config.ConfigurationManager;
34 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
35 import org.openecomp.sdc.common.api.Constants;
36 import org.openecomp.sdc.common.http.client.api.HttpRequest;
37 import org.openecomp.sdc.common.http.client.api.HttpResponse;
38 import org.openecomp.sdc.common.util.ZipUtil;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import fj.data.Either;
43
44 @org.springframework.stereotype.Component("onboarding-client")
45 public class OnboardingClient {
46
47         private static Logger log = LoggerFactory.getLogger(OnboardingClient.class.getName());
48
49         private static Properties downloadCsarHeaders = new Properties();
50
51         static {
52                 downloadCsarHeaders.put("Accept", "application/octet-stream");
53         }
54
55         public OnboardingClient() {
56                 super();
57         }
58
59         public static void main(String[] args) {
60
61                 OnboardingClient csarOperation = new OnboardingClient();
62
63                 String csarUuid = "70025CF6081B489CA7B1CBA583D5278D";
64                 Either<Map<String, byte[]>, StorageOperationStatus> csar = csarOperation.getCsar(csarUuid, null);
65                 System.out.println(csar.left().value());
66
67         }
68
69         public Either<Map<String, byte[]>, StorageOperationStatus> getMockCsar(String csarUuid) {
70                 File dir = new File("/var/tmp/mockCsar");
71                 FileFilter fileFilter = new WildcardFileFilter("*.csar");
72                 File[] files = dir.listFiles(fileFilter);
73                 for (int i = 0; i < files.length; i++) {
74                         File csar = files[i];
75                         if (csar.getName().startsWith(csarUuid)) {
76                                 log.debug("Found CSAR file {} matching the passed csarUuid {}", csar.getAbsolutePath(), csarUuid);
77                                 byte[] data;
78                                 try {
79                                         data = Files.readAllBytes(csar.toPath());
80                                 } catch (IOException e) {
81                                         log.debug("Error reading mock file for CSAR, error: {}", e);
82                                         return Either.right(StorageOperationStatus.NOT_FOUND);
83                                 }
84                                 Map<String, byte[]> readZip = ZipUtil.readZip(data);
85                                 return Either.left(readZip);
86                         }
87                 }
88                 log.debug("Couldn't find mock file for CSAR starting with {}", csarUuid);
89                 return Either.right(StorageOperationStatus.NOT_FOUND);
90         }
91
92         public Either<Map<String, byte[]>, StorageOperationStatus> getCsar(String csarUuid, String userId) {
93                 String url = buildDownloadCsarUrl() + "/" + csarUuid;
94
95                 Properties headers = new Properties();
96                 if (downloadCsarHeaders != null) {
97                         downloadCsarHeaders.forEach((k, v) -> headers.put(k, v));
98                 }
99
100                 if (userId != null) {
101                         headers.put(Constants.USER_ID_HEADER, userId);
102                 }
103
104                 log.debug("Url for downloading csar is {}. Headers are {}", url, headers);
105
106                 try {
107                 HttpResponse<byte []> httpResponse = HttpRequest.getAsByteArray(url, headers);
108                 log.debug("After fetching csar {}. Http return code is {}", csarUuid, httpResponse.getStatusCode());
109     
110                 switch (httpResponse.getStatusCode()) {
111                 case HttpStatus.SC_OK:
112                         byte[] data = httpResponse.getResponse();
113                         if (data != null && data.length > 0) {
114                                 Map<String, byte[]> readZip = ZipUtil.readZip(data);
115                                 return Either.left(readZip);
116                         } else {
117                                 log.debug("Data received from rest is null or empty");
118                                 return Either.right(StorageOperationStatus.NOT_FOUND);
119                         }
120     
121                 case HttpStatus.SC_NOT_FOUND:
122                         return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
123     
124                 default:
125                         return Either.right(StorageOperationStatus.GENERAL_ERROR);
126                 }
127                 }
128                 catch(Exception e) {
129                     log.debug("Request failed with exception {}", e);
130                     return Either.right(StorageOperationStatus.GENERAL_ERROR);
131                 }
132         }
133         
134         public Either<String, StorageOperationStatus> getPackages(String userId) {
135                 String url = buildDownloadCsarUrl();
136
137                 Properties headers = new Properties();
138                 headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
139
140                 if (userId != null) {
141                         headers.put(Constants.USER_ID_HEADER, userId);
142                 }
143
144                 log.debug("Url for downloading packages is {}. Headers are {}", url, headers);
145
146                 try {
147                 HttpResponse<String> httpResposne = HttpRequest.get(url, headers);
148                 log.debug("After fetching packages. Http return code is {}", httpResposne.getStatusCode());
149     
150                 switch (httpResposne.getStatusCode()) {
151                 case HttpStatus.SC_OK:
152                         String data = httpResposne.getResponse();
153                         return Either.left(data);
154     
155                 case HttpStatus.SC_NOT_FOUND:
156                         return Either.right(StorageOperationStatus.CSAR_NOT_FOUND);
157     
158                 default:
159                         return Either.right(StorageOperationStatus.GENERAL_ERROR);
160                 }
161                 }
162                 catch(Exception e) {
163             log.debug("Request failed with exception {}", e);
164             return Either.right(StorageOperationStatus.GENERAL_ERROR);
165                 }
166         }
167
168         /**
169          * Build the url for download CSAR
170          * 
171          * E.g., http://0.0.0.0:8181/onboarding-api/v1.0/vendor-software-products/packages/
172          * 
173          * @return
174          */
175         public String buildDownloadCsarUrl() {
176
177                 OnboardingConfig onboardingConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getOnboarding();
178
179                 String protocol = onboardingConfig.getProtocol();
180                 String host = onboardingConfig.getHost();
181                 Integer port = onboardingConfig.getPort();
182                 String uri = onboardingConfig.getDownloadCsarUri();
183
184                 String getCsarUrl = protocol + "://" + host + ":" + port + uri;
185
186                 return getCsarUrl;
187         }
188
189 }