aboutsummaryrefslogtreecommitdiffstats
path: root/ecomp-sdk-app/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java
blob: c70e331d064980c99d969a79a0be00fa19896394 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/*-
 * ============LICENSE_START=======================================================
 * ECOMP Policy Engine
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.policy.components;


/*
 * 
 */
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Set;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.io.IOUtils;
import org.openecomp.policy.controller.PolicyController;

import org.openecomp.policy.xacml.api.XACMLErrorConstants;

import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
import org.openecomp.policy.common.logging.flexlogger.Logger;



public class PolicyImportWindow{

	private static final Logger logger	= FlexLogger.getLogger(PolicyImportWindow.class);
	private static final int BUFFER_SIZE = 4096;
	private static Path directory = PolicyController.getGitPath();
	private Path newfile = null;
	private boolean succeeded = false;
	public static String CONFIG_HOME = PolicyController.getConfigHome();
	public static String ACTION_HOME = PolicyController.getActionHome();
	private Boolean superadmin = false;
	private ArrayList<String> xacmlFiles = new ArrayList<String>();
	/**
	 * The constructor should first build the main layout, set the
	 * composition root and then do any custom initialization.
	 *
	 * The constructor will not be automatically regenerated by the
	 * visual editor.
	 */
	
	public OutputStream receiveUpload(String filename, String mimeType) {

		//
		// Create its new full path
		//
		this.newfile = Paths.get(PolicyImportWindow.directory.toString(), filename);
		//
		// Does it already exist?
		//
		if (Files.exists(this.newfile)) {
			return null;
		}
		//
		// Try to create the output stream
		//
		try {
			return new FileOutputStream(this.newfile.toFile());
		} catch (FileNotFoundException e) {
			logger.error("Failed to create uploaded file", e);
		}
		return null;
	}

	public void Upload(){
		TarArchiveEntry entry = null;
		TarArchiveInputStream extractFile = null;
		try {
			extractFile = new TarArchiveInputStream (new FileInputStream(this.newfile.toFile()));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		//Create a loop to read every single entry in TAR file 
		try {
			while ((entry = extractFile.getNextTarEntry()) != null) {
				this.superadmin = true;
				try{
					copyFileToLocation(extractFile, entry, xacmlFiles, null, superadmin);
				}catch(Exception e){
					logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception while Importing Polcies"+e);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}





	//Copy files to Directorys 
	public static void copyFileToLocation(TarArchiveInputStream extractFile, TarArchiveEntry entry, ArrayList<String> xacmlFiles, Set<String> finalScopes, Boolean superadminValue ) throws IOException{
		String individualFiles = "";
		int offset = 0;
		FileOutputStream outputFile=null;
		// Get the name of the file
		if(superadminValue){
			individualFiles = entry.getName();
		}else{
			for(int i =0; i< finalScopes.size(); i++){
				if(entry.getName().startsWith(finalScopes.toArray()[i].toString())){
					individualFiles = entry.getName();
				}
			}		
		}

		if(individualFiles.endsWith(".xls")){
			if(individualFiles.contains("\\")){
				individualFiles = individualFiles.replace("\\", File.separator);
			}else if(individualFiles.contains("/")){
				individualFiles = individualFiles.replace("/", File.separator);
			}
			return;
		}

		individualFiles = individualFiles.replace("/", File.separator);
		individualFiles = individualFiles.replace("\\", File.separator);

		//Create the path with the entry name 
		String filePath = directory.toAbsolutePath() + File.separator + individualFiles;
		String	configPath = CONFIG_HOME + File.separator + individualFiles;
		String	 actionPath = ACTION_HOME + File.separator + individualFiles;
		logger.info("File Name in TAR File is: " + individualFiles);
		logger.info("Xml directory file path: " + filePath);
		logger.info("Config Home directory file path: " + configPath);
		logger.info("Action Home directory file path: " + actionPath);


		// Get Size of the file and create a byte array for the size 
		byte[] content = new byte[(int) entry.getSize()];

		offset=0;
		logger.info("File Name in TAR File is: " + individualFiles);
		logger.info("Size of the File is: " + entry.getSize());                  
		// Read file from the archive into byte array 
		extractFile.read(content, offset, content.length - offset);
		if (!entry.isDirectory()) {
			if(!individualFiles.contains(".Config_") || !individualFiles.contains(".Action_")){
				// if the entry is a file, extracts it
				String filePath1 = filePath.substring(0, filePath.lastIndexOf(File.separator));
				File newFile = new File(filePath1);
				if(!(newFile.exists())) {
					File dir = new File(filePath1);
					dir.mkdir();
					extractFile(extractFile, filePath);
				}
			}
		} else {
			// if the entry is a directory, make the director
			File dir = new File(filePath);
			dir.mkdir();
		} 
		// Define OutputStream for writing the file 
		if(individualFiles.contains(".Config_")){
			outputFile=new FileOutputStream(new File(configPath));
		}else if(individualFiles.contains(".Action_")){
			outputFile=new FileOutputStream(new File(actionPath));
		}else{
			if(filePath != null){
				outputFile=new FileOutputStream(new File(filePath));
				xacmlFiles.add(filePath);
			}
		}

		// Use IOUtiles to write content of byte array to physical file 
		IOUtils.write(content,outputFile); 

		// Close Output Stream 
		try {
			outputFile.close();
		} catch (IOException e) {
			logger.info("IOException:" +e);
			e.printStackTrace();
		}
	}

	private static void extractFile(TarArchiveInputStream extractFile, String filePath) throws IOException {
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
		byte[] bytesIn = new byte[BUFFER_SIZE];
		int read = 0;
		while ((read = extractFile.read(bytesIn)) != -1) {
			bos.write(bytesIn, 0, read);
		}
		bos.close();

	}

	public Path	getUploadedFile() {
		if (this.succeeded) {
			return this.newfile;
		}
		return null;
	}

}