Replaced all tabs with spaces in java and pom.xml
[so.git] / adapters / mso-openstack-adapters / src / main / java / org / onap / so / adapters / vnf / CSAR.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2018 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.so.adapters.vnf;
22
23 import java.io.ByteArrayOutputStream;
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.OutputStream;
29 import java.io.PrintStream;
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.zip.ZipEntry;
33 import java.util.zip.ZipOutputStream;
34 import org.onap.so.adapters.vdu.VduArtifact;
35 import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
36 import org.onap.so.adapters.vdu.VduModelInfo;
37 import org.onap.so.adapters.vnf.exceptions.VnfException;
38 import com.google.common.io.Files;
39
40 /**
41  * The purpose of this class is to create a CSAR byte array from Vdu inputs for the purpose of forwarding to a TOSCA
42  * orchestrator.
43  * 
44  * @author DeWayne
45  *
46  */
47 public class CSAR {
48     private static final String MANIFEST_FILENAME = "MANIFEST.MF";
49     private VduModelInfo vduModel;
50
51     public CSAR(VduModelInfo model) {
52         this.vduModel = model;
53     }
54
55     /**
56      * Creates a byte array representation of a CSAR corresponding to the VduBlueprint arg in the constructor.
57      * 
58      * @return
59      * @throws VnfException
60      */
61     public byte[] create() {
62         File dir = Files.createTempDir();
63
64         /**
65          * Create subdir
66          */
67         File metadir = new File(dir.getAbsolutePath() + "/TOSCA-Metadata");
68         if (!metadir.mkdir()) {
69             throw new RuntimeException("CSAR TOSCA-Metadata directory create failed");
70         }
71
72         /**
73          * Organize model info for consumption
74          */
75         VduArtifact mainTemplate = null;
76         List<VduArtifact> extraFiles = new ArrayList<>();
77         for (VduArtifact artifact : vduModel.getArtifacts()) {
78             if (artifact.getType() == ArtifactType.MAIN_TEMPLATE) {
79                 mainTemplate = artifact;
80             } else {
81                 extraFiles.add(artifact);
82             }
83         }
84
85         if (mainTemplate == null) { // make a dummy to avoid null pointers
86             mainTemplate = new VduArtifact("", new byte[0], null);
87         }
88
89         /**
90          * Write template files
91          */
92         try (OutputStream ofs = new FileOutputStream(new File(dir, mainTemplate.getName()));
93                 PrintStream mfstream =
94                         new PrintStream(new File(metadir.getAbsolutePath() + '/' + MANIFEST_FILENAME));) {
95             ofs.write(mainTemplate.getContent());
96
97             /**
98              * Write other files
99              */
100             if (!extraFiles.isEmpty()) {
101                 for (VduArtifact artifact : extraFiles) {
102                     try (OutputStream out = new FileOutputStream(new File(dir, artifact.getName()));) {
103                         out.write(artifact.getContent());
104                     }
105                 }
106             }
107
108
109             /**
110              * Create manifest
111              */
112             mfstream.println("TOSCA-Meta-File-Version: 1.0");
113             mfstream.println("CSAR-Version: 1.1");
114             mfstream.println("Created-by: ONAP");
115             mfstream.println("Entry-Definitions: " + mainTemplate.getName());
116
117             /**
118              * ZIP it up
119              */
120             ByteArrayOutputStream zipbytes = new ByteArrayOutputStream();
121             ZipOutputStream zos = new ZipOutputStream(zipbytes);
122             compressTree(zos, "", dir, dir);
123             zos.close();
124             return zipbytes.toByteArray();
125
126         } catch (Exception e) {
127             throw new RuntimeException("Failed to create CSAR: " + e.getMessage());
128         } finally {
129             /**
130              * Clean up tmpdir
131              */
132             deleteDirectory(dir);
133         }
134     }
135
136     /**
137      * Private methods
138      */
139
140     /**
141      * Compresses (ZIPs) a directory tree
142      * 
143      * @param dir
144      * @throws IOException
145      */
146     private void compressTree(ZipOutputStream zos, String path, File basedir, File dir) throws IOException {
147         if (!dir.isDirectory())
148             return;
149
150         for (File f : dir.listFiles()) {
151             if (f.isDirectory()) {
152                 String newpath = path + f.getName() + '/';
153                 ZipEntry entry = new ZipEntry(newpath);
154                 zos.putNextEntry(entry);
155                 zos.closeEntry();
156                 compressTree(zos, newpath, basedir, f);
157             } else {
158                 ZipEntry ze = new ZipEntry(
159                         f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1).replaceAll("\\\\", "/"));
160                 zos.putNextEntry(ze);
161                 // read the file and write to ZipOutputStream
162                 try (FileInputStream fis = new FileInputStream(f);) {
163                     byte[] buffer = new byte[1024];
164                     int len;
165                     while ((len = fis.read(buffer)) > 0) {
166                         zos.write(buffer, 0, len);
167                     }
168                 }
169                 zos.closeEntry();
170             }
171         }
172     }
173
174     private boolean deleteDirectory(File directory) {
175         if (directory.exists()) {
176             File[] files = directory.listFiles();
177             if (null != files) {
178                 for (int i = 0; i < files.length; i++) {
179                     if (files[i].isDirectory()) {
180                         deleteDirectory(files[i]);
181                     } else {
182                         files[i].delete();
183                     }
184                 }
185             }
186         }
187         return (directory.delete());
188     }
189 }