15d77a1966b4a26add5b92f4fd3f5824a963c7f8
[aai/babel.git] / src / main / java / org / onap / aai / babel / csar / extractor / YamlExtractor.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.babel.csar.extractor;
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.babel.logging.ApplicationMsgs;
34 import org.onap.aai.babel.logging.LogHelper;
35 import org.onap.aai.babel.xml.generator.ModelGenerator;
36 import org.onap.aai.babel.xml.generator.data.Artifact;
37 import org.onap.aai.cl.api.Logger;
38
39 /**
40  * This class extracts YAML files from CSAR (compressed archive) content.
41  *
42  */
43 public class YamlExtractor {
44     private static Logger logger = LogHelper.INSTANCE;
45
46     private static final Pattern YAMLFILE_EXTENSION_REGEX = Pattern.compile("(?i).*\\.ya?ml$");
47
48     /**
49      * This method is responsible for filtering the contents of the supplied archive and returning a collection of
50      * {@link Artifact}s that represent the YAML files that have been found in the archive.
51      *
52      * @param archive
53      *            the compressed archive in the form of a byte array, expected to contain one or more YAML files
54      * @param name
55      *            the name of the archive
56      * @param version
57      *            the version of the archive
58      * @return List<Artifact> collection of YAML artifacts found in the archive
59      * @throws InvalidArchiveException
60      *             if an error occurs trying to extract the YAML file(s) from the archive, or no files were found
61      */
62     public List<Artifact> extract(byte[] archive, String name, String version) throws InvalidArchiveException {
63         validateRequest(archive, name, version);
64
65         logger.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Extracting CSAR archive: " + name);
66
67         List<Artifact> ymlFiles = new ArrayList<>();
68         try (SeekableInMemoryByteChannel inMemoryByteChannel = new SeekableInMemoryByteChannel(archive);
69                 ZipFile zipFile = new ZipFile(inMemoryByteChannel)) {
70             for (Enumeration<ZipArchiveEntry> enumeration = zipFile.getEntries(); enumeration.hasMoreElements();) {
71                 ZipArchiveEntry entry = enumeration.nextElement();
72                 if (fileShouldBeExtracted(entry)) {
73                     ymlFiles.add(ModelGenerator.createArtifact(IOUtils.toByteArray(zipFile.getInputStream(entry)),
74                             entry.getName(), version));
75                 }
76             }
77             if (ymlFiles.isEmpty()) {
78                 throw new InvalidArchiveException("No valid YAML files were found in the csar file.");
79             }
80         } catch (IOException e) {
81             throw new InvalidArchiveException(
82                     "An error occurred trying to create a ZipFile. Is the content being converted really a csar file?",
83                     e);
84         }
85
86         logger.debug(ApplicationMsgs.DISTRIBUTION_EVENT, ymlFiles.size() + " YAML files extracted.");
87
88         return ymlFiles;
89     }
90
91     /**
92      * Throw an error if the supplied parameters are not valid.
93      * 
94      * @param archive
95      * @param name
96      * @param version
97      * @throws InvalidArchiveException
98      */
99     private void validateRequest(byte[] archive, String name, String version) throws InvalidArchiveException {
100         if (archive == null || archive.length == 0) {
101             throw new InvalidArchiveException("An archive must be supplied for processing.");
102         } else if (StringUtils.isBlank(name)) {
103             throw new InvalidArchiveException("The name of the archive must be supplied for processing.");
104         } else if (StringUtils.isBlank(version)) {
105             throw new InvalidArchiveException("The version must be supplied for processing.");
106         }
107     }
108
109     /**
110      * Determine whether the file name matches the pattern for YAML content.
111      *
112      * @param entry
113      *            the entry
114      * @return true, if successful
115      */
116     private boolean fileShouldBeExtracted(ZipArchiveEntry entry) {
117         boolean extractFile = YAMLFILE_EXTENSION_REGEX.matcher(entry.getName()).matches();
118         logger.debug(ApplicationMsgs.DISTRIBUTION_EVENT, "Extraction of " + entry.getName() + "=" + extractFile);
119         return extractFile;
120     }
121 }