1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.river.tool;
20
21 import java.io.BufferedWriter;
22 import java.io.File;
23 import java.io.FileWriter;
24 import java.io.IOException;
25 import java.io.PrintWriter;
26 import java.net.URISyntaxException;
27 import java.security.KeyStore;
28 import java.security.Permission;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Iterator;
32 import java.util.TreeSet;
33 import org.apache.river.api.security.DefaultPolicyParser;
34 import org.apache.river.api.security.PermissionComparator;
35 import org.apache.river.api.security.PermissionGrant;
36 import org.apache.river.api.security.PermissionGrantBuilder;
37 import org.apache.river.api.security.PolicyParser;
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52 public class PolicyCondenser {
53
54 public static void main(String [] args) throws Exception{
55 PolicyCondenser condenser = new PolicyCondenser();
56 for (int i = 0, l = args.length; i < l; i++){
57 condenser.condense(args[i]);
58 }
59 }
60
61 private PolicyCondenser()
62 {
63 super();
64 }
65
66 private static File policyFile(String filename) throws URISyntaxException{
67
68 File policyFile = new File(filename);
69 if (!policyFile.exists()){
70 try {
71 policyFile.createNewFile();
72 } catch (IOException ex) {
73 throw new RuntimeException("Unable to create a policy file: " + filename, ex);
74 }
75 }
76 return policyFile;
77 }
78
79 private void condense(String arg) throws Exception {
80 File policy = policyFile(arg);
81 File condensedPolicy = policyFile(arg + ".con");
82 PolicyParser parser = new DefaultPolicyParser();
83 Collection<PermissionGrant> grantsCol = parser.parse(policy.toURI().toURL(), System.getProperties());
84 PermissionGrant [] grants = grantsCol.toArray(new PermissionGrant[grantsCol.size()]);
85 int length = grants.length;
86 Collection<PermissionGrantBuilder> builders = new ArrayList<PermissionGrantBuilder>(length);
87 for (int i = 0; i < length; i++){
88 if (grants[i] == null) continue;
89 PermissionGrantBuilder builder = grants[i].getBuilderTemplate();
90 Collection<Permission> permissions = new TreeSet<Permission>(new PermissionComparator());
91 permissions.addAll(grants[i].getPermissions());
92 for (int j = 0; j < length; j++){
93 if (i == j || grants[j] == null) continue;
94 if (grants[i].impliesEquivalent(grants[j])){
95 permissions.addAll(grants[j].getPermissions());
96 grants[j] = null;
97 }
98 }
99 builder.permissions(permissions.toArray(new Permission[permissions.size()]));
100 builders.add(builder);
101 grants[i] = null;
102 }
103 PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(condensedPolicy, true)));
104 Iterator<PermissionGrantBuilder> builderIt = builders.iterator();
105 while(builderIt.hasNext()){
106 pw.print("grant ");
107 pw.print(builderIt.next().build().toString());
108 }
109 pw.flush();
110 pw.close();
111 }
112
113 }