Merge 1806 code of vid-common
[vid.git] / vid-app-common / src / main / java / org / onap / vid / asdc / rest / RestfulAsdcClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
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.onap.vid.asdc.rest;
22
23 import com.att.eelf.configuration.EELFLogger;
24 import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
25 import org.onap.portalsdk.core.util.SystemProperties;
26 import org.onap.vid.asdc.AsdcCatalogException;
27 import org.onap.vid.asdc.AsdcClient;
28 import org.onap.vid.asdc.beans.Service;
29 import org.onap.vid.model.ModelConstants;
30 import org.onap.vid.properties.VidProperties;
31 import org.onap.vid.utils.Logging;
32 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
33 import org.springframework.http.HttpMethod;
34
35 import javax.ws.rs.ProcessingException;
36 import javax.ws.rs.WebApplicationException;
37 import javax.ws.rs.client.Client;
38 import javax.ws.rs.client.ResponseProcessingException;
39 import javax.ws.rs.core.MediaType;
40 import javax.ws.rs.core.MultivaluedHashMap;
41 import javax.ws.rs.core.Response;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.net.URI;
45 import java.nio.file.Files;
46 import java.nio.file.Path;
47 import java.nio.file.StandardCopyOption;
48 import java.util.Collections;
49 import java.util.UUID;
50
51 import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY;
52 /**
53  * The Class RestfulAsdcClient.
54  */
55 @SuppressWarnings("Duplicates")
56 public class RestfulAsdcClient implements AsdcClient {
57
58
59     /**
60      * The Class Builder.
61      */
62     public static class Builder {
63
64         /**
65          * The client.
66          */
67         private final Client client;
68
69         /**
70          * The uri.
71          */
72         private final URI uri;
73
74         /**
75          * The auth.
76          */
77         private String auth = null;
78
79         /**
80          * Instantiates a new builder.
81          *
82          * @param client the client
83          * @param uri    the uri
84          */
85         public Builder(Client client, URI uri) {
86             this.client = client;
87             this.client.register(JacksonJsonProvider.class);
88             this.uri = uri;
89         }
90
91         /**
92          * Auth.
93          *
94          * @param auth the auth
95          * @return the builder
96          */
97         public Builder auth(String auth) {
98             this.auth = auth;
99             return this;
100         }
101
102         /**
103          * Builds the.
104          *
105          * @return the restful asdc client
106          */
107         public RestfulAsdcClient build() {
108             return new RestfulAsdcClient(this);
109         }
110     }
111
112     /**
113      * The Constant LOG.
114      */
115     static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(RestfulAsdcClient.class);
116
117     final private static EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("asdc");
118
119     /**
120      * The client.
121      */
122     private final Client client;
123
124     /**
125      * The uri.
126      */
127     private final URI uri;
128
129     /**
130      * The common headers.
131      */
132     private final MultivaluedHashMap<String, Object> commonHeaders;
133
134     /**
135      * The auth.
136      */
137     private final String auth;
138
139     /**
140      * Instantiates a new restful asdc client.
141      *
142      * @param builder the builder
143      */
144     RestfulAsdcClient(Builder builder) {
145         client = builder.client;
146         uri = builder.uri;
147         auth = builder.auth;
148
149         commonHeaders = new MultivaluedHashMap<String, Object>();
150         commonHeaders.put("X-ECOMP-InstanceID", Collections.singletonList((Object) (SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME))));
151         commonHeaders.put("Authorization", Collections.singletonList((Object) (auth)));
152     }
153
154     private Path createTmpFile(InputStream csarInputStream) throws AsdcCatalogException {
155         final Path csarFile;
156         try {
157             csarFile = Files.createTempFile("csar", ".zip");
158             Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING);
159         } catch (IOException e) {
160             throw new AsdcCatalogException("Caught IOException while creating CSAR", e);
161         }
162         return csarFile;
163     }
164
165     /**
166      * Gets the client.
167      *
168      * @return the client
169      */
170     private Client getClient() {
171         return client;
172     }
173
174     /* (non-Javadoc)
175      * @see org.onap.vid.asdc.AsdcClient#getService(java.util.UUID)
176      */
177     public Service getService(UUID uuid) throws AsdcCatalogException {
178
179         String path = VidProperties.getPropertyWithDefault(
180                 ModelConstants.ASDC_SVC_API_PATH,
181                 ModelConstants.DEFAULT_ASDC_SVC_API_PATH);
182
183         String url = uri+path + "/" + uuid.toString() + "/metadata";
184         Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
185         try {
186             Response response = getClient()
187                     .target(uri)
188                     .path(path + "/" + uuid.toString() + "/metadata")
189                     .request(MediaType.APPLICATION_JSON)
190                     .headers(commonHeaders)
191                     .header(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId())
192                     .get();
193             Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response);
194             return response.readEntity(Service.class);
195         } catch (ResponseProcessingException e) {
196             //Couldn't convert response to Java type
197             throw new AsdcCatalogException("SDC response could not be processed", e);
198         } catch (ProcessingException e) {
199             //IO problems during request
200             throw new AsdcCatalogException("Failed to get a response from SDC service", e);
201         } catch (WebApplicationException e) {
202             //Web service returned data, but the response status wasn't a good one (i.e. non 2xx)
203             throw new AsdcCatalogException(e);
204         }
205     }
206
207
208     /* (non-Javadoc)
209      * @see org.onap.vid.asdc.AsdcClient#getServiceToscaModel(java.util.UUID)
210      */
211     public Path getServiceToscaModel(UUID serviceUuid) throws AsdcCatalogException {
212         String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_SVC_API_PATH,
213                 ModelConstants.DEFAULT_ASDC_SVC_API_PATH);
214
215         String url = uri+path + "/" + serviceUuid + "/toscaModel";
216         Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url);
217         try {
218             final InputStream csarInputStream = getClient()
219                     .target(uri)
220                     .path(path + "/" + serviceUuid + "/toscaModel")
221                     .request(MediaType.APPLICATION_OCTET_STREAM_TYPE)
222                     .headers(commonHeaders)
223                     .header("Content-Type", MediaType.APPLICATION_OCTET_STREAM)
224                     .header(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId())
225                     .get(InputStream.class);
226             Path toscaFilePath = createTmpFile(csarInputStream);
227             outgoingRequestsLogger.debug("Received {} {} . Tosca file was saved at: {}", HttpMethod.GET.name(), url, toscaFilePath.toAbsolutePath());
228             return toscaFilePath;
229         } catch (ResponseProcessingException e) {
230             //Couldn't convert response to Java type
231             throw new AsdcCatalogException("SDC response could not be processed", e);
232         } catch (ProcessingException e) {
233             //IO problems during request
234             throw new AsdcCatalogException("Failed to get a response from SDC service. Cause: "+e.getMessage(), e);
235         } catch (WebApplicationException e) {
236             //Web service returned data, but the response status wasn't a good one (i.e. non 2xx)
237             throw new AsdcCatalogException(e);
238         }
239     }
240
241 }
242