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