Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / components / PolicyImportWindow.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017 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.openecomp.policy.components;
22
23
24 /*
25  * 
26  */
27 import java.io.BufferedOutputStream;
28 import java.io.File;
29 import java.io.FileInputStream;
30 import java.io.FileNotFoundException;
31 import java.io.FileOutputStream;
32 import java.io.IOException;
33 import java.io.OutputStream;
34 import java.nio.file.Files;
35 import java.nio.file.Path;
36 import java.nio.file.Paths;
37 import java.util.ArrayList;
38 import java.util.Set;
39
40 import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
41 import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
42 import org.apache.commons.io.IOUtils;
43 import org.openecomp.policy.controller.PolicyController;
44
45 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
46
47 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
48 import org.openecomp.policy.common.logging.flexlogger.Logger;
49
50
51
52 public class PolicyImportWindow{
53
54         private static final Logger logger      = FlexLogger.getLogger(PolicyImportWindow.class);
55         private static final int BUFFER_SIZE = 4096;
56         private static Path directory = PolicyController.getGitPath();
57         private Path newfile = null;
58         private boolean succeeded = false;
59         public static String CONFIG_HOME = PolicyController.getConfigHome();
60         public static String ACTION_HOME = PolicyController.getActionHome();
61         private Boolean superadmin = false;
62         private ArrayList<String> xacmlFiles = new ArrayList<String>();
63         /**
64          * The constructor should first build the main layout, set the
65          * composition root and then do any custom initialization.
66          *
67          * The constructor will not be automatically regenerated by the
68          * visual editor.
69          */
70         
71         public OutputStream receiveUpload(String filename, String mimeType) {
72
73                 //
74                 // Create its new full path
75                 //
76                 this.newfile = Paths.get(PolicyImportWindow.directory.toString(), filename);
77                 //
78                 // Does it already exist?
79                 //
80                 if (Files.exists(this.newfile)) {
81                         return null;
82                 }
83                 //
84                 // Try to create the output stream
85                 //
86                 try {
87                         return new FileOutputStream(this.newfile.toFile());
88                 } catch (FileNotFoundException e) {
89                         logger.error("Failed to create uploaded file", e);
90                 }
91                 return null;
92         }
93
94         public void Upload(){
95                 TarArchiveEntry entry = null;
96                 TarArchiveInputStream extractFile = null;
97                 try {
98                         extractFile = new TarArchiveInputStream (new FileInputStream(this.newfile.toFile()));
99                 } catch (FileNotFoundException e1) {
100                         e1.printStackTrace();
101                 }
102                 //Create a loop to read every single entry in TAR file 
103                 try {
104                         while ((entry = extractFile.getNextTarEntry()) != null) {
105                                 this.superadmin = true;
106                                 try{
107                                         copyFileToLocation(extractFile, entry, xacmlFiles, null, superadmin);
108                                 }catch(Exception e){
109                                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception while Importing Polcies"+e);
110                                 }
111                         }
112                 } catch (IOException e) {
113                         e.printStackTrace();
114                 }
115
116         }
117
118
119
120
121
122         //Copy files to Directorys 
123         public static void copyFileToLocation(TarArchiveInputStream extractFile, TarArchiveEntry entry, ArrayList<String> xacmlFiles, Set<String> finalScopes, Boolean superadminValue ) throws IOException{
124                 String individualFiles = "";
125                 int offset = 0;
126                 FileOutputStream outputFile=null;
127                 // Get the name of the file
128                 if(superadminValue){
129                         individualFiles = entry.getName();
130                 }else{
131                         for(int i =0; i< finalScopes.size(); i++){
132                                 if(entry.getName().startsWith(finalScopes.toArray()[i].toString())){
133                                         individualFiles = entry.getName();
134                                 }
135                         }               
136                 }
137
138                 if(individualFiles.endsWith(".xls")){
139                         if(individualFiles.contains("\\")){
140                                 individualFiles = individualFiles.replace("\\", File.separator);
141                         }else if(individualFiles.contains("/")){
142                                 individualFiles = individualFiles.replace("/", File.separator);
143                         }
144                         return;
145                 }
146
147                 individualFiles = individualFiles.replace("/", File.separator);
148                 individualFiles = individualFiles.replace("\\", File.separator);
149
150                 //Create the path with the entry name 
151                 String filePath = directory.toAbsolutePath() + File.separator + individualFiles;
152                 String  configPath = CONFIG_HOME + File.separator + individualFiles;
153                 String   actionPath = ACTION_HOME + File.separator + individualFiles;
154                 logger.info("File Name in TAR File is: " + individualFiles);
155                 logger.info("Xml directory file path: " + filePath);
156                 logger.info("Config Home directory file path: " + configPath);
157                 logger.info("Action Home directory file path: " + actionPath);
158
159
160                 // Get Size of the file and create a byte array for the size 
161                 byte[] content = new byte[(int) entry.getSize()];
162
163                 offset=0;
164                 logger.info("File Name in TAR File is: " + individualFiles);
165                 logger.info("Size of the File is: " + entry.getSize());                  
166                 // Read file from the archive into byte array 
167                 extractFile.read(content, offset, content.length - offset);
168                 if (!entry.isDirectory()) {
169                         if(!individualFiles.contains(".Config_") || !individualFiles.contains(".Action_")){
170                                 // if the entry is a file, extracts it
171                                 String filePath1 = filePath.substring(0, filePath.lastIndexOf(File.separator));
172                                 File newFile = new File(filePath1);
173                                 if(!(newFile.exists())) {
174                                         File dir = new File(filePath1);
175                                         dir.mkdir();
176                                         extractFile(extractFile, filePath);
177                                 }
178                         }
179                 } else {
180                         // if the entry is a directory, make the director
181                         File dir = new File(filePath);
182                         dir.mkdir();
183                 } 
184                 // Define OutputStream for writing the file 
185                 if(individualFiles.contains(".Config_")){
186                         outputFile=new FileOutputStream(new File(configPath));
187                 }else if(individualFiles.contains(".Action_")){
188                         outputFile=new FileOutputStream(new File(actionPath));
189                 }else{
190                         if(filePath != null){
191                                 outputFile=new FileOutputStream(new File(filePath));
192                                 xacmlFiles.add(filePath);
193                         }
194                 }
195
196                 // Use IOUtiles to write content of byte array to physical file 
197                 IOUtils.write(content,outputFile); 
198
199                 // Close Output Stream 
200                 try {
201                         outputFile.close();
202                 } catch (IOException e) {
203                         logger.info("IOException:" +e);
204                         e.printStackTrace();
205                 }
206         }
207
208         private static void extractFile(TarArchiveInputStream extractFile, String filePath) throws IOException {
209                 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
210                 byte[] bytesIn = new byte[BUFFER_SIZE];
211                 int read = 0;
212                 while ((read = extractFile.read(bytesIn)) != -1) {
213                         bos.write(bytesIn, 0, read);
214                 }
215                 bos.close();
216
217         }
218
219         public Path     getUploadedFile() {
220                 if (this.succeeded) {
221                         return this.newfile;
222                 }
223                 return null;
224         }
225
226 }