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