0e27d5704e9e252140947b8ba3cfea1ae3433c0b
[aai/model-loader.git] / src / main / java / org / onap / aai / modelloader / extraction / VnfCatalogExtractor.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.modelloader.extraction;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Enumeration;
26 import java.util.List;
27 import java.util.regex.Pattern;
28 import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
29 import org.apache.commons.compress.archivers.zip.ZipFile;
30 import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
31 import org.apache.commons.io.IOUtils;
32 import org.apache.commons.lang3.StringUtils;
33 import org.onap.aai.cl.api.Logger;
34 import org.onap.aai.cl.eelf.LoggerFactory;
35 import org.onap.aai.modelloader.entity.Artifact;
36 import org.onap.aai.modelloader.entity.ArtifactType;
37 import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifact;
38 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
39
40
41 /**
42  * The purpose of this class is to process a .csar file in the form of a byte array and extract VNF Catalog XML files
43  * from it.
44  *
45  * A .csar file is a compressed archive like a zip file and this class will treat the byte array as it if were a zip
46  * file.
47  */
48 public class VnfCatalogExtractor {
49     private static final Logger logger = LoggerFactory.getInstance().getLogger(VnfCatalogExtractor.class.getName());
50
51     private static final Pattern VNFCFILE_EXTENSION_REGEX =
52             Pattern.compile("(?i)artifacts([\\\\/])deployment([\\\\/])vnf_catalog([\\\\/]).*\\.xml$");
53
54     /**
55      * This method is responsible for filtering the contents of the supplied archive and returning a collection of
56      * {@link Artifact}s that represent the VNF Catalog files that have been found in the archive.<br>
57      * <br>
58      * If the archive contains no VNF Catalog files it will return an empty list.<br>
59      *
60      * @param archive the zip file in the form of a byte array containing zero or more VNF Catalog files
61      * @param name the name of the archive file
62      * @return List<Artifact> collection of VNF Catalog XML files found in the archive
63      * @throws InvalidArchiveException if an error occurs trying to extract the VNFC files from the archive or if the
64      *         archive is not a zip file
65      */
66     public List<Artifact> extract(byte[] archive, String name) throws InvalidArchiveException {
67         validateRequest(archive, name);
68
69         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Extracting CSAR archive: " + name);
70
71         List<Artifact> vnfcFiles = new ArrayList<>();
72         try (SeekableInMemoryByteChannel inMemoryByteChannel = new SeekableInMemoryByteChannel(archive);
73                 ZipFile zipFile = new ZipFile(inMemoryByteChannel)) {
74             for (Enumeration<ZipArchiveEntry> enumeration = zipFile.getEntries(); enumeration.hasMoreElements();) {
75                 ZipArchiveEntry entry = enumeration.nextElement();
76                 if (fileShouldBeExtracted(entry)) {
77                     vnfcFiles.add(new VnfCatalogArtifact(ArtifactType.VNF_CATALOG_XML,
78                             IOUtils.toString(zipFile.getInputStream(entry))));
79                 }
80             }
81         } catch (IOException e) {
82             throw new InvalidArchiveException(
83                     "An error occurred trying to create a ZipFile. Is the content being converted really a csar file?",
84                     e);
85         }
86
87         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, vnfcFiles.size() + " VNF Catalog files extracted.");
88
89         return vnfcFiles;
90     }
91
92     private static void validateRequest(byte[] archive, String name) throws InvalidArchiveException {
93         if (archive == null || archive.length == 0) {
94             throw new InvalidArchiveException("An archive must be supplied for processing.");
95         } else if (StringUtils.isBlank(name)) {
96             throw new InvalidArchiveException("The name of the archive must be supplied for processing.");
97         }
98     }
99
100     private static boolean fileShouldBeExtracted(ZipArchiveEntry entry) {
101         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Checking if " + entry.getName() + " should be extracted...");
102         boolean extractFile = VNFCFILE_EXTENSION_REGEX.matcher(entry.getName()).matches();
103         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Keeping file: " + entry.getName() + "? : " + extractFile);
104         return extractFile;
105     }
106 }
107