org.onap migration
[vid.git] / vid-app-common / src / main / java / org / onap / vid / asdc / memory / InMemoryAsdcClient.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.memory;
22
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.StandardCopyOption;
28 import java.util.Collection;
29 import java.util.LinkedList;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.UUID;
33 import java.util.zip.ZipFile;
34
35 import org.codehaus.jackson.JsonParseException;
36 import org.codehaus.jackson.map.JsonMappingException;
37 import org.codehaus.jackson.map.ObjectMapper;
38 import org.json.JSONArray;
39 import org.json.JSONObject;
40 import org.yaml.snakeyaml.Yaml;
41
42 import org.onap.vid.asdc.AsdcCatalogException;
43 import org.onap.vid.asdc.AsdcClient;
44 import org.onap.vid.asdc.beans.Artifact;
45 import org.onap.vid.asdc.beans.Resource;
46 import org.onap.vid.asdc.beans.Service;
47 import org.onap.vid.asdc.beans.tosca.ToscaCsar;
48 import org.onap.vid.asdc.beans.tosca.ToscaMeta;
49 import org.onap.vid.asdc.beans.tosca.ToscaModel;
50
51 /**
52  * The Class InMemoryAsdcClient.
53  */
54 public class InMemoryAsdcClient implements AsdcClient {
55
56         /** The catalog. */
57         private final JSONObject catalog;
58         
59         /** The mapper. */
60         private final ObjectMapper mapper;
61
62         /**
63          * The Class Builder.
64          */
65         public static class Builder {
66                 
67                 /** The catalog. */
68                 private JSONObject catalog = new JSONObject()
69                                                                                 .put("resources", new JSONObject())
70                                                                                 .put("services", new JSONObject());
71                 
72                 /** The mapper. */
73                 private ObjectMapper mapper = new ObjectMapper();
74
75                 /**
76                  * Instantiates a new builder.
77                  */
78                 public Builder() {}
79                 
80                 /**
81                  * Catalog.
82                  *
83                  * @param catalog the catalog
84                  * @return the builder
85                  */
86                 public Builder catalog(JSONObject catalog) {
87                         this.catalog = catalog;
88                         return this;
89                 }
90                 
91                 /**
92                  * Mapper.
93                  *
94                  * @param mapper the mapper
95                  * @return the builder
96                  */
97                 public Builder mapper(ObjectMapper mapper) {
98                         this.mapper = mapper;
99                         return this;
100                 }
101                 
102                 /**
103                  * Builds the.
104                  *
105                  * @return the in memory sdc client
106                  */
107                 public InMemoryAsdcClient build() {
108                         return new InMemoryAsdcClient(this);
109                 }
110         }
111         
112         /**
113          * Instantiates a new in memory sdc client.
114          *
115          * @param builder the builder
116          */
117         private InMemoryAsdcClient(Builder builder) {
118                 catalog = builder.catalog;
119                 mapper = builder.mapper;
120         }
121         
122         /**
123          * Gets the catalog.
124          *
125          * @return the catalog
126          */
127         private JSONObject getCatalog() {
128                 return catalog;
129         }
130         
131         /**
132          * Gets the mapper.
133          *
134          * @return the mapper
135          */
136         private ObjectMapper getMapper() {
137                 return mapper;
138         }
139         
140         /**
141          * Convert.
142          *
143          * @param <T> the generic type
144          * @param json the json
145          * @param clazz the clazz
146          * @return the t
147          * @throws AsdcCatalogException the sdc catalog exception
148          */
149         private <T> T convert(JSONObject json, Class<T> clazz) throws AsdcCatalogException {
150                 try {
151                         return getMapper().readValue(json.toString(), clazz);
152                 } catch (JsonParseException e) {
153                         throw new AsdcCatalogException("Failed to parse SDC response (bad data)", e);
154                 } catch (JsonMappingException e) {
155                         throw new AsdcCatalogException("Failed to map SDC response to internal VID data structure(s)", e);
156                 } catch (IOException e) {
157                         throw new AsdcCatalogException("Failed to get a response from SDC", e);
158                 }
159         }
160         
161         /* (non-Javadoc)
162          * @see org.openecomp.vid.asdc.AsdcClient#getResource(java.util.UUID)
163          */
164         public Resource getResource(UUID uuid) throws AsdcCatalogException {
165                 final JSONObject resource = getCatalog().getJSONObject("resources")
166                                                                                 .getJSONObject(uuid.toString());
167                 return convert(resource, Resource.class);
168         }
169
170         /* (non-Javadoc)
171          */
172         public Collection<Resource> getResources() throws AsdcCatalogException {
173                 final Collection<Resource> resources = new LinkedList<Resource> ();
174                 
175                 for (String key : getCatalog().getJSONObject("resources").keySet()) {
176                         final JSONObject json = getCatalog().getJSONObject("resources").getJSONObject(key);
177                         final Resource resource = convert(json, Resource.class);
178                         resources.add(resource);
179                 }
180                 
181                 return resources;
182         }
183
184         /* (non-Javadoc)
185          * @see org.openecomp.vid.asdc.AsdcClient#getResources(java.util.Map)
186          */
187         public Collection<Resource> getResources(Map<String, String[]> filter) throws AsdcCatalogException {
188                 final Collection<Resource> resources = new LinkedList<Resource> ();
189                 
190                 for (String key : getCatalog().getJSONObject("resources").keySet()) {
191                         final JSONObject json = getCatalog().getJSONObject("resources").getJSONObject(key);
192                         
193                         boolean filterMatch = true;
194                         
195                         for (Entry<String, String[]> entry : filter.entrySet()) {
196                                 for (int i = 0; i < entry.getValue().length; i++) {
197                                         if (!json.getString(entry.getKey()).equals(entry.getValue()[i])) {
198                                                 filterMatch = false;
199                                                 break;
200                                         }
201                                 }
202                         }
203                         
204                         if (filterMatch) resources.add(convert(json, Resource.class));
205                 }
206                 
207                 return resources;
208         }
209
210         /* (non-Javadoc)
211          * @see org.openecomp.vid.asdc.AsdcClient#getService(java.util.UUID)
212          */
213         public Service getService(UUID uuid) throws AsdcCatalogException {
214                 final JSONObject service = getCatalog().getJSONObject("services")
215                                 .getJSONObject(uuid.toString());
216                 return convert(service, Service.class);
217         }
218
219         /* (non-Javadoc)
220          * @see org.openecomp.vid.asdc.AsdcClient#getServices()
221          */
222         public Collection<Service> getServices() throws AsdcCatalogException {
223                 final Collection<Service> services = new LinkedList<Service> ();
224                 
225                 for (String key : getCatalog().getJSONObject("services").keySet()) {
226                         final JSONObject json = getCatalog().getJSONObject("services").getJSONObject(key);
227                         final Service service = convert(json, Service.class);
228                         services.add(service);
229                 }
230                 
231                 return services;
232         }
233
234         /* (non-Javadoc)
235          * @see org.openecompt.vid.asdc.AsdcClient#getServices(java.util.Map)
236          */
237         public Collection<Service> getServices(Map<String, String[]> filter) throws AsdcCatalogException {
238                 final Collection<Service> services = new LinkedList<Service> ();
239                 
240                 for (String key : getCatalog().getJSONObject("services").keySet()) {
241                         final JSONObject json = getCatalog().getJSONObject("services").getJSONObject(key);
242                         
243                         boolean filterMatch = true;
244                         
245                         for (Entry<String, String[]> entry : filter.entrySet()) {
246                                 for (int i = 0; i < entry.getValue().length; i++) {
247                                         if (!json.getString(entry.getKey()).equals(entry.getValue()[i])) {
248                                                 filterMatch = false;
249                                                 break;
250                                         }
251                                 }
252                         }
253                         
254                         if (filterMatch) services.add(convert(json, Service.class));
255                 }
256                 
257                 return services;
258         }
259
260         /* (non-Javadoc)
261          * @see org.openecomp.vid.asdc.AsdcClient#getResourceArtifact(java.util.UUID, java.util.UUID)
262          */
263         public Artifact getResourceArtifact(UUID resourceUuid, UUID artifactUuid) throws AsdcCatalogException {
264                 final JSONArray artifacts = getCatalog().getJSONObject("resources")
265                                 .getJSONObject(resourceUuid.toString())
266                                 .getJSONArray("artifacts");
267                 
268                 for (int i = 0; i < artifacts.length(); i++) {
269                         final JSONObject artifact = artifacts.getJSONObject(i);
270                         
271                         if (artifact.getString("artifactUUID").equals(artifactUuid.toString())) {
272                                 return convert(artifact, Artifact.class);
273                         }
274                 }
275                 
276                 return null;
277         }
278
279         /* (non-Javadoc)
280          * @see org.openecomp.vid.asdc.AsdcClient#getServiceArtifact(java.util.UUID, java.util.UUID)
281          */
282         public Artifact getServiceArtifact(UUID serviceUuid, UUID artifactUuid) throws AsdcCatalogException {
283                 final JSONArray artifacts = getCatalog().getJSONObject("services")
284                                 .getJSONObject(serviceUuid.toString())
285                                 .getJSONArray("artifacts");
286                 
287                 for (int i = 0; i < artifacts.length(); i++) {
288                         final JSONObject artifact = artifacts.getJSONObject(i);
289                         
290                         if (artifact.getString("artifactUUID").equals(artifactUuid.toString())) {
291                                 return convert(artifact, Artifact.class);
292                         }
293                 }
294                 
295                 return null;
296         }
297
298         /* (non-Javadoc)
299          * @see org.openecomp.vid.asdc.AsdcClient#getResourceToscaModel(java.util.UUID)
300          */
301         public Path getResourceToscaModel(UUID resourceUuid) throws AsdcCatalogException {
302                 final String toscaModelURL = getCatalog().getJSONObject("resources")
303                                 .getJSONObject(resourceUuid.toString())
304                                 .getString("toscaModelURL");
305
306
307                 final InputStream toscaModelStream = getClass().getClassLoader().getResourceAsStream(toscaModelURL);
308                 
309                 if (toscaModelStream == null) return null;
310                 
311                 return null;//getToscaModel(toscaModelStream);
312         }
313
314         /* (non-Javadoc)
315          * @see org.openecomp.vid.asdc.AsdcClient#getServiceToscaModel(java.util.UUID)
316          */
317         public Path getServiceToscaModel(UUID serviceUuid) throws AsdcCatalogException {
318                 final String toscaModelURL = getCatalog().getJSONObject("services")
319                                                 .getJSONObject(serviceUuid.toString())
320                                                 .getString("toscaModelURL");
321                 
322                 final InputStream toscaModelStream = getClass().getClassLoader().getResourceAsStream(toscaModelURL);
323                 
324                 if (toscaModelStream == null) return null;
325                 
326                 return null;//getToscaModel(toscaModelStream);
327         }
328
329         /**
330          * Gets the tosca model.
331          *
332          * @param csarInputStream the csar input stream
333          * @return the tosca model
334          * @throws AsdcCatalogException the asdc catalog exception
335          */
336         private ToscaCsar getToscaModel(InputStream csarInputStream) throws AsdcCatalogException {
337                 final Path csarFile;
338                 
339                 try {
340                         csarFile = Files.createTempFile("csar", ".zip");
341                         Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING);
342                 } catch (IOException e) {
343                         throw new AsdcCatalogException("Caught IOException while creating CSAR", e);
344                 }
345                 
346                 try (final ZipFile csar = new ZipFile(csarFile.toFile())) {
347                         
348                         final InputStream toscaMetaStream = csar.getInputStream(csar.getEntry("TOSCA-Metadata/TOSCA.meta"));
349                         final ToscaMeta toscaMeta = new ToscaMeta.Builder(toscaMetaStream).build();
350                         final String entryDefinitions = toscaMeta.get("Entry-Definitions");
351                         final InputStream toscaParentEntryYamlStream = csar.getInputStream(csar.getEntry(entryDefinitions));
352                         
353                         final Yaml yaml = new Yaml();
354                         final ToscaModel parentModel = yaml.loadAs(toscaParentEntryYamlStream, ToscaModel.class);
355
356                         final ToscaCsar.Builder csarBuilder = new ToscaCsar.Builder(parentModel);
357                         
358                         for (Map<String, Map<String, String>> imports : parentModel.getImports()) {
359                                 for (Entry<String, Map<String, String>> entry : imports.entrySet()) {
360                                         final InputStream toscaChildEntryYamlStream = csar.getInputStream(csar.getEntry("Definitions/" + entry.getValue().get("file")));
361                                         final ToscaModel childModel = yaml.loadAs(toscaChildEntryYamlStream, ToscaModel.class);
362                                         csarBuilder.addVnf(childModel);
363                                 }
364                         }
365                         
366                         return csarBuilder.build();
367                 } catch (IOException e) {
368                         throw new AsdcCatalogException("Caught IOException while processing CSAR", e);
369                 }
370         }
371
372 }