KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > security > provider > PolicyConfigurationImpl


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.security.provider;
25
26 import javax.security.jacc.PolicyConfiguration JavaDoc;
27 import javax.security.jacc.*;
28
29 import java.util.Map JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.Enumeration JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.util.HashMap JavaDoc;
34 import java.util.HashSet JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.Set JavaDoc;
37 import java.lang.UnsupportedOperationException JavaDoc;
38 import java.lang.reflect.Constructor JavaDoc;
39
40 import java.security.*;
41 import javax.security.auth.Subject JavaDoc;
42 import java.io.File JavaDoc;
43 import java.io.FileFilter JavaDoc;
44 import java.io.FileReader JavaDoc;
45 import java.io.FileWriter JavaDoc;
46
47 import java.util.logging.*;
48 import sun.security.provider.PolicyParser;
49 import sun.security.provider.PolicyParser.GrantEntry;
50 import sun.security.provider.PolicyParser.PermissionEntry;
51 import sun.security.provider.PolicyParser.PrincipalEntry;
52 import com.sun.logging.LogDomains;
53 import com.sun.enterprise.util.LocalStringManagerImpl;
54
55 import com.sun.enterprise.deployment.interfaces.SecurityRoleMapper;
56 import com.sun.enterprise.deployment.interfaces.SecurityRoleMapperFactory;
57 import com.sun.enterprise.deployment.interfaces.SecurityRoleMapperFactoryMgr;
58
59 /**
60  * Implementation of Jacc PolicyConfiguration Interface
61  * @author Harpreet Singh (harpreet.singh@sun.com)
62  * @author Ron Monzillo
63  */

