aboutsummaryrefslogtreecommitdiffstats
path: root/ecomp-sdk-app/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java
blob: 20bfa1a50549714f634b1496df2b39072e99188c (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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/*-
 * ============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.utils;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.UUID;

import org.openecomp.policy.rest.XACMLRestProperties;

import org.openecomp.policy.xacml.api.XACMLErrorConstants;
import org.openecomp.policy.xacml.util.XACMLPolicyWriter;
import com.att.research.xacml.util.XACMLProperties;

import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;

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

/**
 * Helper static class that wraps XACMLPolicyWriter
 * 
 *
 */
public class XACMLPolicyWriterWithPapNotify{
	private static final Logger logger = FlexLogger.getLogger(XACMLPolicyWriterWithPapNotify.class);

	/**
	 * Helper static class that does the work to write a policy set to a file on disk and notify PAP
	 * 
	 *
	 */
	public static Path writePolicyFile(Path filename, PolicySetType policySet) {
		if(logger.isDebugEnabled()){
			logger.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet)"
					+ "\nfilename = " + filename
					+ "\npolicySet = " + policySet);
		}
		//write to file
		Path path = XACMLPolicyWriter.writePolicyFile(filename, policySet);
		
		if(path!=null){
			//write to DB
			if(notifyPapOfCreateUpdate(filename.toAbsolutePath().toString())){
				return path;
			}else{
				//write to DB failed.  So, delete the file
				try{
					Files.deleteIfExists(path);
				}catch(DirectoryNotEmptyException e){
					//We are trying to delete a directory and it is not empty
					logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)"
							+ "\nDirectoryNotEmptyException for path = " + path
							+ "\nException message = " + e);
				}catch(IOException e) {
				    // File permission problems are caught here.
					logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)"
							+ "\nIOException for path = " + path
							+ "\nException message = " + e);
				}catch(Exception e){
					logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)"
							+ "\nException for path = " + path
							+ "\nException message = " + e);
				}
				return null;
			}

		}else{
			return null;
		}
	}

	/**
	 * Helper static class that does the work to write a policy set to an output stream and notify PAP
	 * 
	 *
	 */
	public static void writePolicyFile(OutputStream os, PolicySetType policySet) {
		if(logger.isDebugEnabled()){
			logger.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(OutputStream os, PolicySetType policySet)"
					+ "\nos = " + os
					+ "\npolicySet = " + policySet);
		}
		//Only used for writing a byte array output stream for a message.  No file is written
		XACMLPolicyWriter.writePolicyFile(os, policySet);
	}

	/**
	 * Helper static class that does the work to write a policy to a file on disk.
	 * 
	 *
	 */
	public static Path writePolicyFile(Path filename, PolicyType policy) {
		if(logger.isDebugEnabled()){
			logger.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicyType policy)"
					+ "\nfilename = " + filename
					+ "\npolicy = " + policy);
		}

		//write to file
		Path path = XACMLPolicyWriter.writePolicyFile(filename, policy);
		
		if(path!=null){
			//write to DB			
			if(notifyPapOfCreateUpdate(filename.toAbsolutePath().toString())){
				return path;
			}else{
				//write to DB failed so delete the file
				try{
					Files.deleteIfExists(path);
				}catch(DirectoryNotEmptyException e){
					//We are trying to delete a directory and it is not empty
					logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet)Files.deleteIfExists(path) :"
							+ "\nDirectoryNotEmptyException for path = " + path
							+ "\nException message = " + e);
				}catch(IOException e) {
				    // File permission problems are caught here.
					logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)"
							+ "\nIOException for path = " + path
							+ "\nException message = " + e);
				}catch(Exception e){
					logger.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)"
							+ "\nException for path = " + path
							+ "\nException message = " + e);
				}
				return null;
			}

		}else{
			return null;
		}
	}


	/**
	 * Helper static class that does the work to write a policy to a file on disk.
	 * 
	 *
	 */
	public static InputStream getXmlAsInputStream(PolicyType policy) {
		if(logger.isDebugEnabled()){
			logger.debug("\nXACMLPolicyWriterWithPapNotify.getXmlAsInputStream(PolicyType policy)"
					+ "\npolicy = " + policy);
		}
		return XACMLPolicyWriter.getXmlAsInputStream(policy);
	}
	/**
	 * Helper static class that does the work to write a policy set to an output stream.
	 * 
	 *
	 */
	public static void writePolicyFile(OutputStream os, PolicyType policy) {
		if(logger.isDebugEnabled()){
			logger.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(OutputStream os, PolicyType policy)"
					+ "\nos = " + os
					+ "\npolicy = " + policy);
		}
		//There are no references to this and if there were, it would most likely be used in an http message
		XACMLPolicyWriter.writePolicyFile(os, policy);
	}

	public static String changeFileNameInXmlWhenRenamePolicy(Path filename) {
		if(logger.isDebugEnabled()){
			logger.debug("\nXACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(Path filename)"
					+ "\nfilename = " + filename);
		}
		return XACMLPolicyWriter.changeFileNameInXmlWhenRenamePolicy(filename);
	}
	
	public static boolean notifyPapOfPolicyRename(String oldPolicyName, String newPolicyName){
		if(logger.isDebugEnabled()){
			logger.debug("\nXACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(String policyToCreateUpdate) " 
					+ "\npolicyToCreateUpdate = " + " ");
		}
		Base64.Encoder encoder = Base64.getEncoder();
		String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8));
		HttpURLConnection connection = null;
		UUID requestID = UUID.randomUUID();
		//loggingContext.setRequestID(requestID.toString());
		//loggingContext.transactionStarted();
		URL url;
		try {
			url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)+"?oldPolicyName="+ URLEncoder.encode(oldPolicyName, "UTF-8")+"&newPolicyName="+URLEncoder.encode(newPolicyName,"UTF-8"));
			if(logger.isDebugEnabled()){
				logger.debug("\nnotifyPapOfCreateUpdate: URL = " + url);
			}
		} catch (MalformedURLException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nMalformedURLException message = " + e);
			
			return false;
		} catch (UnsupportedEncodingException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nUnsupportedEncodingException message = " + e);

			return false;
		}
		//
		// Open up the connection
		//
		try {
			connection = (HttpURLConnection)url.openConnection();
		} catch (IOException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nurl.openConnection() IOException message = " + e);			
			return false;
		}
		//
		// Setup our method and headers
		//
        try {
			connection.setRequestMethod("PUT");
		} catch (ProtocolException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nconnection.setRequestMethod(PUT) ProtocolException message = " + e);
			connection.disconnect();
			return false;
		}
        connection.setRequestProperty("Authorization", "Basic " + encoding);
		connection.setRequestProperty("Accept", "text/x-java-properties");
        connection.setRequestProperty("Content-Type", "text/x-java-properties");	  	        
        connection.setRequestProperty("requestID", requestID.toString());
        connection.setUseCaches(false);
        //
        // Adding this in. It seems the HttpUrlConnection class does NOT
        // properly forward our headers for POST re-direction. It does so
        // for a GET re-direction.
        //
        // So we need to handle this ourselves.
        //
        connection.setInstanceFollowRedirects(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);
        try {
			connection.connect();
		} catch (IOException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nconnection.connect() IOException message = " + e);
			connection.disconnect();
			return false;
		}
        try {
        	int responseCode = connection.getResponseCode();
        	if(logger.isDebugEnabled()){
        		logger.debug("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
    					+ "\nconnection.getResponseCode() = " + responseCode);
        	}
			if (responseCode == 200) {
				connection.disconnect();
				return true;
			} else {
				connection.disconnect();
				return false;
				//System.out.println(connection.getResponseMessage());
				//System.out.println(connection.getResponseCode());
				//System.out.println(connection.g);
			}
		} catch (IOException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nconnection.getResponseCode() IOException message = " + e);
			connection.disconnect();
			return false;
		}
	}
	
	public static boolean notifyPapOfDelete(String policyToDelete){
		Base64.Encoder encoder = Base64.getEncoder();
		String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8));
		HttpURLConnection connection = null;
		UUID requestID = UUID.randomUUID();
		//loggingContext.setRequestID(requestID.toString());
		//loggingContext.transactionStarted();
		String papUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
		if(papUrl == null){
			logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + 
					"PAP url property does not exist");
			return false;
		}
		String urlString = "";
		try{
		urlString = papUrl+"?groupId=0&isDeleteNotify=1&policyToDelete="+ URLEncoder.encode(policyToDelete, "UTF-8");
		} catch(UnsupportedEncodingException e){
			logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + 
					"Invalid encoding: UTF-8", e);
			return false;
		}
		URL url;
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e) {			
			logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + 
					"Error parsing PAP url: "
							+ urlString
							, e);				
			return false;
		}
		//
		// Open up the connection
		//
		try {
			connection = (HttpURLConnection)url.openConnection();
		} catch (IOException e) {
			logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + 
					"Error opening HttpURLConnection to: "
							+ url.toString()
							, e);				
			return false;
		}
		//
		// Setup our method and headers
		//
        try {
			connection.setRequestMethod("DELETE");
		} catch (ProtocolException e) {
			logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + 
					"Invalid request method: DELETE", e);
			connection.disconnect();
			return false;
		}
        connection.setRequestProperty("Authorization", "Basic " + encoding);
		connection.setRequestProperty("Accept", "text/x-java-properties");
        connection.setRequestProperty("Content-Type", "text/x-java-properties");	  	        
        connection.setRequestProperty("requestID", requestID.toString());
        connection.setUseCaches(false);
        //
        // Adding this in. It seems the HttpUrlConnection class does NOT
        // properly forward our headers for POST re-direction. It does so
        // for a GET re-direction.
        //
        // So we need to handle this ourselves.
        //
        connection.setInstanceFollowRedirects(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);
        try {
			connection.connect();
		} catch (IOException e) {
			logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + 
					"Error connecting HttpURLConnection to: "
							+ connection.getURL().toString()
							, e);	
			connection.disconnect();
			return false;
		}
        try {
			if (connection.getResponseCode() == 200) {
				connection.disconnect();
				//worked
				return true;
			} else {
				connection.disconnect();
				return false;
				//System.out.println(connection.getResponseMessage());
				//System.out.println(connection.getResponseCode());
				//System.out.println(connection.g);
			}
		} catch (IOException e) {
			logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + 
					"Error getting HttpUrlConnection response code for: "
							+ connection.getURL().toString()
							, e);
			connection.disconnect();
			return false;
		}
	}
	
	public static boolean notifyPapOfCreateUpdate(String policyToCreateUpdate){
		if(logger.isDebugEnabled()){
			logger.debug("\nXACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(String policyToCreateUpdate) " 
					+ "\npolicyToCreateUpdate = " + policyToCreateUpdate);
		}
		Base64.Encoder encoder = Base64.getEncoder();
		String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8));
		HttpURLConnection connection = null;
		UUID requestID = UUID.randomUUID();
		//loggingContext.setRequestID(requestID.toString());
		//loggingContext.transactionStarted();
		URL url;
		try {
			url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)+"?policyToCreateUpdate="+ URLEncoder.encode(policyToCreateUpdate, "UTF-8"));
			if(logger.isDebugEnabled()){
				logger.debug("\nnotifyPapOfCreateUpdate: URL = " + url);
			}
		} catch (MalformedURLException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nMalformedURLException message = " + e);
			
			return false;
		} catch (UnsupportedEncodingException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nUnsupportedEncodingException message = " + e);

			return false;
		}
		//
		// Open up the connection
		//
		try {
			connection = (HttpURLConnection)url.openConnection();
		} catch (IOException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nurl.openConnection() IOException message = " + e);			
			return false;
		}
		//
		// Setup our method and headers
		//
        try {
			connection.setRequestMethod("PUT");
		} catch (ProtocolException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nconnection.setRequestMethod(PUT) ProtocolException message = " + e);
			connection.disconnect();
			return false;
		}
        connection.setRequestProperty("Authorization", "Basic " + encoding);
		connection.setRequestProperty("Accept", "text/x-java-properties");
        connection.setRequestProperty("Content-Type", "text/x-java-properties");	  	        
        connection.setRequestProperty("requestID", requestID.toString());
        connection.setUseCaches(false);
        //
        // Adding this in. It seems the HttpUrlConnection class does NOT
        // properly forward our headers for POST re-direction. It does so
        // for a GET re-direction.
        //
        // So we need to handle this ourselves.
        //
        connection.setInstanceFollowRedirects(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);
        try {
			connection.connect();
		} catch (IOException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nconnection.connect() IOException message = " + e);
			connection.disconnect();
			return false;
		}
        try {
        	int responseCode = connection.getResponseCode();
        	if(logger.isDebugEnabled()){
        		logger.debug("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
    					+ "\nconnection.getResponseCode() = " + responseCode);
        	}
			if (responseCode == 200) {
				connection.disconnect();
				return true;
			} else {
				connection.disconnect();
				return false;
				//System.out.println(connection.getResponseMessage());
				//System.out.println(connection.getResponseCode());
				//System.out.println(connection.g);
			}
		} catch (IOException e) {
			logger.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)"
					+ "\nconnection.getResponseCode() IOException message = " + e);
			connection.disconnect();
			return false;
		}
	}
}