Upgrade spring-boot to 2.7.X in model-loader
[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.nio.charset.Charset;
25 import java.util.ArrayList;
26 import java.util.Enumeration;
27 import java.util.List;
28 import java.util.regex.Pattern;
29
30 import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
31 import org.apache.commons.compress.archivers.zip.ZipFile;
32 import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
33 import org.apache.commons.io.IOUtils;
34 import org.apache.commons.lang3.StringUtils;
35 import org.onap.aai.cl.api.Logger;
36 import org.onap.aai.cl.eelf.LoggerFactory;
37 import org.onap.aai.modelloader.entity.Artifact;
38 import org.onap.aai.modelloader.entity.ArtifactType;
39 import org.onap.aai.modelloader.entity.catalog.VnfCatalogArtifact;
40 import org.onap.aai.modelloader.service.ModelLoaderMsgs;
41 import org.springframework.stereotype.Component;
42
43
44 /**
45  * The purpose of this class is to process a .csar file in the form of a byte array and extract VNF Catalog XML files
46  * from it.
47  *
48  * 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
49  * file.
50  */
51 @Component
52 public class VnfCatalogExtractor {
53     private static final Logger logger = LoggerFactory.getInstance().getLogger(VnfCatalogExtractor.class.getName());
54
55     private static final Pattern VNFCFILE_EXTENSION_REGEX =
56             Pattern.compile("(?i)artifacts([\\\\/])deployment([\\\\/])vnf_catalog([\\\\/]).*\\.xml$");
57
58     /**
59      * This method is responsible for filtering the contents of the supplied archive and returning a collection of
60      * {@link Artifact}s that represent the VNF Catalog files that have been found in the archive.<br>
61      * <br>
62      * If the archive contains no VNF Catalog files it will return an empty list.<br>
63      *
64      * @param archive the zip file in the form of a byte array containing zero or more VNF Catalog files
65      * @param name the name of the archive file
66      * @return List<Artifact> collection of VNF Catalog XML files found in the archive
67      * @throws InvalidArchiveException if an error occurs trying to extract the VNFC files from the archive or if the
68      *         archive is not a zip file
69      */
70     public List<Artifact> extract(byte[] archive, String name) throws InvalidArchiveException {
71         validateRequest(archive, name);
72
73         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Extracting CSAR archive: " + name);
74
75         List<Artifact> vnfcFiles = new ArrayList<>();
76         try (SeekableInMemoryByteChannel inMemoryByteChannel = new SeekableInMemoryByteChannel(archive);
77                 ZipFile zipFile = new ZipFile(inMemoryByteChannel)) {
78             for (Enumeration<ZipArchiveEntry> enumeration = zipFile.getEntries(); enumeration.hasMoreElements();) {
79                 ZipArchiveEntry entry = enumeration.nextElement();
80                 if (fileShouldBeExtracted(entry)) {
81                     vnfcFiles.add(new VnfCatalogArtifact(ArtifactType.VNF_CATALOG_XML,
82                             IOUtils.toString(zipFile.getInputStream(entry), Charset.defaultCharset())));
83                 }
84             }
85         } catch (IOException e) {
86             throw new InvalidArchiveException(
87                     "An error occurred trying to create a ZipFile. Is the content being converted really a csar file?",
88                     e);
89         }
90
91         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, vnfcFiles.size() + " VNF Catalog files extracted.");
92
93         return vnfcFiles;
94     }
95
96     private static void validateRequest(byte[] archive, String name) throws InvalidArchiveException {
97         if (archive == null || archive.length == 0) {
98             throw new InvalidArchiveException("An archive must be supplied for processing.");
99         } else if (StringUtils.isBlank(name)) {
100             throw new InvalidArchiveException("The name of the archive must be supplied for processing.");
101         }
102     }
103
104     private static boolean fileShouldBeExtracted(ZipArchiveEntry entry) {
105         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Checking if " + entry.getName() + " should be extracted...");
106         boolean extractFile = VNFCFILE_EXTENSION_REGEX.matcher(entry.getName()).matches();
107         logger.debug(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Keeping file: " + entry.getName() + "? : " + extractFile);
108         return extractFile;
109     }
110 }
111