64 public class PolicyConfigurationImpl implements PolicyConfiguration JavaDoc {
65
66     private static Logger logger =
67     Logger.getLogger(LogDomains.SECURITY_LOGGER);
68
69     private static LocalStringManagerImpl localStrings =
70     new LocalStringManagerImpl(PolicyConfigurationImpl.class);
71
72     private String JavaDoc CONTEXT_ID = null;
73
74     // Excluded permissions
75
private Permissions excludedPermissions = null;
76     // Unchecked permissions
77
private Permissions uncheckedPermissions = null;
78     // permissions mapped to roles.
79
private HashMap JavaDoc rolePermissionsTable = null;
80
81     // used to represent configuration linkages
82
private static HashMap JavaDoc linkTable = new HashMap JavaDoc();
83     
84     private static SecurityRoleMapperFactory factory =
85     SecurityRoleMapperFactoryMgr.getFactory();
86
87     // set in PolicyLoader from domain.xml
88
private static final String JavaDoc REPOSITORY_HOME_PROP =
89         "com.sun.enterprise.jaccprovider.property.repository";
90
91     private static String JavaDoc policySuffix = ".policy";
92  
93     private static String JavaDoc PROVIDER_URL = "policy.url.";
94
95     private static final Class JavaDoc[] permissionParams = { String JavaDoc.class, String JavaDoc.class};
96
97     // These are the 3 possible states that this object can be in.
98
public static final int OPEN_STATE = 0;
99     public static final int INSERVICE_STATE = 2;
100     public static final int DELETED_STATE = 3;
101
102     // new instances are created in the open state.
103
protected int state = OPEN_STATE;
104
105     // this bit is used to optimize commit processing
106
private boolean writeOnCommit = true;
107
108     // this bit is used to optimize refresh processing
109
private boolean wasRefreshed = false;
110     
111     private Policy policy = null;
112     private String JavaDoc policyUrlValue = null;
113
114     // policy file mod times
115
private long[] lastModTimes = new long[2];
116
117     private static Object JavaDoc refreshLock = new Object JavaDoc();
118
119     private static String JavaDoc repository = initializeRepository();
120
121     private static Permission setPolicyPermission = null;
122
123     protected PolicyConfigurationImpl(String JavaDoc contextId){
124     CONTEXT_ID = contextId;
125     // initialize(open,remove,!fromFile)
126
initialize(true,true,false);
127     }
128
129     /**
130      * @param applicationPolicyDirectory, need to have absolute path
131      * @param open, then mark state as open
132      * @param remove, then remove any existing policy statements
133      */

134     protected PolicyConfigurationImpl
135     (File JavaDoc applicationPolicyDirectory, boolean open, boolean remove) {
136
137     CONTEXT_ID = applicationPolicyDirectory.getParentFile().getName() +
138                 '/' + applicationPolicyDirectory.getName();
139
140     String JavaDoc name = getPolicyFileName(true);
141     File JavaDoc f = new File JavaDoc(name);
142     if (!f.exists()) {
143             String JavaDoc defMsg="Unable to open Policy file: "+name;
144             String JavaDoc msg= localStrings.getLocalString("pc.file_not_found",defMsg,new Object JavaDoc []{ name});
145         logger.log(Level.SEVERE,msg);
146         throw new RuntimeException JavaDoc(defMsg);
147     }
148
149     // initialize(open,remove,fromFile)
150
initialize(open,remove,true);
151     }
152
153    /**
154     * This method returns this object's policy context identifier.
155     * @return this object's policy context identifier.
156     *
157     * @throws java.lang.SecurityException
158     * if called by an AccessControlContext that has not been
159     * granted the "setPolicy" SecurityPermission.
160     *
161     * @throws javax.security.jacc.PolicyContextException
162     * if the implementation throws a checked exception that has not been
163     * accounted for by the getContextID method signature. The exception thrown
164     * by the implementation class will be encapsulated (during construction)
165     * in the thrown PolicyContextException.
166     */

167     public String JavaDoc getContextID() throws PolicyContextException {
168     checkSetPolicyPermission();
169     return this.CONTEXT_ID;
170     }
171
172    /**
173     * Used to add permissions to a named role in this PolicyConfiguration.
174     * If the named Role does not exist in the PolicyConfiguration, it is
175     * created as a result of the call to this function.
176     * <P>
177     * It is the job of the Policy provider to ensure that all the permissions
178     * added to a role are granted to principals "mapped to the role".
179     * <P>
180     * @param roleName the name of the Role to which the permissions are
181     * to be added.
182     * <P>
183     * @param permissions the collection of permissions to be added
184     * to the role. The collection may be either a homogenous or
185     * heterogenous collection.
186     *
187     * @throws java.lang.SecurityException
188     * if called by an AccessControlContext that has not been
189     * granted the "setPolicy" SecurityPermission.
190     *
191     * @throws java.lang.UnsupportedOperationException
192     * if the state of the policy context whose interface is this
193     * PolicyConfiguration Object is "deleted" or "inService" when this
194     * method is called.
195     *
196     * @throws javax.security.jacc.PolicyContextException
197     * if the implementation throws a checked exception that has not been
198     * accounted for by the addToRole method signature. The exception thrown
199     * by the implementation class will be encapsulated (during construction)
200     * in the thrown PolicyContextException.
201     */

202     public void addToRole(String JavaDoc roleName, PermissionCollection permissions)
203     throws PolicyContextException
204     {
205         assertStateIsOpen();
206
207     assert roleName != null;
208     assert permissions != null;
209     
210     if (roleName != null && permissions != null) {
211         checkSetPolicyPermission();
212         for(Enumeration JavaDoc e = permissions.elements(); e.hasMoreElements();) {
213         this.getRolePermissions(roleName).add((Permission)e.nextElement());
214         writeOnCommit = true;
215         }
216     }
217     }
218     
219    /**
220     * Used to add a single permission to a named role in this
221     * PolicyConfiguration.
222     * If the named Role does not exist in the PolicyConfiguration, it is
223     * created as a result of the call to this function.
224     * <P>
225     * It is the job of the Policy provider to ensure that all the permissions
226     * added to a role are granted to principals "mapped to the role".
227     * <P>
228     * @param roleName the name of the Role to which the permission is
229     * to be added.
230     * <P>
231     * @param permission the permission to be added
232     * to the role.
233     *
234     * @throws java.lang.SecurityException
235     * if called by an AccessControlContext that has not been
236     * granted the "setPolicy" SecurityPermission.
237     *
238     * @throws java.lang.UnsupportedOperationException
239     * if the state of the policy context whose interface is this
240     * PolicyConfiguration Object is "deleted" or "inService" when this
241     * method is called.
242     *
243     * @throws javax.security.jacc.PolicyContextException
244     * if the implementation throws a checked exception that has not been
245     * accounted for by the addToRole method signature. The exception thrown
246     * by the implementation class will be encapsulated (during construction)
247     * in the thrown PolicyContextException.
248     */

249     public void addToRole(String JavaDoc roleName, Permission permission)
250     throws PolicyContextException {
251
252         assertStateIsOpen();
253
254     assert permission != null;
255     assert roleName != null;
256     
257     if (roleName != null && permission != null) {
258         checkSetPolicyPermission();
259         this.getRolePermissions(roleName).add(permission);
260         writeOnCommit = true;
261     }
262     }
263     
264    /**
265     * Used to add unchecked policy statements to this PolicyConfiguration.
266     * <P>
267     * @param permissions the collection of permissions to be added
268     * as unchecked policy statements. The collection may be either
269     * a homogenous or heterogenous collection.
270     *
271     * @throws java.lang.SecurityException
272     * if called by an AccessControlContext that has not been
273     * granted the "setPolicy" SecurityPermission.
274     *
275     * @throws java.lang.UnsupportedOperationException
276     * if the state of the policy context whose interface is this
277     * PolicyConfiguration Object is "deleted" or "inService" when this
278     * method is called.
279     *
280     * @throws javax.security.jacc.PolicyContextException
281     * if the implementation throws a checked exception that has not been
282     * accounted for by the addToUncheckedPolicy method signature.
283     * The exception thrown
284     * by the implementation class will be encapsulated (during construction)
285     * in the thrown PolicyContextException.
286     */

287     public void addToUncheckedPolicy(PermissionCollection permissions)
288     throws PolicyContextException {
289
290         assertStateIsOpen();
291
292     assert permissions != null;
293     
294     if (permissions != null) {
295         checkSetPolicyPermission();
296         for(Enumeration JavaDoc e = permissions.elements(); e.hasMoreElements();){
297         this.getUncheckedPermissions().add((Permission) e.nextElement());
298         writeOnCommit = true;
299         }
300     }
301     }
302
303    /**
304     * Used to add a single unchecked policy statement to this
305     * PolicyConfiguration.
306     * <P>
307     * @param permission the permission to be added
308     * to the unchecked policy statements.
309     *
310     * @throws java.lang.SecurityException
311     * if called by an AccessControlContext that has not been
312     * granted the "setPolicy" SecurityPermission.
313     *
314     * @throws java.lang.UnsupportedOperationException
315     * if the state of the policy context whose interface is this
316     * PolicyConfiguration Object is "deleted" or "inService" when this
317     * method is called.
318     *
319     * @throws javax.security.jacc.PolicyContextException
320     * if the implementation throws a checked exception that has not been
321     * accounted for by the addToUncheckedPolicy method signature.
322     * The exception thrown
323     * by the implementation class will be encapsulated (during construction)
324     * in the thrown PolicyContextException.
325     */

326     public void addToUncheckedPolicy(Permission permission)
327     throws PolicyContextException{
328     
329         assertStateIsOpen();
330
331     assert permission != null;
332
333     if (permission != null) {
334         checkSetPolicyPermission();
335         this.getUncheckedPermissions().add(permission);
336         writeOnCommit = true;
337     }
338     }
339
340    /**
341     * Used to add excluded policy statements to this PolicyConfiguration.
342     * <P>
343     * @param permissions the collection of permissions to be added
344     * to the excluded policy statements. The collection may be either
345     * a homogenous or heterogenous collection.
346     *
347     * @throws java.lang.SecurityException
348     * if called by an AccessControlContext that has not been
349     * granted the "setPolicy" SecurityPermission.
350     *
351     * @throws java.lang.UnsupportedOperationException
352     * if the state of the policy context whose interface is this
353     * PolicyConfiguration Object is "deleted" or "inService" when this
354     * method is called.
355     *
356     * @throws javax.security.jacc.PolicyContextException
357     * if the implementation throws a checked exception that has not been
358     * accounted for by the addToExcludedPolicy method signature.
359     * The exception thrown
360     * by the implementation class will be encapsulated (during construction)
361     * in the thrown PolicyContextException.
362     */

363     public void addToExcludedPolicy(PermissionCollection permissions)
364     throws PolicyContextException {
365
366         assertStateIsOpen();
367
368     assert permissions != null;
369
370     if (permissions != null) {
371         checkSetPolicyPermission();
372         for(Enumeration JavaDoc e = permissions.elements(); e.hasMoreElements();){
373         this.getExcludedPermissions().add((Permission) e.nextElement());
374         writeOnCommit = true;
375         }
376     }
377     }
378
379    /**
380     * Used to add a single excluded policy statement to this
381     * PolicyConfiguration.
382     * <P>
383     * @param permission the permission to be added
384     * to the excluded policy statements.
385     *
386     * @throws java.lang.SecurityException
387     * if called by an AccessControlContext that has not been
388     * granted the "setPolicy" SecurityPermission.
389     *
390     * @throws java.lang.UnsupportedOperationException
391     * if the state of the policy context whose interface is this
392     * PolicyConfiguration Object is "deleted" or "inService" when this
393     * method is called.
394     *
395     * @throws javax.security.jacc.PolicyContextException
396     * if the implementation throws a checked exception that has not been
397     * accounted for by the addToExcludedPolicy method signature.
398     * The exception thrown
399     * by the implementation class will be encapsulated (during construction)
400     * in the thrown PolicyContextException.
401     */

402     public void addToExcludedPolicy(Permission permission)
403     throws PolicyContextException{
404
405         assertStateIsOpen();
406
407     assert permission != null;
408
409     if (permission != null) {
410         checkSetPolicyPermission();
411         this.getExcludedPermissions().add(permission);
412         writeOnCommit = true;
413     }
414     }
415
416    /**
417     * Used to remove a role and all its permissions from this
418     * PolicyConfiguration.
419     * <P>
420     * @param roleName the name of the Role to remove from this
421     * PolicyConfiguration.
422     *
423     * @throws java.lang.SecurityException
424     * if called by an AccessControlContext that has not been
425     * granted the "setPolicy" SecurityPermission.
426     *
427     * @throws java.lang.UnsupportedOperationException
428     * if the state of the policy context whose interface is this
429     * PolicyConfiguration Object is "deleted" or "inService" when this
430     * method is called.
431     *
432     * @throws javax.security.jacc.PolicyContextException
433     * if the implementation throws a checked exception that has not been
434     * accounted for by the removeRole method signature. The exception thrown
435     * by the implementation class will be encapsulated (during construction)
436     * in the thrown PolicyContextException.
437     */

438     public void removeRole(String JavaDoc roleName)
439     throws PolicyContextException{
440
441         assertStateIsOpen();
442
443     assert roleName != null;
444
445     if(roleName != null && rolePermissionsTable != null) {
446         checkSetPolicyPermission();
447         if (rolePermissionsTable.remove(roleName) != null)
448         writeOnCommit = true;
449     }
450     }
451
452    /**
453     * Used to remove any unchecked policy statements from this
454     * PolicyConfiguration.
455     *
456     * @throws java.lang.SecurityException
457     * if called by an AccessControlContext that has not been
458     * granted the "setPolicy" SecurityPermission.
459     *
460     * @throws java.lang.UnsupportedOperationException
461     * if the state of the policy context whose interface is this
462     * PolicyConfiguration Object is "deleted" or "inService" when this
463     * method is called.
464     *
465     * @throws javax.security.jacc.PolicyContextException
466     * if the implementation throws a checked exception that has not been
467     * accounted for by the removeUncheckedPolicy method signature.
468     * The exception thrown
469     * by the implementation class will be encapsulated (during construction)
470     * in the thrown PolicyContextException.
471     */

472     public void removeUncheckedPolicy()
473     throws PolicyContextException{
474
475         assertStateIsOpen();
476
477     checkSetPolicyPermission();
478
479     if (uncheckedPermissions != null) {
480         uncheckedPermissions = null;
481         writeOnCommit = true;
482     }
483     }
484
485    /**
486     * Used to remove any excluded policy statements from this
487     * PolicyConfiguration.
488     *
489     * @throws java.lang.SecurityException
490     * if called by an AccessControlContext that has not been
491     * granted the "setPolicy" SecurityPermission.
492     *
493     * @throws java.lang.UnsupportedOperationException
494     * if the state of the policy context whose interface is this
495     * PolicyConfiguration Object is "deleted" or "inService" when this
496     * method is called.
497     *
498     * @throws javax.security.jacc.PolicyContextException
499     * if the implementation throws a checked exception that has not been
500     * accounted for by the removeExcludedPolicy method signature.
501     * The exception thrown
502     * by the implementation class will be encapsulated (during construction)
503     * in the thrown PolicyContextException.
504     */

505     public void removeExcludedPolicy()
506         throws PolicyContextException{
507
508         assertStateIsOpen();
509
510     checkSetPolicyPermission();
511
512     if (excludedPermissions != null) {
513         excludedPermissions = null;
514         writeOnCommit = true;
515     }
516     }
517
518    /**
519     * This method is used to set to "inService" the state of the policy context
520     * whose interface is this PolicyConfiguration Object. Only those policy
521     * contexts whose state is "inService" will be included in the policy
522     * contexts processed by the Policy.refresh method. A policy context whose
523     * state is "inService" may be returned to the "open" state by calling the
524     * getPolicyConfiguration method of the PolicyConfiguration factory
525     * with the policy context identifier of the policy context.
526     * <P>
527     * When the state of a policy context is "inService", calling any method
528     * other than commit, delete, getContextID, or inService on its
529     * PolicyConfiguration Object will cause an UnsupportedOperationException
530     * to be thrown.
531     *
532     * @throws java.lang.SecurityException
533     * if called by an AccessControlContext that has not been
534     * granted the "setPolicy" SecurityPermission.
535     *
536     * @throws java.lang.UnsupportedOperationException
537     * if the state of the policy context whose interface is this
538     * PolicyConfiguration Object is "deleted" when this
539     * method is called.
540     *
541     * @throws javax.security.jacc.PolicyContextException
542     * if the implementation throws a checked exception that has not been
543     * accounted for by the commit method signature. The exception thrown
544     * by the implementation class will be encapsulated (during construction)
545     * in the thrown PolicyContextException.
546     */

547     public void commit() throws PolicyContextException{
548
549     synchronized(refreshLock) {
550         if(state == DELETED_STATE){
551                 String JavaDoc defMsg="Cannot perform Operation on a deleted PolicyConfiguration";
552                 String JavaDoc msg=localStrings.getLocalString("pc.invalid_op_for_state_delete",defMsg);
553         logger.log(Level.WARNING,msg);
554         throw new UnsupportedOperationException JavaDoc(defMsg);
555
556         } else {
557             
558         try {
559
560             checkSetPolicyPermission();
561
562             if (state == OPEN_STATE) {
563
564             generatePermissions();
565
566             state = INSERVICE_STATE;
567             }
568         } catch(Exception JavaDoc e){
569                     String JavaDoc defMsg="commit fail for contextod "+CONTEXT_ID;
570                     String JavaDoc msg=localStrings.getLocalString("pc.commit_failure",defMsg,new Object JavaDoc[]{CONTEXT_ID,e});
571             logger.log(Level.SEVERE,msg);
572             throw new PolicyContextException(e);
573         }
574         if (logger.isLoggable(Level.FINE)){
575             logger.fine("JACC Policy Provider: PC.commit "+CONTEXT_ID);
576         }
577         }
578         
579     }
580     }
581
582    /**
583     * Creates a relationship between this configuration and another
584     * such that they share the same principal-to-role mappings.
585     * PolicyConfigurations are linked to apply a common principal-to-role
586     * mapping to multiple seperately manageable PolicyConfigurations,
587     * as is required when an application is composed of multiple
588     * modules.
589     * <P>
590     * Note that the policy statements which comprise a role, or comprise
591     * the excluded or unchecked policy collections in a PolicyConfiguration
592     * are unaffected by the configuration being linked to another.
593     * <P>
594     * @param link a reference to a different PolicyConfiguration than this
595     * PolicyConfiguration.
596     * <P>
597     * The relationship formed by this method is symetric, transitive
598     * and idempotent. If the argument PolicyConfiguration does not have a
599     * different Policy context identifier than this PolicyConfiguration
600     * no relationship is formed, and an exception, as described below, is
601     * thrown.
602     *
603     * @throws java.lang.SecurityException
604     * if called by an AccessControlContext that has not been
605     * granted the "setPolicy" SecurityPermission.
606     *
607     * @throws java.lang.UnsupportedOperationException
608     * if the state of the policy context whose interface is this
609     * PolicyConfiguration Object is "deleted" or "inService" when this
610     * method is called.
611     *
612     * @throws java.lang.IllegalArgumentException
613     * if called with an argument PolicyConfiguration whose Policy context
614     * is equivalent to that of this PolicyConfiguration.
615     *
616     * @throws javax.security.jacc.PolicyContextException
617     * if the implementation throws a checked exception that has not been
618     * accounted for by the linkConfiguration method signature. The exception
619     * thrown
620     * by the implementation class will be encapsulated (during construction)
621     * in the thrown PolicyContextException.
622     */

623     public void linkConfiguration(PolicyConfiguration JavaDoc link) throws PolicyContextException {
624
625         assertStateIsOpen();
626
627     String JavaDoc linkId = link.getContextID();
628     if (this.CONTEXT_ID == linkId) {
629             String JavaDoc defMsg="Operation attempted to link PolicyConfiguration to itself.";
630             String JavaDoc msg=localStrings.getLocalString("pc.unsupported_link_operation",defMsg);
631         logger.log(Level.WARNING,msg);
632         throw new IllegalArgumentException JavaDoc(defMsg);
633     }
634
635     checkSetPolicyPermission();
636
637     updateLinkTable(linkId);
638
639     }
640
641    /**
642     * Causes all policy statements to be deleted from this PolicyConfiguration
643     * and sets its internal state such that calling any method, other than
644     * delete, getContextID, or inService on the PolicyConfiguration will
645     * be rejected and cause an UnsupportedOperationException to be thrown.
646     * <P>
647     * This operation has no affect on any linked PolicyConfigurations
648     * other than removing any links involving the deleted PolicyConfiguration.
649     *
650     * @throws java.lang.SecurityException
651     * if called by an AccessControlContext that has not been
652     * granted the "setPolicy" SecurityPermission.
653     *
654     * @throws javax.security.jacc.PolicyContextException
655     * if the implementation throws a checked exception that has not been
656     * accounted for by the delete method signature. The exception thrown
657     * by the implementation class will be encapsulated (during construction)
658     * in the thrown PolicyContextException.
659     */

660     public void delete() throws PolicyContextException
661     {
662     checkSetPolicyPermission();
663     synchronized(refreshLock) {
664         try {
665         removePolicy();
666         } finally {
667         state = DELETED_STATE;
668         }
669     }
670     }
671
672    /**
673     * This method is used to determine if the policy context whose interface is
674     * this PolicyConfiguration Object is in the "inService" state.
675     *
676     * @return true if the state of the associated policy context is
677     * "inService"; false otherwise.
678     *
679     * @throws java.lang.SecurityException
680     * if called by an AccessControlContext that has not been
681     * granted the "setPolicy" SecurityPermission.
682     *
683     * @throws javax.security.jacc.PolicyContextException
684     * if the implementation throws a checked exception that has not been
685     * accounted for by the inService method signature. The exception thrown
686     * by the implementation class will be encapsulated (during construction)
687     * in the thrown PolicyContextException.
688     */

689     public boolean inService() throws PolicyContextException{
690     checkSetPolicyPermission();
691     return (state == INSERVICE_STATE)? true: false;
692     }
693
694     // The following methods are implementation specific
695

696     protected static void checkSetPolicyPermission() {
697     SecurityManager JavaDoc sm = System.getSecurityManager();
698     if (sm != null) {
699         if (setPolicyPermission == null) {
700         setPolicyPermission = new java.security.SecurityPermission JavaDoc("setPolicy");
701         }
702         sm.checkPermission(setPolicyPermission);
703     }
704     }
705
706     // get the policy object
707
protected java.security.Policy JavaDoc getPolicy(){
708     synchronized(refreshLock) {
709         if (state == INSERVICE_STATE) {
710         return this.policy;
711         }
712         if (logger.isLoggable(Level.FINEST)) {
713         logger.finest("JACC Policy Provider: getPolicy ("+CONTEXT_ID+") is NOT in service");
714         }
715         return null;
716     }
717     }
718
719     // get the policy object
720
protected Permissions getExcludedPolicy(){
721     synchronized(refreshLock) {
722         return state == INSERVICE_STATE ? this.excludedPermissions : null;
723     }
724     }
725
726     // called by PolicyWrapper to refresh context specific policy object.
727
protected void refresh(boolean force){
728
729     synchronized(refreshLock){
730         if (state == INSERVICE_STATE &&
731         (wasRefreshed == false || force || filesChanged())) {
732
733         // find open policy.url
734
int i = 0;
735         String JavaDoc value = null;
736         String JavaDoc urlKey = null;
737         while (true) {
738             urlKey = PROVIDER_URL+(++i);
739             value = java.security.Security.getProperty(urlKey);
740             if (value == null || value.equals("")) {
741             break;
742             }
743         }
744
745         try {
746             java.security.Security.setProperty(urlKey,policyUrlValue);
747
748             if (fileChanged(false)) {
749             excludedPermissions = loadExcludedPolicy();
750             }
751
752             // capture time before load, to ensure that we
753
// have a time that precedes load
754
captureFileTime(true);
755
756             if (policy == null) {
757             policy = (java.security.Policy JavaDoc) new sun.security.provider.PolicyFile();
758             } else {
759             policy.refresh();
760             if (logger.isLoggable(Level.FINE)){
761                 logger.fine("JACC Policy Provider: Called Policy.refresh on contextId: "+CONTEXT_ID+" policyUrlValue was "+policyUrlValue);
762             }
763             }
764             wasRefreshed = true;
765         } finally {
766             // can't setProperty back to null, workaround is to
767
// use empty string
768
java.security.Security.setProperty(urlKey,"");
769         }
770         }
771     }
772     }
773
774     private void captureFileTime(boolean granted) {
775     String JavaDoc name = getPolicyFileName(granted);
776     File JavaDoc f = new File JavaDoc(name);
777     lastModTimes[(int) (granted ? 1 : 0)] = f.lastModified();
778     }
779
780     private boolean fileChanged(boolean granted) {
781     String JavaDoc name = getPolicyFileName(granted);
782     File JavaDoc f = new File JavaDoc(name);
783     return !(lastModTimes[(int) (granted ? 1 : 0)] == f.lastModified());
784     }
785
786     private boolean filesChanged() {
787     return (fileChanged(true) || fileChanged(false));
788     }
789
790     // initilaize the internal data structures.
791
// if open, then mark state as open
792
// if remove, then remove any existing policy statements
793
// if fromFile (and not remove), then mark state as in service,
794
// and not requiring write on commit
795
// if fromFile (and remove), then remove and mark state as open
796
protected void initialize(boolean open, boolean remove, boolean fromFile) {
797     synchronized(refreshLock) {
798         String JavaDoc name = getPolicyFileName(true);
799         if (open || remove) {
800         state = OPEN_STATE;
801         } else {
802         state = INSERVICE_STATE;
803         }
804         try {
805         if (remove) {
806             removePolicy();
807         }
808
809         policyUrlValue =
810             sun.net.www.ParseUtil.fileToEncodedURL(new File JavaDoc(name)).toString();
811         if (fromFile && !remove) {
812             excludedPermissions = loadExcludedPolicy();
813             writeOnCommit = false;
814         }
815         wasRefreshed = false;
816         } catch (java.net.MalformedURLException JavaDoc mue) {
817                 String JavaDoc defMsg="Unable to convert Policy file Name to URL: "+name;
818                 String JavaDoc msg=localStrings.getLocalString("pc.file_to_url",defMsg, new Object JavaDoc[]{name,mue});
819         logger.log(Level.SEVERE,msg);
820         throw new RuntimeException JavaDoc(defMsg);
821         }
822     }
823     }
824
825     private String JavaDoc getPolicyFileName(boolean granted) {
826       return granted ?
827       getContextDirectoryName()+File.separator+"granted"+policySuffix :
828       getContextDirectoryName()+File.separator+"excluded"+policySuffix;
829     }
830
831     private String JavaDoc getContextDirectoryName() {
832     if (repository == null) {
833         throw new RuntimeException JavaDoc("JACC Policy provider: repository not initialized");
834     }
835     return getContextDirectoryName(CONTEXT_ID);
836     }
837
838     protected static String JavaDoc getContextDirectoryName(String JavaDoc contextId) {
839     if (repository == null) {
840         throw new RuntimeException JavaDoc("JACC Policy provider: repository not initialized");
841     }
842     return repository+File.separator+contextId;
843     }
844
845     // remove the directory used ot hold the context's policy files
846
private void removePolicyContextDirectory(){
847     String JavaDoc directoryName = getContextDirectoryName();
848     File JavaDoc f = new File JavaDoc(directoryName);
849     if(f.exists()){
850
851             // WORKAROUND: due to existence of timestamp file in given directory
852
// for SE/EE synchronization
853
File JavaDoc[] files = f.listFiles();
854             if (files != null && files.length > 0) {
855                 for (int i = 0; i < files.length; i++) {
856                     files[i].delete();
857                 }
858              }
859              //WORKAROUND: End
860

861         if (!f.delete()) {
862                 String JavaDoc defMsg = "Failure removing policy context directory: "+directoryName;
863                 String JavaDoc msg=localStrings.getLocalString("pc.file_delete_error", defMsg);
864         logger.log(Level.SEVERE,msg);
865         throw new RuntimeException JavaDoc(defMsg);
866         } else if(logger.isLoggable(Level.FINE)){
867         logger.fine("JACC Policy Provider: Policy context directory removed: "+directoryName);
868         }
869
870             File JavaDoc appDir = f.getParentFile();
871             // WORKAROUND: due to existence of timestamp file in given directory
872
// for SE/EE synchronization
873
File JavaDoc[] fs = appDir.listFiles();
874             if (fs != null && fs.length > 0) {
875                 boolean hasDir = false;
876                 for (int i = 0; i < fs.length; i++) {
877                     if (fs[i].isDirectory()) {
878                         hasDir = true;
879                         break;
880                     }
881                 }
882                 if (!hasDir) {
883                     for (int i = 0; i < fs.length; i++) {
884                         fs[i].delete();
885                     }
886                 }
887             }
888             //WORKAROUND: End
889

890             File JavaDoc[] moduleDirs = appDir.listFiles();
891             if (moduleDirs == null || moduleDirs.length == 0) {
892                 if (!appDir.delete()) {
893                     String JavaDoc defMsg = "Failure removing policy context directory: " + appDir;
894                     String JavaDoc msg = localStrings.getLocalString("pc.file_delete_error", defMsg);
895             logger.log(Level.SEVERE,msg);
896             throw new RuntimeException JavaDoc(defMsg);
897                 }
898             }
899     }
900     }
901
902     // remove the external (file) policy statements.
903
private void removePolicyFile(boolean granted){
904     String JavaDoc fileName = getPolicyFileName(granted);
905     File JavaDoc f = new File JavaDoc(fileName);
906     if(f.exists()){
907         if (!f.delete()) {
908                 String JavaDoc defMsg = "Failure removing policy file: "+fileName;
909                 String JavaDoc msg=localStrings.getLocalString("pc.file_delete_error", defMsg,new Object JavaDoc []{ fileName} );
910         logger.log(Level.SEVERE,msg);
911         throw new RuntimeException JavaDoc(defMsg);
912         } else if(logger.isLoggable(Level.FINE)){
913         logger.fine("JACC Policy Provider: Policy file removed: "+fileName);
914         }
915     }
916     }
917
918     // remove the internal and external (file) policy statements.
919
private void removePolicy(){
920     excludedPermissions = null;
921     uncheckedPermissions = null;
922     rolePermissionsTable = null;
923     removePolicyFile(true);
924     removePolicyFile(false);
925     removePolicyContextDirectory();
926     initLinkTable();
927     policy = null;
928     writeOnCommit = true;
929     }
930
931     private void initLinkTable() {
932
933     synchronized(refreshLock) {
934         // get the linkSet corresponding to this context.
935
Set JavaDoc linkSet = (Set JavaDoc) linkTable.get(CONTEXT_ID);
936         // remobe this context id from the linkSet (which may be shared
937
// with other contexts), and unmap the linkSet form this context.
938
if (linkSet != null) {
939         linkSet.remove(CONTEXT_ID);
940         linkTable.remove(CONTEXT_ID);
941         }
942
943         // create a new linkSet with onlythis context id, and put it in the table.
944
linkSet = new HashSet JavaDoc();
945         linkSet.add(CONTEXT_ID);
946         linkTable.put(CONTEXT_ID,linkSet);
947     }
948     }
949
950     private void updateLinkTable(String JavaDoc otherId) {
951
952     synchronized(refreshLock) {
953
954         // get the linkSet corresponding to this context
955
Set JavaDoc linkSet = (Set JavaDoc) linkTable.get(CONTEXT_ID);
956         // get the linkSet corresponding to the context being linked to this
957
Set JavaDoc otherLinkSet = (Set JavaDoc) linkTable.get(otherId);
958
959         if (otherLinkSet == null) {
960                 String JavaDoc defMsg="Linked policy configuration ("+otherId+") does not exist";
961                 String JavaDoc msg = localStrings.getLocalString("pc.invalid_link_target",defMsg, new Object JavaDoc []{otherId});
962         logger.log(Level.SEVERE,"pc.invalid_link_target",otherId);
963         throw new RuntimeException JavaDoc(defMsg);
964         } else {
965         Iterator JavaDoc it = otherLinkSet.iterator();
966         // for each context (id) linked to the context being linked to this
967
while (it.hasNext()) {
968             String JavaDoc id = (String JavaDoc) it.next();
969             //add the id to this linkSet
970
linkSet.add(id);
971             //replace the linkset mapped to all the contexts being linked
972
//to this context, with this linkset.
973
linkTable.put(id,linkSet);
974         }
975         }
976     }
977     }
978
979     private void assertStateIsOpen() {
980       
981         if (state != OPEN_STATE){
982             String JavaDoc defMsg="Operation invoked on closed or deleted PolicyConfiguration.";
983             String JavaDoc msg = localStrings.getLocalString("pc.op_requires_state_open",defMsg);
984         logger.log(Level.WARNING, msg);
985         throw new UnsupportedOperationException JavaDoc(defMsg);
986     }
987     }
988
989     /**
990      * Read the repository directory name, create the directory, and
991      * save the name in 'repository'
992      */

993     private static String JavaDoc initializeRepository() {
994
995     try {
996         repository = System.getProperty(REPOSITORY_HOME_PROP);
997         if (repository == null) {
998                 String JavaDoc msg=localStrings.getLocalString("pc.no_repository","no repository");
999         logger.log(Level.SEVERE,msg);
1000        } else {
1001
1002        if (logger.isLoggable(Level.FINE)) {
1003            logger.fine("JACC policy provider: repository set to: "+repository);
1004        }
1005
1006        File JavaDoc rf = new File JavaDoc(repository);
1007        if (rf.exists()) {
1008            if(!rf.isDirectory()) {
1009                        String JavaDoc msg=localStrings.getLocalString("pc.unable_to_create_repository",
1010                              "unable to create repository"+repository,new Object JavaDoc []{repository});
1011            logger.log(Level.SEVERE,msg);
1012            } else {
1013            // read deployed policy contextes
1014
File JavaDoc[] appsInService = rf.listFiles();
1015            if (appsInService != null) {
1016                for (int i = 0; i <appsInService.length; i++) {
1017                                File JavaDoc[] contextsInService =
1018                                    appsInService[i].listFiles(new FileFilter JavaDoc() {
1019                                        public boolean accept(File JavaDoc pathname) {
1020                                            return pathname.isDirectory();
1021                                        }
1022                                    });
1023                                if (contextsInService != null) {
1024                                    for (int j = 0; j < contextsInService.length; j++) {
1025                                        try {
1026                                            PolicyConfigurationImpl pc =
1027                               new PolicyConfigurationImpl(contextsInService[j],false,false);
1028                            PolicyConfigurationFactoryImpl.
1029                               putPolicyConfigurationImpl(pc.CONTEXT_ID,pc);
1030                                        } catch(Exception JavaDoc ex) {
1031                                            String JavaDoc msg=localStrings.getLocalString("pc.unable_to_read_repostory",
1032                                            "unable to read repository" ,new Object JavaDoc []{contextsInService[i].toString()});
1033                                            logger.log(Level.WARNING,msg);
1034                                        }
1035                                    }
1036                                }
1037                }
1038            }
1039            }
1040        } else {
1041            if(logger.isLoggable(Level.FINE)){
1042            logger.fine("JACC Policy Provider: creating new policy repository");
1043            }
1044            rf.mkdirs();
1045        }
1046        }
1047    } catch (Exception JavaDoc e) {
1048            String JavaDoc msg=localStrings.getLocalString("pc.unable_to_init_repository",
1049                     "unable to init repository",new Object JavaDoc []{e});
1050        logger.log(Level.SEVERE,msg);
1051        repository = null;
1052    }
1053
1054    return repository;
1055    }
1056
1057    private Permissions getUncheckedPermissions() {
1058    if (uncheckedPermissions == null) {
1059        uncheckedPermissions = new Permissions();
1060    }
1061    return uncheckedPermissions;
1062    }
1063
1064    private Permissions getExcludedPermissions() {
1065    if (excludedPermissions == null) {
1066        excludedPermissions = new Permissions();
1067    }
1068    return excludedPermissions;
1069    }
1070
1071    private Permissions getRolePermissions(String JavaDoc roleName) {
1072    if (rolePermissionsTable == null) rolePermissionsTable = new HashMap JavaDoc();
1073    Permissions rolePermissions = (Permissions) rolePermissionsTable.get(roleName);
1074    if (rolePermissions == null) {
1075        rolePermissions = new Permissions();
1076        rolePermissionsTable.put(roleName,rolePermissions);
1077    }
1078    return rolePermissions;
1079    }
1080
1081    // This method workarounds a bug in PolicyParser.write(...).
1082
private String JavaDoc escapeName(String JavaDoc name) {
1083        return (name != null && name.indexOf('"') > 0) ?
1084                name.replaceAll("\"", "\\\\\"") : name;
1085    }
1086    
1087    private void generatePermissions()
1088
1089    throws java.io.FileNotFoundException JavaDoc, java.io.IOException JavaDoc {
1090
1091    // optimization - return if the rules have not changed
1092

1093    if (!writeOnCommit) return;
1094
1095    // otherwise proceed to write policy file
1096

1097    Map JavaDoc roleToSubjectMap = null;
1098    if (rolePermissionsTable != null) {
1099        // Make sure a role to subject map has been defined for the Policy Context
1100
if (factory != null) {
1101                // the rolemapper is stored against the
1102
// appname, for a web app get the appname for this contextid
1103
SecurityRoleMapper srm = factory.getRoleMapper(CONTEXT_ID);
1104        if (srm != null) {
1105            roleToSubjectMap = srm.getRoleToSubjectMapping();
1106        }
1107        if (roleToSubjectMap != null) {
1108            // make sure all liked PC's have the same roleToSubjectMap
1109
Set JavaDoc linkSet = (Set JavaDoc) linkTable.get(CONTEXT_ID);
1110            if (linkSet != null) {
1111            Iterator JavaDoc it = linkSet.iterator();
1112            while (it.hasNext()) {
1113                String JavaDoc contextId = (String JavaDoc)it.next();
1114                if (!CONTEXT_ID.equals(contextId)) {
1115                SecurityRoleMapper otherSrm = factory.getRoleMapper(contextId);
1116                Map JavaDoc otherRoleToSubjectMap = null;
1117
1118                if (otherSrm != null) {
1119                    otherRoleToSubjectMap = otherSrm.getRoleToSubjectMapping();
1120                }
1121                
1122                if (otherRoleToSubjectMap != roleToSubjectMap) {
1123                                    String JavaDoc defMsg="Linked policy contexts have different roleToSubjectMaps ("+CONTEXT_ID+")<->("+contextId+")";
1124                                    String JavaDoc msg=localStrings.getLocalString("pc.linked_with_different_role_maps",defMsg,new Object JavaDoc []{CONTEXT_ID,contextId});
1125                    logger.log(Level.SEVERE,msg);
1126                    throw new RuntimeException JavaDoc(defMsg);
1127                }
1128                }
1129            }
1130            }
1131        }
1132        }
1133    }
1134
1135    if (roleToSubjectMap == null && rolePermissionsTable != null) {
1136            String JavaDoc defMsg="This application has no role mapper factory defined";
1137            String JavaDoc msg=localStrings.getLocalString("pc.role_map_not_defined_at_commit",defMsg,new Object JavaDoc []{CONTEXT_ID});
1138        logger.log(Level.SEVERE,msg);
1139        throw new RuntimeException JavaDoc
1140        (localStrings.getLocalString
1141         ("enterprise.deployment.deployment.norolemapperfactorydefine",defMsg));
1142    }
1143
1144    PolicyParser parser = new PolicyParser(false);
1145
1146    // load unchecked grants in parser
1147
if (uncheckedPermissions != null) {
1148        Enumeration JavaDoc pEnum = uncheckedPermissions.elements();
1149        if (pEnum.hasMoreElements()) {
1150        GrantEntry grant = new GrantEntry();
1151        while (pEnum.hasMoreElements()) {
1152            Permission p = (Permission) pEnum.nextElement();
1153            PermissionEntry entry =
1154            new PermissionEntry(p.getClass().getName(),
1155                        p.getName(),p.getActions());
1156            grant.add(entry);
1157        }
1158        parser.add(grant);
1159        }
1160    }
1161
1162    // load role based grants in parser
1163
if (rolePermissionsTable != null) {
1164        Iterator JavaDoc roleIt = rolePermissionsTable.keySet().iterator();
1165        while (roleIt.hasNext()) {
1166        boolean withPrincipals = false;
1167        String JavaDoc roleName = (String JavaDoc) roleIt.next();
1168        Permissions rolePerms = getRolePermissions(roleName);
1169        Subject JavaDoc rolePrincipals = (Subject JavaDoc) roleToSubjectMap.get(roleName);
1170        if (rolePrincipals != null) {
1171            Iterator JavaDoc pit = rolePrincipals.getPrincipals().iterator();
1172            while (pit.hasNext()){
1173            Principal prin = (Principal) pit.next();
1174            assert prin instanceof java.security.Principal JavaDoc;
1175            if (prin instanceof java.security.Principal JavaDoc) {
1176                withPrincipals = true;
1177                PrincipalEntry prinEntry =
1178                new PrincipalEntry(prin.getClass().getName(),
1179                           escapeName(prin.getName()));
1180                GrantEntry grant = new GrantEntry();
1181                grant.principals.add(prinEntry);
1182                Enumeration JavaDoc pEnum = rolePerms.elements();
1183                while (pEnum.hasMoreElements()) {
1184                Permission perm = (Permission) pEnum.nextElement();
1185                PermissionEntry permEntry =
1186                    new PermissionEntry(perm.getClass().getName(),
1187                            perm.getName(),
1188                            perm.getActions());
1189                grant.add(permEntry);
1190                }
1191                parser.add(grant);
1192            }
1193            else {
1194                            String JavaDoc msg = localStrings.getLocalString("pc.non_principal_mapped_to_role",
1195                                         "non principal mapped to role "+roleName,new Object JavaDoc[]{prin,roleName});
1196                logger.log(Level.WARNING,msg);
1197            }
1198            }
1199        }
1200        if (!withPrincipals) {
1201                    String JavaDoc msg = localStrings.getLocalString("pc.no_principals_mapped_to_role",
1202                                  "no principals mapped to role "+roleName, new Object JavaDoc []{ roleName});
1203            logger.log(Level.WARNING,msg);
1204        }
1205        }
1206    }
1207
1208    writeOnCommit = createPolicyFile(true,parser,writeOnCommit);
1209
1210    // load excluded perms in excluded parser
1211
if (excludedPermissions != null) {
1212
1213        PolicyParser excludedParser = new PolicyParser(false);
1214
1215        Enumeration JavaDoc pEnum = excludedPermissions.elements();
1216        if (pEnum.hasMoreElements()) {
1217        GrantEntry grant = new GrantEntry();
1218        while (pEnum.hasMoreElements()) {
1219            Permission p = (Permission) pEnum.nextElement();
1220            PermissionEntry entry =
1221            new PermissionEntry(p.getClass().getName(),
1222                        p.getName(),p.getActions());
1223            grant.add(entry);
1224        }
1225        excludedParser.add(grant);
1226        }
1227
1228        writeOnCommit = createPolicyFile(false,excludedParser,writeOnCommit);
1229    }
1230
1231    if (!writeOnCommit) wasRefreshed = false;
1232    }
1233
1234    private void createPolicyContextDirectory() {
1235
1236    String JavaDoc contextDirectoryName = getContextDirectoryName();
1237    File JavaDoc d = new File JavaDoc(contextDirectoryName);
1238    if (d.exists()) {
1239        if(!d.isDirectory()) {
1240                String JavaDoc defMsg="unable to create policy context directory";
1241                String JavaDoc msg=localStrings.getLocalString("pc.unable_to_create_context_directory",
1242                      defMsg,new Object JavaDoc []{contextDirectoryName});
1243        logger.log(Level.SEVERE,msg);
1244        throw new RuntimeException JavaDoc(defMsg);
1245        }
1246    } else {
1247        d.mkdirs();
1248    }
1249    }
1250
1251    // returns false if write succeeds. otherwise returns input woc (i.e. writeOnCommit)
1252
private boolean createPolicyFile
1253    (boolean granted, PolicyParser parser, boolean woc) throws java.io.IOException JavaDoc {
1254
1255    boolean result = woc;
1256    createPolicyContextDirectory();
1257    removePolicyFile(granted);
1258    String JavaDoc name = getPolicyFileName(granted);
1259    FileWriter JavaDoc writer = null;
1260    try {
1261        if(logger.isLoggable (Level.FINE)){
1262        logger.fine("JACC Policy Provider: Writing grant statements to policy file: "+name);
1263        }
1264        writer = new FileWriter JavaDoc(name);
1265        parser.write(writer);
1266        result = false;
1267    } catch(java.io.FileNotFoundException JavaDoc fnfe) {
1268            String JavaDoc msg=localStrings.getLocalString("pc.file_error","file not found "+name,
1269                  new Object JavaDoc []{name, fnfe});
1270        logger.log(Level.SEVERE,msg);
1271        throw fnfe;
1272    } catch(java.io.IOException JavaDoc ioe){
1273            String JavaDoc msg=localStrings.getLocalString("pc.file_write_error","file IO error on file "+name,
1274                  new Object JavaDoc []{name,ioe});
1275        logger.log(Level.SEVERE,msg);
1276        throw ioe;
1277    } finally {
1278        if (writer != null) {
1279        try {
1280            writer.close();
1281            captureFileTime(granted);
1282        } catch (Exception JavaDoc e) {
1283                    String JavaDoc defMsg="Unable to close Policy file: "+name;
1284                    String JavaDoc msg=localStrings.getLocalString("pc.file_close_error",defMsg,new Object JavaDoc []{name,e});
1285            logger.log(Level.SEVERE,msg);
1286            throw new RuntimeException JavaDoc(defMsg);
1287        }
1288        }
1289    }
1290    return result;
1291    }
1292
1293    private Permission loadPermission(String JavaDoc className,String JavaDoc name,String JavaDoc actions){
1294    Class JavaDoc clazz = null;
1295    Permission permission = null;
1296    try{
1297        clazz = Class.forName(className);
1298        Constructor JavaDoc c = clazz.getConstructor(permissionParams);
1299        permission = (Permission) c.newInstance(new Object JavaDoc[] { name, actions });
1300    } catch(Exception JavaDoc e){
1301            String JavaDoc defMsg="PolicyConfiguration error loading permission";
1302            String JavaDoc msg=localStrings.getLocalString("pc.permission_load_error",defMsg,
1303                       new Object JavaDoc []{className, e});
1304        logger.log(Level.SEVERE,msg);
1305        throw new RuntimeException JavaDoc(defMsg,e);
1306    }
1307    return permission;
1308    }
1309
1310    private Permissions loadExcludedPolicy() {
1311    Permissions result = null;
1312    String JavaDoc name = getPolicyFileName(false);
1313    FileReader JavaDoc reader = null;
1314    PolicyParser parser = new PolicyParser(false);
1315    try {
1316        captureFileTime(false);
1317        reader = new FileReader JavaDoc(name);
1318        parser.read(reader);
1319    } catch (java.io.FileNotFoundException JavaDoc fnf) {
1320        //Just means there is no excluded Policy file, which
1321
// is the typical case
1322
parser = null;
1323    } catch (java.io.IOException JavaDoc ioe) {
1324            String JavaDoc defMsg="Error reading Policy file: "+name;
1325            String JavaDoc msg=localStrings.getLocalString("pc.file_read_error",defMsg,
1326                       new Object JavaDoc []{name, ioe});
1327        logger.log(Level.SEVERE,msg);
1328        throw new RuntimeException JavaDoc(defMsg);
1329    } catch ( sun.security.provider.PolicyParser.ParsingException pe) {
1330            String JavaDoc defMsg="Unable to parse Policy file: "+name;
1331            String JavaDoc msg=localStrings.getLocalString("pc.policy_parsing_exception",defMsg,
1332                       new Object JavaDoc []{name,pe});
1333        logger.log(Level.SEVERE,msg);
1334        throw new RuntimeException JavaDoc(defMsg);
1335    } finally {
1336        if (reader != null) {
1337        try {
1338            reader.close();
1339        } catch (Exception JavaDoc e) {
1340                    String JavaDoc defMsg="Unable to close Policy file: "+name;
1341                    String JavaDoc msg=localStrings.getLocalString("pc.file_close_error",defMsg,
1342                                new Object JavaDoc []{name,e});
1343            logger.log(Level.SEVERE,msg);
1344            throw new RuntimeException JavaDoc(defMsg);
1345        }
1346        }
1347    }
1348
1349    if (parser != null) {
1350        Enumeration JavaDoc grants = parser.grantElements();
1351        while (grants.hasMoreElements()) {
1352        GrantEntry grant = (GrantEntry) grants.nextElement();
1353        if (grant.codeBase != null || grant.signedBy != null ||
1354            grant.principals.size() != 0) {
1355                        String JavaDoc msg=localStrings.getLocalString("pc.excluded_grant_context_ignored",
1356                                   "ignore excluded grant context", new Object JavaDoc []{grant});
1357            logger.log(Level.WARNING,msg);
1358        } else {
1359            Enumeration JavaDoc perms = grant.permissionEntries.elements();
1360            while (perms.hasMoreElements()) {
1361            PermissionEntry entry = (PermissionEntry) perms.nextElement();
1362            Permission p =
1363                loadPermission(entry.permission,entry.name,entry.action);
1364            if (result == null) {
1365                result = new Permissions();
1366            }
1367            result.add(p);
1368            }
1369        }
1370        }
1371    }
1372
1373    return result;
1374    }
1375}
1376
1377
1378
1379
1380
1381
Popular Tags