96be59123e346e133aaba9144b74118b60328702
[vid.git] / vid-app-common / src / main / java / org / onap / vid / asdc / rest / SdcRestClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2018 - 2019 Nokia. 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.onap.vid.asdc.rest;
22
23 import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
24 import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM;
25 import static org.onap.portalsdk.core.util.SystemProperties.APP_DISPLAY_NAME;
26 import static org.onap.vid.asdc.AsdcClient.URIS.METADATA_URL_TEMPLATE;
27 import static org.onap.vid.asdc.AsdcClient.URIS.TOSCA_MODEL_URL_TEMPLATE;
28 import static org.onap.vid.client.SyncRestClientInterface.HEADERS.AUTHORIZATION;
29 import static org.onap.vid.client.SyncRestClientInterface.HEADERS.CONTENT_TYPE;
30 import static org.onap.vid.client.SyncRestClientInterface.HEADERS.X_ECOMP_INSTANCE_ID;
31 import static org.onap.vid.client.UnirestPatchKt.extractRawAsString;
32 import static org.onap.vid.logging.Headers.PARTNER_NAME;
33 import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY;
34
35 import com.att.eelf.configuration.EELFLogger;
36 import com.google.common.collect.ImmutableMap;
37 import io.joshworks.restclient.http.HttpResponse;
38 import io.vavr.control.Try;
39 import java.io.IOException;
40 import java.io.InputStream;
41 import java.nio.file.Files;
42 import java.nio.file.Path;
43 import java.nio.file.StandardCopyOption;
44 import java.util.Collections;
45 import java.util.Map;
46 import java.util.UUID;
47 import javax.ws.rs.ProcessingException;
48 import javax.ws.rs.client.ResponseProcessingException;
49 import org.onap.portalsdk.core.util.SystemProperties;
50 import org.onap.vid.aai.ExceptionWithRequestInfo;
51 import org.onap.vid.aai.HttpResponseWithRequestInfo;
52 import org.onap.vid.asdc.AsdcCatalogException;
53 import org.onap.vid.asdc.AsdcClient;
54 import org.onap.vid.asdc.beans.Service;
55 import org.onap.vid.client.SyncRestClientInterface;
56 import org.onap.vid.model.ModelConstants;
57 import org.onap.vid.properties.VidProperties;
58 import org.onap.vid.utils.Logging;
59 import org.springframework.http.HttpMethod;
60
61 public class SdcRestClient implements AsdcClient {
62
63     private String baseUrl;
64     private String path;
65     private String auth;
66     private static final EELFLogger LOGGER = Logging.getRequestsLogger("sdc");
67
68     private SyncRestClientInterface syncRestClient;
69     private Logging loggingService;
70
71
72     public SdcRestClient(String baseUrl, String auth, SyncRestClientInterface client, Logging loggingService) {
73         this.syncRestClient = client;
74         this.auth = auth;
75         this.baseUrl = baseUrl;
76         this.path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_SVC_API_PATH, ModelConstants.DEFAULT_ASDC_SVC_API_PATH);
77         this.loggingService = loggingService;
78     }
79
80
81     @Override
82     public Service getService(UUID uuid) throws AsdcCatalogException {
83         String finalUrl = String.format(METADATA_URL_TEMPLATE, baseUrl, path, uuid);
84         loggingService.logRequest(LOGGER, HttpMethod.GET, finalUrl);
85
86         return Try
87                 .of(() -> syncRestClient.get(finalUrl, prepareHeaders(auth, APPLICATION_JSON), Collections.emptyMap(), Service.class))
88                 .getOrElseThrow(AsdcCatalogException::new)
89                 .getBody();
90
91     }
92
93     @Override
94     public Path getServiceToscaModel(UUID uuid) throws AsdcCatalogException {
95         try {
96             HttpResponseWithRequestInfo<InputStream> responseWithRequestInfo = getServiceInputStream(uuid, false);
97
98             if (responseWithRequestInfo.getResponse().getStatus()>399) {
99                 loggingService.logRequest(LOGGER, HttpMethod.GET,
100                     responseWithRequestInfo.getRequestUrl(), responseWithRequestInfo.getResponse());
101
102                 String body = extractRawAsString(responseWithRequestInfo.getResponse());
103                 throw new AsdcCatalogException(String.format("Http bad status code: %s, body: %s",
104                     responseWithRequestInfo.getResponse().getStatus(),
105                     body));
106             }
107
108             final InputStream csarInputStream = responseWithRequestInfo.getResponse().getBody();
109             Path toscaFilePath = createTmpFile(csarInputStream);
110             LOGGER.debug("Received {} {} . Tosca file was saved at: {}",
111                 responseWithRequestInfo.getRequestHttpMethod().name(),
112                 responseWithRequestInfo.getRequestUrl(),
113                 toscaFilePath.toAbsolutePath());
114             return toscaFilePath;
115         } catch (ResponseProcessingException e) {
116             //Couldn't convert response to Java type
117             throw new AsdcCatalogException("ASDC response could not be processed", e);
118         } catch (ProcessingException e) {
119             //IO problems during request
120             throw new AsdcCatalogException("Failed to get a response from ASDC service. Cause: " + e.getMessage(), e);
121         } catch (RuntimeException e) {
122             throw new AsdcCatalogException(e);
123         }
124     }
125
126     @Override
127     public HttpResponseWithRequestInfo<InputStream> getServiceInputStream(UUID serviceUuid, boolean warpException) {
128         String finalUrl = String.format(TOSCA_MODEL_URL_TEMPLATE, baseUrl, path, serviceUuid);
129         loggingService.logRequest(LOGGER, HttpMethod.GET, finalUrl);
130         try {
131             HttpResponse<InputStream> httpResponse = syncRestClient.getStream(finalUrl, prepareHeaders(auth, APPLICATION_OCTET_STREAM), Collections.emptyMap());
132             return new HttpResponseWithRequestInfo<>(httpResponse, finalUrl, HttpMethod.GET);
133         }
134         catch (RuntimeException exception) {
135             throw warpException ? new ExceptionWithRequestInfo(HttpMethod.GET, finalUrl, exception) : exception;
136         }
137     }
138
139
140     @Override
141     public HttpResponse<String> checkSDCConnectivity() {
142         String finalUrl = baseUrl + URIS.HEALTH_CHECK_ENDPOINT;
143
144         return syncRestClient
145                 .get(finalUrl, prepareHeaders(auth, APPLICATION_JSON), Collections.emptyMap(), String.class);
146     }
147
148     @Override
149     public String getBaseUrl() {
150         return baseUrl;
151     }
152
153     private Map<String, String> prepareHeaders(String auth, String contentType) {
154         return ImmutableMap.of(
155                 X_ECOMP_INSTANCE_ID, SystemProperties.getProperty(APP_DISPLAY_NAME),
156                 PARTNER_NAME.getHeaderName(), PARTNER_NAME.getHeaderValue(),
157                 AUTHORIZATION, auth,
158                 REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId(),
159                 CONTENT_TYPE, contentType
160         );
161     }
162
163     private Path createTmpFile(InputStream csarInputStream) throws AsdcCatalogException {
164         return Try
165                 .of(() -> tryToCreateTmpFile(csarInputStream))
166                 .getOrElseThrow(throwable -> new AsdcCatalogException("Caught IOException while creating CSAR", throwable));
167     }
168
169     private Path tryToCreateTmpFile(InputStream csarInputStream) throws IOException {
170         Path csarFile = Files.createTempFile("csar", ".zip");
171         Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING);
172
173         LOGGER.debug("Tosca file was saved at: {} ", csarFile.toAbsolutePath());
174
175         return csarFile;
176     }
177 }