1/*
2 * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package sun.security.tools.policytool;
27
28import java.io.*;
29import java.util.LinkedList;
30import java.util.ListIterator;
31import java.util.Vector;
32import java.util.Enumeration;
33import java.net.URL;
34import java.net.MalformedURLException;
35import java.lang.reflect.*;
36import java.text.Collator;
37import java.text.MessageFormat;
38import sun.security.util.PropertyExpander;
39import sun.security.util.PropertyExpander.ExpandException;
40import java.awt.Component;
41import java.awt.Container;
42import java.awt.Dimension;
43import java.awt.FileDialog;
44import java.awt.GridBagConstraints;
45import java.awt.GridBagLayout;
46import java.awt.Insets;
47import java.awt.Point;
48import java.awt.Toolkit;
49import java.awt.Window;
50import java.awt.event.*;
51import java.security.cert.Certificate;
52import java.security.cert.CertificateException;
53import java.security.*;
54import sun.security.provider.*;
55import sun.security.util.PolicyUtil;
56import javax.security.auth.x500.X500Principal;
57import javax.swing.*;
58import javax.swing.border.EmptyBorder;
59
60/**
61 * PolicyTool may be used by users and administrators to configure the
62 * overall java security policy (currently stored in the policy file).
63 * Using PolicyTool administrators may add and remove policies from
64 * the policy file. <p>
65 *
66 * @see java.security.Policy
67 * @since   1.2
68 * @deprecated {@code policytool} has been deprecated for removal because it
69 * is rarely used, and it provides little value over editing policy
70 * files using a text editor.
71 */
72
73@Deprecated(since="9", forRemoval=true)
74@SuppressWarnings("removal")
75public class PolicyTool {
76
77    // for i18n
78    static final java.util.ResourceBundle rb =
79        java.util.ResourceBundle.getBundle(
80            "sun.security.tools.policytool.Resources");
81    static final Collator collator = Collator.getInstance();
82    static {
83        // this is for case insensitive string comparisons
84        collator.setStrength(Collator.PRIMARY);
85
86        // Support for Apple menu bar
87        if (System.getProperty("apple.laf.useScreenMenuBar") == null) {
88            System.setProperty("apple.laf.useScreenMenuBar", "true");
89        }
90        System.setProperty("apple.awt.application.name", getMessage("Policy.Tool"));
91
92        // Apply the system L&F if not specified with a system property.
93        if (System.getProperty("swing.defaultlaf") == null) {
94            try {
95                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
96            } catch (Exception e) {
97                // ignore
98            }
99        }
100    }
101
102    // anyone can add warnings
103    Vector<String> warnings;
104    boolean newWarning = false;
105
106    // set to true if policy modified.
107    // this way upon exit we know if to ask the user to save changes
108    boolean modified = false;
109
110    private static final boolean testing = false;
111    private static final Class<?>[] TWOPARAMS = { String.class, String.class };
112    private static final Class<?>[] ONEPARAMS = { String.class };
113    private static final Class<?>[] NOPARAMS  = {};
114    /*
115     * All of the policy entries are read in from the
116     * policy file and stored here.  Updates to the policy entries
117     * using addEntry() and removeEntry() are made here.  To ultimately save
118     * the policy entries back to the policy file, the SavePolicy button
119     * must be clicked.
120     **/
121    private static String policyFileName = null;
122    private Vector<PolicyEntry> policyEntries = null;
123    private PolicyParser parser = null;
124
125    /* The public key alias information is stored here.  */
126    private KeyStore keyStore = null;
127    private String keyStoreName = " ";
128    private String keyStoreType = " ";
129    private String keyStoreProvider = " ";
130    private String keyStorePwdURL = " ";
131
132    /* standard PKCS11 KeyStore type */
133    private static final String P11KEYSTORE = "PKCS11";
134
135    /* reserved word for PKCS11 KeyStores */
136    private static final String NONE = "NONE";
137
138    /**
139     * default constructor
140     */
141    private PolicyTool() {
142        policyEntries = new Vector<PolicyEntry>();
143        parser = new PolicyParser();
144        warnings = new Vector<String>();
145    }
146
147    /**
148     * get the PolicyFileName
149     */
150    String getPolicyFileName() {
151        return policyFileName;
152    }
153
154    /**
155     * set the PolicyFileName
156     */
157    void setPolicyFileName(String policyFileName) {
158        PolicyTool.policyFileName = policyFileName;
159    }
160
161   /**
162    * clear keyStore info
163    */
164    void clearKeyStoreInfo() {
165        this.keyStoreName = null;
166        this.keyStoreType = null;
167        this.keyStoreProvider = null;
168        this.keyStorePwdURL = null;
169
170        this.keyStore = null;
171    }
172
173    /**
174     * get the keyStore URL name
175     */
176    String getKeyStoreName() {
177        return keyStoreName;
178    }
179
180    /**
181     * get the keyStore Type
182     */
183    String getKeyStoreType() {
184        return keyStoreType;
185    }
186
187    /**
188     * get the keyStore Provider
189     */
190    String getKeyStoreProvider() {
191        return keyStoreProvider;
192    }
193
194    /**
195     * get the keyStore password URL
196     */
197    String getKeyStorePwdURL() {
198        return keyStorePwdURL;
199    }
200
201    /**
202     * Open and read a policy file
203     */
204    void openPolicy(String filename) throws FileNotFoundException,
205                                        PolicyParser.ParsingException,
206                                        KeyStoreException,
207                                        CertificateException,
208                                        InstantiationException,
209                                        MalformedURLException,
210                                        IOException,
211                                        NoSuchAlgorithmException,
212                                        IllegalAccessException,
213                                        NoSuchMethodException,
214                                        UnrecoverableKeyException,
215                                        NoSuchProviderException,
216                                        ClassNotFoundException,
217                                        PropertyExpander.ExpandException,
218                                        InvocationTargetException {
219
220        newWarning = false;
221
222        // start fresh - blow away the current state
223        policyEntries = new Vector<PolicyEntry>();
224        parser = new PolicyParser();
225        warnings = new Vector<String>();
226        setPolicyFileName(null);
227        clearKeyStoreInfo();
228
229        // see if user is opening a NEW policy file
230        if (filename == null) {
231            modified = false;
232            return;
233        }
234
235        // Read in the policy entries from the file and
236        // populate the parser vector table.  The parser vector
237        // table only holds the entries as strings, so it only
238        // guarantees that the policies are syntactically
239        // correct.
240        setPolicyFileName(filename);
241        parser.read(new FileReader(filename));
242
243        // open the keystore
244        openKeyStore(parser.getKeyStoreUrl(), parser.getKeyStoreType(),
245                parser.getKeyStoreProvider(), parser.getStorePassURL());
246
247        // Update the local vector with the same policy entries.
248        // This guarantees that the policy entries are not only
249        // syntactically correct, but semantically valid as well.
250        Enumeration<PolicyParser.GrantEntry> enum_ = parser.grantElements();
251        while (enum_.hasMoreElements()) {
252            PolicyParser.GrantEntry ge = enum_.nextElement();
253
254            // see if all the signers have public keys
255            if (ge.signedBy != null) {
256
257                String signers[] = parseSigners(ge.signedBy);
258                for (int i = 0; i < signers.length; i++) {
259                    PublicKey pubKey = getPublicKeyAlias(signers[i]);
260                    if (pubKey == null) {
261                        newWarning = true;
262                        MessageFormat form = new MessageFormat(getMessage
263                            ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));
264                        Object[] source = {signers[i]};
265                        warnings.addElement(form.format(source));
266                    }
267                }
268            }
269
270            // check to see if the Principals are valid
271            ListIterator<PolicyParser.PrincipalEntry> prinList =
272                                                ge.principals.listIterator(0);
273            while (prinList.hasNext()) {
274                PolicyParser.PrincipalEntry pe = prinList.next();
275                try {
276                    verifyPrincipal(pe.getPrincipalClass(),
277                                pe.getPrincipalName());
278                } catch (ClassNotFoundException fnfe) {
279                    newWarning = true;
280                    MessageFormat form = new MessageFormat(getMessage
281                                ("Warning.Class.not.found.class"));
282                    Object[] source = {pe.getPrincipalClass()};
283                    warnings.addElement(form.format(source));
284                }
285            }
286
287            // check to see if the Permissions are valid
288            Enumeration<PolicyParser.PermissionEntry> perms =
289                                                ge.permissionElements();
290            while (perms.hasMoreElements()) {
291                PolicyParser.PermissionEntry pe = perms.nextElement();
292                try {
293                    verifyPermission(pe.permission, pe.name, pe.action);
294                } catch (ClassNotFoundException fnfe) {
295                    newWarning = true;
296                    MessageFormat form = new MessageFormat(getMessage
297                                ("Warning.Class.not.found.class"));
298                    Object[] source = {pe.permission};
299                    warnings.addElement(form.format(source));
300                } catch (InvocationTargetException ite) {
301                    newWarning = true;
302                    MessageFormat form = new MessageFormat(getMessage
303                        ("Warning.Invalid.argument.s.for.constructor.arg"));
304                    Object[] source = {pe.permission};
305                    warnings.addElement(form.format(source));
306                }
307
308                // see if all the permission signers have public keys
309                if (pe.signedBy != null) {
310
311                    String signers[] = parseSigners(pe.signedBy);
312
313                    for (int i = 0; i < signers.length; i++) {
314                        PublicKey pubKey = getPublicKeyAlias(signers[i]);
315                        if (pubKey == null) {
316                            newWarning = true;
317                            MessageFormat form = new MessageFormat(getMessage
318                                ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));
319                            Object[] source = {signers[i]};
320                            warnings.addElement(form.format(source));
321                        }
322                    }
323                }
324            }
325            PolicyEntry pEntry = new PolicyEntry(this, ge);
326            policyEntries.addElement(pEntry);
327        }
328
329        // just read in the policy -- nothing has been modified yet
330        modified = false;
331    }
332
333
334    /**
335     * Save a policy to a file
336     */
337    void savePolicy(String filename)
338    throws FileNotFoundException, IOException {
339        // save the policy entries to a file
340        parser.setKeyStoreUrl(keyStoreName);
341        parser.setKeyStoreType(keyStoreType);
342        parser.setKeyStoreProvider(keyStoreProvider);
343        parser.setStorePassURL(keyStorePwdURL);
344        parser.write(new FileWriter(filename));
345        modified = false;
346    }
347
348    /**
349     * Open the KeyStore
350     */
351    void openKeyStore(String name,
352                String type,
353                String provider,
354                String pwdURL) throws   KeyStoreException,
355                                        NoSuchAlgorithmException,
356                                        UnrecoverableKeyException,
357                                        IOException,
358                                        CertificateException,
359                                        NoSuchProviderException,
360                                        ExpandException {
361
362        if (name == null && type == null &&
363            provider == null && pwdURL == null) {
364
365            // policy did not specify a keystore during open
366            // or use wants to reset keystore values
367
368            this.keyStoreName = null;
369            this.keyStoreType = null;
370            this.keyStoreProvider = null;
371            this.keyStorePwdURL = null;
372
373            // caller will set (tool.modified = true) if appropriate
374
375            return;
376        }
377
378        URL policyURL = null;
379        if (policyFileName != null) {
380            File pfile = new File(policyFileName);
381            policyURL = new URL("file:" + pfile.getCanonicalPath());
382        }
383
384        // although PolicyUtil.getKeyStore may properly handle
385        // defaults and property expansion, we do it here so that
386        // if the call is successful, we can set the proper values
387        // (PolicyUtil.getKeyStore does not return expanded values)
388
389        if (name != null && name.length() > 0) {
390            name = PropertyExpander.expand(name).replace
391                                        (File.separatorChar, '/');
392        }
393        if (type == null || type.length() == 0) {
394            type = KeyStore.getDefaultType();
395        }
396        if (pwdURL != null && pwdURL.length() > 0) {
397            pwdURL = PropertyExpander.expand(pwdURL).replace
398                                        (File.separatorChar, '/');
399        }
400
401        try {
402            this.keyStore = PolicyUtil.getKeyStore(policyURL,
403                                                name,
404                                                type,
405                                                provider,
406                                                pwdURL,
407                                                null);
408        } catch (IOException ioe) {
409
410            // copied from sun.security.pkcs11.SunPKCS11
411            String MSG = "no password provided, and no callback handler " +
412                        "available for retrieving password";
413
414            Throwable cause = ioe.getCause();
415            if (cause != null &&
416                cause instanceof javax.security.auth.login.LoginException &&
417                MSG.equals(cause.getMessage())) {
418
419                // throw a more friendly exception message
420                throw new IOException(MSG);
421            } else {
422                throw ioe;
423            }
424        }
425
426        this.keyStoreName = name;
427        this.keyStoreType = type;
428        this.keyStoreProvider = provider;
429        this.keyStorePwdURL = pwdURL;
430
431        // caller will set (tool.modified = true)
432    }
433
434    /**
435     * Add a Grant entry to the overall policy at the specified index.
436     * A policy entry consists of a CodeSource.
437     */
438    boolean addEntry(PolicyEntry pe, int index) {
439
440        if (index < 0) {
441            // new entry -- just add it to the end
442            policyEntries.addElement(pe);
443            parser.add(pe.getGrantEntry());
444        } else {
445            // existing entry -- replace old one
446            PolicyEntry origPe = policyEntries.elementAt(index);
447            parser.replace(origPe.getGrantEntry(), pe.getGrantEntry());
448            policyEntries.setElementAt(pe, index);
449        }
450        return true;
451    }
452
453    /**
454     * Add a Principal entry to an existing PolicyEntry at the specified index.
455     * A Principal entry consists of a class, and name.
456     *
457     * If the principal already exists, it is not added again.
458     */
459    boolean addPrinEntry(PolicyEntry pe,
460                        PolicyParser.PrincipalEntry newPrin,
461                        int index) {
462
463        // first add the principal to the Policy Parser entry
464        PolicyParser.GrantEntry grantEntry = pe.getGrantEntry();
465        if (grantEntry.contains(newPrin) == true)
466            return false;
467
468        LinkedList<PolicyParser.PrincipalEntry> prinList =
469                                                grantEntry.principals;
470        if (index != -1)
471            prinList.set(index, newPrin);
472        else
473            prinList.add(newPrin);
474
475        modified = true;
476        return true;
477    }
478
479    /**
480     * Add a Permission entry to an existing PolicyEntry at the specified index.
481     * A Permission entry consists of a permission, name, and actions.
482     *
483     * If the permission already exists, it is not added again.
484     */
485    boolean addPermEntry(PolicyEntry pe,
486                        PolicyParser.PermissionEntry newPerm,
487                        int index) {
488
489        // first add the permission to the Policy Parser Vector
490        PolicyParser.GrantEntry grantEntry = pe.getGrantEntry();
491        if (grantEntry.contains(newPerm) == true)
492            return false;
493
494        Vector<PolicyParser.PermissionEntry> permList =
495                                                grantEntry.permissionEntries;
496        if (index != -1)
497            permList.setElementAt(newPerm, index);
498        else
499            permList.addElement(newPerm);
500
501        modified = true;
502        return true;
503    }
504
505    /**
506     * Remove a Permission entry from an existing PolicyEntry.
507     */
508    boolean removePermEntry(PolicyEntry pe,
509                        PolicyParser.PermissionEntry perm) {
510
511        // remove the Permission from the GrantEntry
512        PolicyParser.GrantEntry ppge = pe.getGrantEntry();
513        modified = ppge.remove(perm);
514        return modified;
515    }
516
517    /**
518     * remove an entry from the overall policy
519     */
520    boolean removeEntry(PolicyEntry pe) {
521
522        parser.remove(pe.getGrantEntry());
523        modified = true;
524        return (policyEntries.removeElement(pe));
525    }
526
527    /**
528     * retrieve all Policy Entries
529     */
530    PolicyEntry[] getEntry() {
531
532        if (policyEntries.size() > 0) {
533            PolicyEntry entries[] = new PolicyEntry[policyEntries.size()];
534            for (int i = 0; i < policyEntries.size(); i++)
535                entries[i] = policyEntries.elementAt(i);
536            return entries;
537        }
538        return null;
539    }
540
541    /**
542     * Retrieve the public key mapped to a particular name.
543     * If the key has expired, a KeyException is thrown.
544     */
545    PublicKey getPublicKeyAlias(String name) throws KeyStoreException {
546        if (keyStore == null) {
547            return null;
548        }
549
550        Certificate cert = keyStore.getCertificate(name);
551        if (cert == null) {
552            return null;
553        }
554        PublicKey pubKey = cert.getPublicKey();
555        return pubKey;
556    }
557
558    /**
559     * Retrieve all the alias names stored in the certificate database
560     */
561    String[] getPublicKeyAlias() throws KeyStoreException {
562
563        int numAliases = 0;
564        String aliases[] = null;
565
566        if (keyStore == null) {
567            return null;
568        }
569        Enumeration<String> enum_ = keyStore.aliases();
570
571        // first count the number of elements
572        while (enum_.hasMoreElements()) {
573            enum_.nextElement();
574            numAliases++;
575        }
576
577        if (numAliases > 0) {
578            // now copy them into an array
579            aliases = new String[numAliases];
580            numAliases = 0;
581            enum_ = keyStore.aliases();
582            while (enum_.hasMoreElements()) {
583                aliases[numAliases] = new String(enum_.nextElement());
584                numAliases++;
585            }
586        }
587        return aliases;
588    }
589
590    /**
591     * This method parses a single string of signers separated by commas
592     * ("jordan, duke, pippen") into an array of individual strings.
593     */
594    String[] parseSigners(String signedBy) {
595
596        String signers[] = null;
597        int numSigners = 1;
598        int signedByIndex = 0;
599        int commaIndex = 0;
600        int signerNum = 0;
601
602        // first pass thru "signedBy" counts the number of signers
603        while (commaIndex >= 0) {
604            commaIndex = signedBy.indexOf(',', signedByIndex);
605            if (commaIndex >= 0) {
606                numSigners++;
607                signedByIndex = commaIndex + 1;
608            }
609        }
610        signers = new String[numSigners];
611
612        // second pass thru "signedBy" transfers signers to array
613        commaIndex = 0;
614        signedByIndex = 0;
615        while (commaIndex >= 0) {
616            if ((commaIndex = signedBy.indexOf(',', signedByIndex)) >= 0) {
617                // transfer signer and ignore trailing part of the string
618                signers[signerNum] =
619                        signedBy.substring(signedByIndex, commaIndex).trim();
620                signerNum++;
621                signedByIndex = commaIndex + 1;
622            } else {
623                // we are at the end of the string -- transfer signer
624                signers[signerNum] = signedBy.substring(signedByIndex).trim();
625            }
626        }
627        return signers;
628    }
629
630    /**
631     * Check to see if the Principal contents are OK
632     */
633    void verifyPrincipal(String type, String name)
634        throws ClassNotFoundException,
635               InstantiationException
636    {
637        if (type.equals(PolicyParser.PrincipalEntry.WILDCARD_CLASS) ||
638            type.equals(PolicyParser.PrincipalEntry.REPLACE_NAME)) {
639            return;
640        }
641        Class<?> pc = Class.forName(type, true,
642                Thread.currentThread().getContextClassLoader());
643        if (!Principal.class.isAssignableFrom(pc)) {
644            MessageFormat form = new MessageFormat(getMessage
645                        ("Illegal.Principal.Type.type"));
646            Object[] source = {type};
647            throw new InstantiationException(form.format(source));
648        }
649
650        if (X500Principal.class.getName().equals(pc.getName())) {
651            // PolicyParser checks validity of X500Principal name
652            // - PolicyTool needs to as well so that it doesn't store
653            //   an invalid name that can't be read in later
654            //
655            // this can throw an IllegalArgumentException
656            X500Principal newP = new X500Principal(name);
657        }
658    }
659
660    /**
661     * Check to see if the Permission contents are OK
662     */
663    @SuppressWarnings("fallthrough")
664    void verifyPermission(String type,
665                                    String name,
666                                    String actions)
667        throws ClassNotFoundException,
668               InstantiationException,
669               IllegalAccessException,
670               NoSuchMethodException,
671               InvocationTargetException
672    {
673
674        //XXX we might want to keep a hash of created factories...
675        Class<?> pc = Class.forName(type, true,
676                Thread.currentThread().getContextClassLoader());
677        Constructor<?> c = null;
678        Vector<String> objects = new Vector<>(2);
679        if (name != null) objects.add(name);
680        if (actions != null) objects.add(actions);
681        switch (objects.size()) {
682        case 0:
683            try {
684                c = pc.getConstructor(NOPARAMS);
685                break;
686            } catch (NoSuchMethodException ex) {
687                // proceed to the one-param constructor
688                objects.add(null);
689            }
690            /* fall through */
691        case 1:
692            try {
693                c = pc.getConstructor(ONEPARAMS);
694                break;
695            } catch (NoSuchMethodException ex) {
696                // proceed to the two-param constructor
697                objects.add(null);
698            }
699            /* fall through */
700        case 2:
701            c = pc.getConstructor(TWOPARAMS);
702            break;
703        }
704        Object parameters[] = objects.toArray();
705        Permission p = (Permission)c.newInstance(parameters);
706    }
707
708    /*
709     * Parse command line arguments.
710     */
711    static void parseArgs(String args[]) {
712        /* parse flags */
713        int n = 0;
714
715        for (n=0; (n < args.length) && args[n].startsWith("-"); n++) {
716
717            String flags = args[n];
718
719            if (collator.compare(flags, "-file") == 0) {
720                if (++n == args.length) usage();
721                policyFileName = args[n];
722            } else {
723                MessageFormat form = new MessageFormat(getMessage
724                                ("Illegal.option.option"));
725                Object[] source = { flags };
726                System.err.println(form.format(source));
727                usage();
728            }
729        }
730    }
731
732    static void usage() {
733        System.out.println(getMessage("Usage.policytool.options."));
734        System.out.println();
735        System.out.println(getMessage
736                (".file.file.policy.file.location"));
737        System.out.println();
738
739        System.exit(1);
740    }
741
742    /**
743     * run the PolicyTool
744     */
745    public static void main(String args[]) {
746        System.out.println("Note: The policytool tool has been deprecated and" +
747                " is planned to be removed in a future release.\n");
748        parseArgs(args);
749        SwingUtilities.invokeLater(new Runnable() {
750            public void run() {
751                ToolWindow tw = new ToolWindow(new PolicyTool());
752                tw.displayToolWindow(args);
753            }
754        });
755    }
756
757    // split instr to words according to capitalization,
758    // like, AWTControl -> A W T Control
759    // this method is for easy pronounciation
760    static String splitToWords(String instr) {
761        return instr.replaceAll("([A-Z])", " $1");
762    }
763
764    /**
765     * Returns the message corresponding to the key in the bundle.
766     * This is preferred over {@link #getString} because it removes
767     * any mnemonic '&' character in the string.
768     *
769     * @param key the key
770     *
771     * @return the message
772     */
773    static String getMessage(String key) {
774        return removeMnemonicAmpersand(rb.getString(key));
775    }
776
777
778    /**
779     * Returns the mnemonic for a message.
780     *
781     * @param key the key
782     *
783     * @return the mnemonic <code>int</code>
784     */
785    static int getMnemonicInt(String key) {
786        String message = rb.getString(key);
787        return (findMnemonicInt(message));
788    }
789
790    /**
791     * Returns the mnemonic display index for a message.
792     *
793     * @param key the key
794     *
795     * @return the mnemonic display index
796     */
797    static int getDisplayedMnemonicIndex(String key) {
798        String message = rb.getString(key);
799        return (findMnemonicIndex(message));
800    }
801
802    /**
803     * Finds the mnemonic character in a message.
804     *
805     * The mnemonic character is the first character followed by the first
806     * <code>&</code> that is not followed by another <code>&</code>.
807     *
808     * @return the mnemonic as an <code>int</code>, or <code>0</code> if it
809     *         can't be found.
810     */
811    private static int findMnemonicInt(String s) {
812        for (int i = 0; i < s.length() - 1; i++) {
813            if (s.charAt(i) == '&') {
814                if (s.charAt(i + 1) != '&') {
815                    return KeyEvent.getExtendedKeyCodeForChar(s.charAt(i + 1));
816                } else {
817                    i++;
818                }
819            }
820        }
821        return 0;
822    }
823
824    /**
825     * Finds the index of the mnemonic character in a message.
826     *
827     * The mnemonic character is the first character followed by the first
828     * <code>&</code> that is not followed by another <code>&</code>.
829     *
830     * @return the mnemonic character index as an <code>int</code>, or <code>-1</code> if it
831     *         can't be found.
832     */
833    private static int findMnemonicIndex(String s) {
834        for (int i = 0; i < s.length() - 1; i++) {
835            if (s.charAt(i) == '&') {
836                if (s.charAt(i + 1) != '&') {
837                    // Return the index of the '&' since it will be removed
838                    return i;
839                } else {
840                    i++;
841                }
842            }
843        }
844        return -1;
845    }
846
847    /**
848     * Removes the mnemonic identifier (<code>&</code>) from a string unless
849     * it's escaped by <code>&&</code> or placed at the end.
850     *
851     * @param message the message
852     *
853     * @return a message with the mnemonic identifier removed
854     */
855    private static String removeMnemonicAmpersand(String message) {
856        StringBuilder s = new StringBuilder();
857        for (int i = 0; i < message.length(); i++) {
858            char current = message.charAt(i);
859            if (current != '&' || i == message.length() - 1
860                    || message.charAt(i + 1) == '&') {
861                s.append(current);
862            }
863        }
864        return s.toString();
865    }
866}
867
868/**
869 * Each entry in the policy configuration file is represented by a
870 * PolicyEntry object.
871 *
872 * A PolicyEntry is a (CodeSource,Permission) pair.  The
873 * CodeSource contains the (URL, PublicKey) that together identify
874 * where the Java bytecodes come from and who (if anyone) signed
875 * them.  The URL could refer to localhost.  The URL could also be
876 * null, meaning that this policy entry is given to all comers, as
877 * long as they match the signer field.  The signer could be null,
878 * meaning the code is not signed.
879 *
880 * The Permission contains the (Type, Name, Action) triplet.
881 *
882 */
883@SuppressWarnings({"deprecation",
884                   "removal"}) // PolicyTool
885class PolicyEntry {
886
887    private CodeSource codesource;
888    private PolicyTool tool;
889    private PolicyParser.GrantEntry grantEntry;
890    private boolean testing = false;
891
892    /**
893     * Create a PolicyEntry object from the information read in
894     * from a policy file.
895     */
896    PolicyEntry(PolicyTool tool, PolicyParser.GrantEntry ge)
897    throws MalformedURLException, NoSuchMethodException,
898    ClassNotFoundException, InstantiationException, IllegalAccessException,
899    InvocationTargetException, CertificateException,
900    IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
901
902        this.tool = tool;
903
904        URL location = null;
905
906        // construct the CodeSource
907        if (ge.codeBase != null)
908            location = new URL(ge.codeBase);
909        this.codesource = new CodeSource(location,
910            (java.security.cert.Certificate[]) null);
911
912        if (testing) {
913            System.out.println("Adding Policy Entry:");
914            System.out.println("    CodeBase = " + location);
915            System.out.println("    Signers = " + ge.signedBy);
916            System.out.println("    with " + ge.principals.size() +
917                    " Principals");
918        }
919
920        this.grantEntry = ge;
921    }
922
923    /**
924     * get the codesource associated with this PolicyEntry
925     */
926    CodeSource getCodeSource() {
927        return codesource;
928    }
929
930    /**
931     * get the GrantEntry associated with this PolicyEntry
932     */
933    PolicyParser.GrantEntry getGrantEntry() {
934        return grantEntry;
935    }
936
937    /**
938     * convert the header portion, i.e. codebase, signer, principals, of
939     * this policy entry into a string
940     */
941    String headerToString() {
942        String pString = principalsToString();
943        if (pString.length() == 0) {
944            return codebaseToString();
945        } else {
946            return codebaseToString() + ", " + pString;
947        }
948    }
949
950    /**
951     * convert the Codebase/signer portion of this policy entry into a string
952     */
953    String codebaseToString() {
954
955        String stringEntry = new String();
956
957        if (grantEntry.codeBase != null &&
958            grantEntry.codeBase.equals("") == false)
959            stringEntry = stringEntry.concat
960                                ("CodeBase \"" +
961                                grantEntry.codeBase +
962                                "\"");
963
964        if (grantEntry.signedBy != null &&
965            grantEntry.signedBy.equals("") == false)
966            stringEntry = ((stringEntry.length() > 0) ?
967                stringEntry.concat(", SignedBy \"" +
968                                grantEntry.signedBy +
969                                "\"") :
970                stringEntry.concat("SignedBy \"" +
971                                grantEntry.signedBy +
972                                "\""));
973
974        if (stringEntry.length() == 0)
975            return new String("CodeBase <ALL>");
976        return stringEntry;
977    }
978
979    /**
980     * convert the Principals portion of this policy entry into a string
981     */
982    String principalsToString() {
983        String result = "";
984        if ((grantEntry.principals != null) &&
985            (!grantEntry.principals.isEmpty())) {
986            StringBuilder sb = new StringBuilder(200);
987            ListIterator<PolicyParser.PrincipalEntry> list =
988                                grantEntry.principals.listIterator();
989            while (list.hasNext()) {
990                PolicyParser.PrincipalEntry pppe = list.next();
991                sb.append(" Principal ").append(pppe.getDisplayClass())
992                        .append(' ')
993                        .append(pppe.getDisplayName(true));
994                if (list.hasNext()) sb.append(", ");
995            }
996            result = sb.toString();
997        }
998        return result;
999    }
1000
1001    /**
1002     * convert this policy entry into a PolicyParser.PermissionEntry
1003     */
1004    PolicyParser.PermissionEntry toPermissionEntry(Permission perm) {
1005
1006        String actions = null;
1007
1008        // get the actions
1009        if (perm.getActions() != null &&
1010            perm.getActions().trim() != "")
1011                actions = perm.getActions();
1012
1013        PolicyParser.PermissionEntry pe = new PolicyParser.PermissionEntry
1014                        (perm.getClass().getName(),
1015                        perm.getName(),
1016                        actions);
1017        return pe;
1018    }
1019}
1020
1021/**
1022 * The main window for the PolicyTool
1023 */
1024@SuppressWarnings({"deprecation",
1025                   "removal"}) // PolicyTool
1026class ToolWindow extends JFrame {
1027    // use serialVersionUID from JDK 1.2.2 for interoperability
1028    private static final long serialVersionUID = 5682568601210376777L;
1029
1030    /* ESCAPE key */
1031    static final KeyStroke escKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
1032
1033    /* external paddings */
1034    public static final Insets TOP_PADDING = new Insets(25,0,0,0);
1035    public static final Insets BOTTOM_PADDING = new Insets(0,0,25,0);
1036    public static final Insets LITE_BOTTOM_PADDING = new Insets(0,0,10,0);
1037    public static final Insets LR_PADDING = new Insets(0,10,0,10);
1038    public static final Insets TOP_BOTTOM_PADDING = new Insets(15, 0, 15, 0);
1039    public static final Insets L_TOP_BOTTOM_PADDING = new Insets(5,10,15,0);
1040    public static final Insets LR_TOP_BOTTOM_PADDING = new Insets(15, 4, 15, 4);
1041    public static final Insets LR_BOTTOM_PADDING = new Insets(0,10,5,10);
1042    public static final Insets L_BOTTOM_PADDING = new Insets(0,10,5,0);
1043    public static final Insets R_BOTTOM_PADDING = new Insets(0, 0, 25, 5);
1044    public static final Insets R_PADDING = new Insets(0, 0, 0, 5);
1045
1046    /* buttons and menus */
1047    public static final String NEW_POLICY_FILE          = "New";
1048    public static final String OPEN_POLICY_FILE         = "Open";
1049    public static final String SAVE_POLICY_FILE         = "Save";
1050    public static final String SAVE_AS_POLICY_FILE      = "Save.As";
1051    public static final String VIEW_WARNINGS            = "View.Warning.Log";
1052    public static final String QUIT                     = "Exit";
1053    public static final String ADD_POLICY_ENTRY         = "Add.Policy.Entry";
1054    public static final String EDIT_POLICY_ENTRY        = "Edit.Policy.Entry";
1055    public static final String REMOVE_POLICY_ENTRY      = "Remove.Policy.Entry";
1056    public static final String EDIT_KEYSTORE            = "Edit";
1057    public static final String ADD_PUBKEY_ALIAS         = "Add.Public.Key.Alias";
1058    public static final String REMOVE_PUBKEY_ALIAS      = "Remove.Public.Key.Alias";
1059
1060    /* gridbag index for components in the main window (MW) */
1061    public static final int MW_FILENAME_LABEL           = 0;
1062    public static final int MW_FILENAME_TEXTFIELD       = 1;
1063    public static final int MW_PANEL                    = 2;
1064    public static final int MW_ADD_BUTTON               = 0;
1065    public static final int MW_EDIT_BUTTON              = 1;
1066    public static final int MW_REMOVE_BUTTON            = 2;
1067    public static final int MW_POLICY_LIST              = 3; // follows MW_PANEL
1068
1069    /* The preferred height of JTextField should match JComboBox. */
1070    static final int TEXTFIELD_HEIGHT = new JComboBox<>().getPreferredSize().height;
1071
1072    private PolicyTool tool;
1073
1074    /**
1075     * Constructor
1076     */
1077    ToolWindow(PolicyTool tool) {
1078        this.tool = tool;
1079    }
1080
1081    /**
1082     * Don't call getComponent directly on the window
1083     */
1084    public Component getComponent(int n) {
1085        Component c = getContentPane().getComponent(n);
1086        if (c instanceof JScrollPane) {
1087            c = ((JScrollPane)c).getViewport().getView();
1088        }
1089        return c;
1090    }
1091
1092    /**
1093     * Initialize the PolicyTool window with the necessary components
1094     */
1095    private void initWindow() {
1096        // The ToolWindowListener will handle closing the window.
1097        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
1098
1099        // create the top menu bar
1100        JMenuBar menuBar = new JMenuBar();
1101
1102        // create a File menu
1103        JMenu menu = new JMenu();
1104        configureButton(menu, "File");
1105        ActionListener actionListener = new FileMenuListener(tool, this);
1106        addMenuItem(menu, NEW_POLICY_FILE, actionListener, "N");
1107        addMenuItem(menu, OPEN_POLICY_FILE, actionListener, "O");
1108        addMenuItem(menu, SAVE_POLICY_FILE, actionListener, "S");
1109        addMenuItem(menu, SAVE_AS_POLICY_FILE, actionListener, null);
1110        addMenuItem(menu, VIEW_WARNINGS, actionListener, null);
1111        addMenuItem(menu, QUIT, actionListener, null);
1112        menuBar.add(menu);
1113
1114        // create a KeyStore menu
1115        menu = new JMenu();
1116        configureButton(menu, "KeyStore");
1117        actionListener = new MainWindowListener(tool, this);
1118        addMenuItem(menu, EDIT_KEYSTORE, actionListener, null);
1119        menuBar.add(menu);
1120        setJMenuBar(menuBar);
1121
1122        // Create some space around components
1123        ((JPanel)getContentPane()).setBorder(new EmptyBorder(6, 6, 6, 6));
1124
1125        // policy entry listing
1126        JLabel label = new JLabel(PolicyTool.getMessage("Policy.File."));
1127        addNewComponent(this, label, MW_FILENAME_LABEL,
1128                        0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
1129                        LR_TOP_BOTTOM_PADDING);
1130        JTextField tf = new JTextField(50);
1131        tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
1132        tf.getAccessibleContext().setAccessibleName(
1133                PolicyTool.getMessage("Policy.File."));
1134        tf.setEditable(false);
1135        addNewComponent(this, tf, MW_FILENAME_TEXTFIELD,
1136                        1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
1137                        LR_TOP_BOTTOM_PADDING);
1138
1139
1140        // add ADD/REMOVE/EDIT buttons in a new panel
1141        JPanel panel = new JPanel();
1142        panel.setLayout(new GridBagLayout());
1143
1144        JButton button = new JButton();
1145        configureButton(button, ADD_POLICY_ENTRY);
1146        button.addActionListener(new MainWindowListener(tool, this));
1147        addNewComponent(panel, button, MW_ADD_BUTTON,
1148                        0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
1149                        LR_PADDING);
1150
1151        button = new JButton();
1152        configureButton(button, EDIT_POLICY_ENTRY);
1153        button.addActionListener(new MainWindowListener(tool, this));
1154        addNewComponent(panel, button, MW_EDIT_BUTTON,
1155                        1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
1156                        LR_PADDING);
1157
1158        button = new JButton();
1159        configureButton(button, REMOVE_POLICY_ENTRY);
1160        button.addActionListener(new MainWindowListener(tool, this));
1161        addNewComponent(panel, button, MW_REMOVE_BUTTON,
1162                        2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
1163                        LR_PADDING);
1164
1165        addNewComponent(this, panel, MW_PANEL,
1166                        0, 2, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH,
1167                        BOTTOM_PADDING);
1168
1169
1170        String policyFile = tool.getPolicyFileName();
1171        if (policyFile == null) {
1172            String userHome;
1173            userHome = java.security.AccessController.doPrivileged(
1174                (PrivilegedAction<String>) () -> System.getProperty("user.home"));
1175            policyFile = userHome + File.separatorChar + ".java.policy";
1176        }
1177
1178        try {
1179            // open the policy file
1180            tool.openPolicy(policyFile);
1181
1182            // display the policy entries via the policy list textarea
1183            DefaultListModel<String> listModel = new DefaultListModel<>();
1184            JList<String> list = new JList<>(listModel);
1185            list.setVisibleRowCount(15);
1186            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
1187            list.addMouseListener(new PolicyListListener(tool, this));
1188            PolicyEntry entries[] = tool.getEntry();
1189            if (entries != null) {
1190                for (int i = 0; i < entries.length; i++) {
1191                    listModel.addElement(entries[i].headerToString());
1192                }
1193            }
1194            JTextField newFilename = (JTextField)
1195                                getComponent(MW_FILENAME_TEXTFIELD);
1196            newFilename.setText(policyFile);
1197            initPolicyList(list);
1198
1199        } catch (FileNotFoundException fnfe) {
1200            // add blank policy listing
1201            JList<String> list = new JList<>(new DefaultListModel<>());
1202            list.setVisibleRowCount(15);
1203            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
1204            list.addMouseListener(new PolicyListListener(tool, this));
1205            initPolicyList(list);
1206            tool.setPolicyFileName(null);
1207            tool.modified = false;
1208
1209            // just add warning
1210            tool.warnings.addElement(fnfe.toString());
1211
1212        } catch (Exception e) {
1213            // add blank policy listing
1214            JList<String> list = new JList<>(new DefaultListModel<>());
1215            list.setVisibleRowCount(15);
1216            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
1217            list.addMouseListener(new PolicyListListener(tool, this));
1218            initPolicyList(list);
1219            tool.setPolicyFileName(null);
1220            tool.modified = false;
1221
1222            // display the error
1223            MessageFormat form = new MessageFormat(PolicyTool.getMessage
1224                ("Could.not.open.policy.file.policyFile.e.toString."));
1225            Object[] source = {policyFile, e.toString()};
1226            displayErrorDialog(null, form.format(source));
1227        }
1228    }
1229
1230
1231    // Platform specific modifier (control / command).
1232    private int shortCutModifier = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
1233
1234    private void addMenuItem(JMenu menu, String key, ActionListener actionListener, String accelerator) {
1235        JMenuItem menuItem = new JMenuItem();
1236        configureButton(menuItem, key);
1237
1238        if (PolicyTool.rb.containsKey(key + ".accelerator")) {
1239            // Accelerator from resources takes precedence
1240            accelerator = PolicyTool.getMessage(key + ".accelerator");
1241        }
1242
1243        if (accelerator != null && !accelerator.isEmpty()) {
1244            KeyStroke keyStroke;
1245            if (accelerator.length() == 1) {
1246                keyStroke = KeyStroke.getKeyStroke(KeyEvent.getExtendedKeyCodeForChar(accelerator.charAt(0)),
1247                                                   shortCutModifier);
1248            } else {
1249                keyStroke = KeyStroke.getKeyStroke(accelerator);
1250            }
1251            menuItem.setAccelerator(keyStroke);
1252        }
1253
1254        menuItem.addActionListener(actionListener);
1255        menu.add(menuItem);
1256    }
1257
1258    static void configureButton(AbstractButton button, String key) {
1259        button.setText(PolicyTool.getMessage(key));
1260        button.setActionCommand(key);
1261
1262        int mnemonicInt = PolicyTool.getMnemonicInt(key);
1263        if (mnemonicInt > 0) {
1264            button.setMnemonic(mnemonicInt);
1265            button.setDisplayedMnemonicIndex(PolicyTool.getDisplayedMnemonicIndex(key));
1266         }
1267    }
1268
1269    static void configureLabelFor(JLabel label, JComponent component, String key) {
1270        label.setText(PolicyTool.getMessage(key));
1271        label.setLabelFor(component);
1272
1273        int mnemonicInt = PolicyTool.getMnemonicInt(key);
1274        if (mnemonicInt > 0) {
1275            label.setDisplayedMnemonic(mnemonicInt);
1276            label.setDisplayedMnemonicIndex(PolicyTool.getDisplayedMnemonicIndex(key));
1277         }
1278    }
1279
1280
1281    /**
1282     * Add a component to the PolicyTool window
1283     */
1284    void addNewComponent(Container container, JComponent component,
1285        int index, int gridx, int gridy, int gridwidth, int gridheight,
1286        double weightx, double weighty, int fill, Insets is) {
1287
1288        if (container instanceof JFrame) {
1289            container = ((JFrame)container).getContentPane();
1290        } else if (container instanceof JDialog) {
1291            container = ((JDialog)container).getContentPane();
1292        }
1293
1294        // add the component at the specified gridbag index
1295        container.add(component, index);
1296
1297        // set the constraints
1298        GridBagLayout gbl = (GridBagLayout)container.getLayout();
1299        GridBagConstraints gbc = new GridBagConstraints();
1300        gbc.gridx = gridx;
1301        gbc.gridy = gridy;
1302        gbc.gridwidth = gridwidth;
1303        gbc.gridheight = gridheight;
1304        gbc.weightx = weightx;
1305        gbc.weighty = weighty;
1306        gbc.fill = fill;
1307        if (is != null) gbc.insets = is;
1308        gbl.setConstraints(component, gbc);
1309    }
1310
1311
1312    /**
1313     * Add a component to the PolicyTool window without external padding
1314     */
1315    void addNewComponent(Container container, JComponent component,
1316        int index, int gridx, int gridy, int gridwidth, int gridheight,
1317        double weightx, double weighty, int fill) {
1318
1319        // delegate with "null" external padding
1320        addNewComponent(container, component, index, gridx, gridy,
1321                        gridwidth, gridheight, weightx, weighty,
1322                        fill, null);
1323    }
1324
1325
1326    /**
1327     * Init the policy_entry_list TEXTAREA component in the
1328     * PolicyTool window
1329     */
1330    void initPolicyList(JList<String> policyList) {
1331
1332        // add the policy list to the window
1333        //policyList.setPreferredSize(new Dimension(500, 350));
1334        JScrollPane scrollPane = new JScrollPane(policyList);
1335        addNewComponent(this, scrollPane, MW_POLICY_LIST,
1336                        0, 3, 2, 1, 1.0, 1.0, GridBagConstraints.BOTH);
1337    }
1338
1339    /**
1340     * Replace the policy_entry_list TEXTAREA component in the
1341     * PolicyTool window with an updated one.
1342     */
1343    void replacePolicyList(JList<String> policyList) {
1344
1345        // remove the original list of Policy Entries
1346        // and add the new list of entries
1347        @SuppressWarnings("unchecked")
1348        JList<String> list = (JList<String>)getComponent(MW_POLICY_LIST);
1349        list.setModel(policyList.getModel());
1350    }
1351
1352    /**
1353     * display the main PolicyTool window
1354     */
1355    void displayToolWindow(String args[]) {
1356
1357        setTitle(PolicyTool.getMessage("Policy.Tool"));
1358        setResizable(true);
1359        addWindowListener(new ToolWindowListener(tool, this));
1360        //setBounds(135, 80, 500, 500);
1361        getContentPane().setLayout(new GridBagLayout());
1362
1363        initWindow();
1364        pack();
1365        setLocationRelativeTo(null);
1366
1367        // display it
1368        setVisible(true);
1369
1370        if (tool.newWarning == true) {
1371            displayStatusDialog(this, PolicyTool.getMessage
1372                ("Errors.have.occurred.while.opening.the.policy.configuration.View.the.Warning.Log.for.more.information."));
1373        }
1374    }
1375
1376    /**
1377     * displays a dialog box describing an error which occurred.
1378     */
1379    void displayErrorDialog(Window w, String error) {
1380        ToolDialog ed = new ToolDialog
1381                (PolicyTool.getMessage("Error"), tool, this, true);
1382
1383        ed.setLayout(new GridBagLayout());
1384
1385        JLabel label = new JLabel(error);
1386        addNewComponent(ed, label, 0,
1387                        0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
1388
1389        JButton okButton = new JButton(PolicyTool.getMessage("OK"));
1390        ActionListener okListener = new ErrorOKButtonListener(ed);
1391        okButton.addActionListener(okListener);
1392        addNewComponent(ed, okButton, 1,
1393                        0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
1394
1395        ed.getRootPane().setDefaultButton(okButton);
1396        ed.getRootPane().registerKeyboardAction(okListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
1397
1398        ed.pack();
1399        ed.setLocationRelativeTo(w);
1400        ed.setVisible(true);
1401    }
1402
1403    /**
1404     * displays a dialog box describing an error which occurred.
1405     */
1406    void displayErrorDialog(Window w, Throwable t) {
1407        if (t instanceof NoDisplayException) {
1408            return;
1409        }
1410        if (t.getClass() == Exception.class) {
1411            // Exception is usually thrown inside policytool for user
1412            // interaction error. There is no need to show the type.
1413            displayErrorDialog(w, t.getLocalizedMessage());
1414        } else {
1415            displayErrorDialog(w, t.toString());
1416        }
1417    }
1418
1419    /**
1420     * displays a dialog box describing the status of an event
1421     */
1422    void displayStatusDialog(Window w, String status) {
1423        ToolDialog sd = new ToolDialog
1424                (PolicyTool.getMessage("Status"), tool, this, true);
1425
1426        // find the location of the PolicyTool gui
1427        Point location = ((w == null) ?
1428                getLocationOnScreen() : w.getLocationOnScreen());
1429        //sd.setBounds(location.x + 50, location.y + 50, 500, 100);
1430        sd.setLayout(new GridBagLayout());
1431
1432        JLabel label = new JLabel(status);
1433        addNewComponent(sd, label, 0,
1434                        0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
1435
1436        JButton okButton = new JButton(PolicyTool.getMessage("OK"));
1437        ActionListener okListener = new StatusOKButtonListener(sd);
1438        okButton.addActionListener(okListener);
1439        addNewComponent(sd, okButton, 1,
1440                        0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
1441
1442        sd.getRootPane().setDefaultButton(okButton);
1443        sd.getRootPane().registerKeyboardAction(okListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
1444
1445        sd.pack();
1446        sd.setLocationRelativeTo(w);
1447        sd.setVisible(true);
1448    }
1449
1450    /**
1451     * display the warning log
1452     */
1453    void displayWarningLog(Window w) {
1454
1455        ToolDialog wd = new ToolDialog
1456                (PolicyTool.getMessage("Warning"), tool, this, true);
1457
1458        // find the location of the PolicyTool gui
1459        Point location = ((w == null) ?
1460                getLocationOnScreen() : w.getLocationOnScreen());
1461        //wd.setBounds(location.x + 50, location.y + 50, 500, 100);
1462        wd.setLayout(new GridBagLayout());
1463
1464        JTextArea ta = new JTextArea();
1465        ta.setEditable(false);
1466        for (int i = 0; i < tool.warnings.size(); i++) {
1467            ta.append(tool.warnings.elementAt(i));
1468            ta.append(PolicyTool.getMessage("NEWLINE"));
1469        }
1470        addNewComponent(wd, ta, 0,
1471                        0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
1472                        BOTTOM_PADDING);
1473        ta.setFocusable(false);
1474
1475        JButton okButton = new JButton(PolicyTool.getMessage("OK"));
1476        ActionListener okListener = new CancelButtonListener(wd);
1477        okButton.addActionListener(okListener);
1478        addNewComponent(wd, okButton, 1,
1479                        0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
1480                        LR_PADDING);
1481
1482        wd.getRootPane().setDefaultButton(okButton);
1483        wd.getRootPane().registerKeyboardAction(okListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
1484
1485        wd.pack();
1486        wd.setLocationRelativeTo(w);
1487        wd.setVisible(true);
1488    }
1489
1490    char displayYesNoDialog(Window w, String title, String prompt, String yes, String no) {
1491
1492        final ToolDialog tw = new ToolDialog
1493                (title, tool, this, true);
1494        Point location = ((w == null) ?
1495                getLocationOnScreen() : w.getLocationOnScreen());
1496        //tw.setBounds(location.x + 75, location.y + 100, 400, 150);
1497        tw.setLayout(new GridBagLayout());
1498
1499        JTextArea ta = new JTextArea(prompt, 10, 50);
1500        ta.setEditable(false);
1501        ta.setLineWrap(true);
1502        ta.setWrapStyleWord(true);
1503        JScrollPane scrollPane = new JScrollPane(ta,
1504                                                 JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
1505                                                 JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
1506        addNewComponent(tw, scrollPane, 0,
1507                0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
1508        ta.setFocusable(false);
1509
1510        JPanel panel = new JPanel();
1511        panel.setLayout(new GridBagLayout());
1512
1513        // StringBuffer to store button press. Must be final.
1514        final StringBuffer chooseResult = new StringBuffer();
1515
1516        JButton button = new JButton(yes);
1517        button.addActionListener(new ActionListener() {
1518            public void actionPerformed(ActionEvent e) {
1519                chooseResult.append('Y');
1520                tw.setVisible(false);
1521                tw.dispose();
1522            }
1523        });
1524        addNewComponent(panel, button, 0,
1525                           0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
1526                           LR_PADDING);
1527
1528        button = new JButton(no);
1529        button.addActionListener(new ActionListener() {
1530            public void actionPerformed(ActionEvent e) {
1531                chooseResult.append('N');
1532                tw.setVisible(false);
1533                tw.dispose();
1534            }
1535        });
1536        addNewComponent(panel, button, 1,
1537                           1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
1538                           LR_PADDING);
1539
1540        addNewComponent(tw, panel, 1,
1541                0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
1542
1543        tw.pack();
1544        tw.setLocationRelativeTo(w);
1545        tw.setVisible(true);
1546        if (chooseResult.length() > 0) {
1547            return chooseResult.charAt(0);
1548        } else {
1549            // I did encounter this once, don't why.
1550            return 'N';
1551        }
1552    }
1553
1554}
1555
1556/**
1557 * General dialog window
1558 */
1559@SuppressWarnings({"deprecation",
1560                   "removal"}) // PolicyTool
1561class ToolDialog extends JDialog {
1562    // use serialVersionUID from JDK 1.2.2 for interoperability
1563    private static final long serialVersionUID = -372244357011301190L;
1564
1565    /* ESCAPE key */
1566    static final KeyStroke escKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
1567
1568    /* necessary constants */
1569    public static final int NOACTION            = 0;
1570    public static final int QUIT                = 1;
1571    public static final int NEW                 = 2;
1572    public static final int OPEN                = 3;
1573
1574    /* popup menus */
1575    public static final String PERM             =
1576        PolicyTool.getMessage
1577        ("Permission.");
1578
1579    public static final String PRIN_TYPE        =
1580        PolicyTool.getMessage("Principal.Type.");
1581    public static final String PRIN_NAME        =
1582        PolicyTool.getMessage("Principal.Name.");
1583
1584    /* more popu menus */
1585    public static final String PERM_NAME        =
1586        PolicyTool.getMessage
1587        ("Target.Name.");
1588
1589    /* and more popup menus */
1590    public static final String PERM_ACTIONS             =
1591      PolicyTool.getMessage
1592      ("Actions.");
1593
1594    /* gridbag index for display PolicyEntry (PE) components */
1595    public static final int PE_CODEBASE_LABEL           = 0;
1596    public static final int PE_CODEBASE_TEXTFIELD       = 1;
1597    public static final int PE_SIGNEDBY_LABEL           = 2;
1598    public static final int PE_SIGNEDBY_TEXTFIELD       = 3;
1599
1600    public static final int PE_PANEL0                   = 4;
1601    public static final int PE_ADD_PRIN_BUTTON          = 0;
1602    public static final int PE_EDIT_PRIN_BUTTON         = 1;
1603    public static final int PE_REMOVE_PRIN_BUTTON       = 2;
1604
1605    public static final int PE_PRIN_LABEL               = 5;
1606    public static final int PE_PRIN_LIST                = 6;
1607
1608    public static final int PE_PANEL1                   = 7;
1609    public static final int PE_ADD_PERM_BUTTON          = 0;
1610    public static final int PE_EDIT_PERM_BUTTON         = 1;
1611    public static final int PE_REMOVE_PERM_BUTTON       = 2;
1612
1613    public static final int PE_PERM_LIST                = 8;
1614
1615    public static final int PE_PANEL2                   = 9;
1616    public static final int PE_CANCEL_BUTTON            = 1;
1617    public static final int PE_DONE_BUTTON              = 0;
1618
1619    /* the gridbag index for components in the Principal Dialog (PRD) */
1620    public static final int PRD_DESC_LABEL              = 0;
1621    public static final int PRD_PRIN_CHOICE             = 1;
1622    public static final int PRD_PRIN_TEXTFIELD          = 2;
1623    public static final int PRD_NAME_LABEL              = 3;
1624    public static final int PRD_NAME_TEXTFIELD          = 4;
1625    public static final int PRD_CANCEL_BUTTON           = 6;
1626    public static final int PRD_OK_BUTTON               = 5;
1627
1628    /* the gridbag index for components in the Permission Dialog (PD) */
1629    public static final int PD_DESC_LABEL               = 0;
1630    public static final int PD_PERM_CHOICE              = 1;
1631    public static final int PD_PERM_TEXTFIELD           = 2;
1632    public static final int PD_NAME_CHOICE              = 3;
1633    public static final int PD_NAME_TEXTFIELD           = 4;
1634    public static final int PD_ACTIONS_CHOICE           = 5;
1635    public static final int PD_ACTIONS_TEXTFIELD        = 6;
1636    public static final int PD_SIGNEDBY_LABEL           = 7;
1637    public static final int PD_SIGNEDBY_TEXTFIELD       = 8;
1638    public static final int PD_CANCEL_BUTTON            = 10;
1639    public static final int PD_OK_BUTTON                = 9;
1640
1641    /* modes for KeyStore */
1642    public static final int EDIT_KEYSTORE               = 0;
1643
1644    /* the gridbag index for components in the Change KeyStore Dialog (KSD) */
1645    public static final int KSD_NAME_LABEL              = 0;
1646    public static final int KSD_NAME_TEXTFIELD          = 1;
1647    public static final int KSD_TYPE_LABEL              = 2;
1648    public static final int KSD_TYPE_TEXTFIELD          = 3;
1649    public static final int KSD_PROVIDER_LABEL          = 4;
1650    public static final int KSD_PROVIDER_TEXTFIELD      = 5;
1651    public static final int KSD_PWD_URL_LABEL           = 6;
1652    public static final int KSD_PWD_URL_TEXTFIELD       = 7;
1653    public static final int KSD_CANCEL_BUTTON           = 9;
1654    public static final int KSD_OK_BUTTON               = 8;
1655
1656    /* the gridbag index for components in the User Save Changes Dialog (USC) */
1657    public static final int USC_LABEL                   = 0;
1658    public static final int USC_PANEL                   = 1;
1659    public static final int USC_YES_BUTTON              = 0;
1660    public static final int USC_NO_BUTTON               = 1;
1661    public static final int USC_CANCEL_BUTTON           = 2;
1662
1663    /* gridbag index for the ConfirmRemovePolicyEntryDialog (CRPE) */
1664    public static final int CRPE_LABEL1                 = 0;
1665    public static final int CRPE_LABEL2                 = 1;
1666    public static final int CRPE_PANEL                  = 2;
1667    public static final int CRPE_PANEL_OK               = 0;
1668    public static final int CRPE_PANEL_CANCEL           = 1;
1669
1670    /* some private static finals */
1671    private static final int PERMISSION                 = 0;
1672    private static final int PERMISSION_NAME            = 1;
1673    private static final int PERMISSION_ACTIONS         = 2;
1674    private static final int PERMISSION_SIGNEDBY        = 3;
1675    private static final int PRINCIPAL_TYPE             = 4;
1676    private static final int PRINCIPAL_NAME             = 5;
1677
1678    /* The preferred height of JTextField should match JComboBox. */
1679    static final int TEXTFIELD_HEIGHT = new JComboBox<>().getPreferredSize().height;
1680
1681    public static java.util.ArrayList<Perm> PERM_ARRAY;
1682    public static java.util.ArrayList<Prin> PRIN_ARRAY;
1683    PolicyTool tool;
1684    ToolWindow tw;
1685
1686    static {
1687
1688        // set up permission objects
1689
1690        PERM_ARRAY = new java.util.ArrayList<Perm>();
1691        PERM_ARRAY.add(new AllPerm());
1692        PERM_ARRAY.add(new AudioPerm());
1693        PERM_ARRAY.add(new AuthPerm());
1694        PERM_ARRAY.add(new AWTPerm());
1695        PERM_ARRAY.add(new DelegationPerm());
1696        PERM_ARRAY.add(new FilePerm());
1697        PERM_ARRAY.add(new URLPerm());
1698        PERM_ARRAY.add(new InqSecContextPerm());
1699        PERM_ARRAY.add(new LogPerm());
1700        PERM_ARRAY.add(new MgmtPerm());
1701        PERM_ARRAY.add(new MBeanPerm());
1702        PERM_ARRAY.add(new MBeanSvrPerm());
1703        PERM_ARRAY.add(new MBeanTrustPerm());
1704        PERM_ARRAY.add(new NetPerm());
1705        PERM_ARRAY.add(new NetworkPerm());
1706        PERM_ARRAY.add(new PrivCredPerm());
1707        PERM_ARRAY.add(new PropPerm());
1708        PERM_ARRAY.add(new ReflectPerm());
1709        PERM_ARRAY.add(new RuntimePerm());
1710        PERM_ARRAY.add(new SecurityPerm());
1711        PERM_ARRAY.add(new SerialPerm());
1712        PERM_ARRAY.add(new ServicePerm());
1713        PERM_ARRAY.add(new SocketPerm());
1714        PERM_ARRAY.add(new SQLPerm());
1715        PERM_ARRAY.add(new SSLPerm());
1716        PERM_ARRAY.add(new SubjDelegPerm());
1717
1718        // set up principal objects
1719
1720        PRIN_ARRAY = new java.util.ArrayList<Prin>();
1721        PRIN_ARRAY.add(new KrbPrin());
1722        PRIN_ARRAY.add(new X500Prin());
1723    }
1724
1725    ToolDialog(String title, PolicyTool tool, ToolWindow tw, boolean modal) {
1726        super(tw, modal);
1727        setTitle(title);
1728        this.tool = tool;
1729        this.tw = tw;
1730        addWindowListener(new ChildWindowListener(this));
1731
1732        // Create some space around components
1733        ((JPanel)getContentPane()).setBorder(new EmptyBorder(6, 6, 6, 6));
1734    }
1735
1736    /**
1737     * Don't call getComponent directly on the window
1738     */
1739    public Component getComponent(int n) {
1740        Component c = getContentPane().getComponent(n);
1741        if (c instanceof JScrollPane) {
1742            c = ((JScrollPane)c).getViewport().getView();
1743        }
1744        return c;
1745    }
1746
1747    /**
1748     * get the Perm instance based on either the (shortened) class name
1749     * or the fully qualified class name
1750     */
1751    static Perm getPerm(String clazz, boolean fullClassName) {
1752        for (int i = 0; i < PERM_ARRAY.size(); i++) {
1753            Perm next = PERM_ARRAY.get(i);
1754            if (fullClassName) {
1755                if (next.getName().equals(clazz)) {
1756                    return next;
1757                }
1758            } else {
1759                if (next.getSimpleName().equals(clazz)) {
1760                    return next;
1761                }
1762            }
1763        }
1764        return null;
1765    }
1766
1767    /**
1768     * get the Prin instance based on either the (shortened) class name
1769     * or the fully qualified class name
1770     */
1771    static Prin getPrin(String clazz, boolean fullClassName) {
1772        for (int i = 0; i < PRIN_ARRAY.size(); i++) {
1773            Prin next = PRIN_ARRAY.get(i);
1774            if (fullClassName) {
1775                if (next.getName().equals(clazz)) {
1776                    return next;
1777                }
1778            } else {
1779                if (next.getSimpleName().equals(clazz)) {
1780                    return next;
1781                }
1782            }
1783        }
1784        return null;
1785    }
1786
1787    /**
1788     * pop up a dialog so the user can enter info to add a new PolicyEntry
1789     * - if edit is TRUE, then the user is editing an existing entry
1790     *   and we should display the original info as well.
1791     *
1792     * - the other reason we need the 'edit' boolean is we need to know
1793     *   when we are adding a NEW policy entry.  in this case, we can
1794     *   not simply update the existing entry, because it doesn't exist.
1795     *   we ONLY update the GUI listing/info, and then when the user
1796     *   finally clicks 'OK' or 'DONE', then we can collect that info
1797     *   and add it to the policy.
1798     */
1799    void displayPolicyEntryDialog(boolean edit) {
1800
1801        int listIndex = 0;
1802        PolicyEntry entries[] = null;
1803        TaggedList prinList = new TaggedList(3, false);
1804        prinList.getAccessibleContext().setAccessibleName(
1805                PolicyTool.getMessage("Principal.List"));
1806        prinList.addMouseListener
1807                (new EditPrinButtonListener(tool, tw, this, edit));
1808        TaggedList permList = new TaggedList(10, false);
1809        permList.getAccessibleContext().setAccessibleName(
1810                PolicyTool.getMessage("Permission.List"));
1811        permList.addMouseListener
1812                (new EditPermButtonListener(tool, tw, this, edit));
1813
1814        // find where the PolicyTool gui is
1815        Point location = tw.getLocationOnScreen();
1816        //setBounds(location.x + 75, location.y + 200, 650, 500);
1817        setLayout(new GridBagLayout());
1818        setResizable(true);
1819
1820        if (edit) {
1821            // get the selected item
1822            entries = tool.getEntry();
1823            @SuppressWarnings("unchecked")
1824            JList<String> policyList = (JList<String>)tw.getComponent(ToolWindow.MW_POLICY_LIST);
1825            listIndex = policyList.getSelectedIndex();
1826
1827            // get principal list
1828            LinkedList<PolicyParser.PrincipalEntry> principals =
1829                entries[listIndex].getGrantEntry().principals;
1830            for (int i = 0; i < principals.size(); i++) {
1831                String prinString = null;
1832                PolicyParser.PrincipalEntry nextPrin = principals.get(i);
1833                prinList.addTaggedItem(PrincipalEntryToUserFriendlyString(nextPrin), nextPrin);
1834            }
1835
1836            // get permission list
1837            Vector<PolicyParser.PermissionEntry> permissions =
1838                entries[listIndex].getGrantEntry().permissionEntries;
1839            for (int i = 0; i < permissions.size(); i++) {
1840                String permString = null;
1841                PolicyParser.PermissionEntry nextPerm =
1842                                                permissions.elementAt(i);
1843                permList.addTaggedItem(ToolDialog.PermissionEntryToUserFriendlyString(nextPerm), nextPerm);
1844            }
1845        }
1846
1847        // codebase label and textfield
1848        JLabel label = new JLabel();
1849        tw.addNewComponent(this, label, PE_CODEBASE_LABEL,
1850                0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
1851                ToolWindow.R_PADDING);
1852        JTextField tf;
1853        tf = (edit ?
1854                new JTextField(entries[listIndex].getGrantEntry().codeBase) :
1855                new JTextField());
1856        ToolWindow.configureLabelFor(label, tf, "CodeBase.");
1857        tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
1858        tf.getAccessibleContext().setAccessibleName(
1859                PolicyTool.getMessage("Code.Base"));
1860        tw.addNewComponent(this, tf, PE_CODEBASE_TEXTFIELD,
1861                1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH);
1862
1863        // signedby label and textfield
1864        label = new JLabel();
1865        tw.addNewComponent(this, label, PE_SIGNEDBY_LABEL,
1866                           0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
1867                           ToolWindow.R_PADDING);
1868        tf = (edit ?
1869                new JTextField(entries[listIndex].getGrantEntry().signedBy) :
1870                new JTextField());
1871        ToolWindow.configureLabelFor(label, tf, "SignedBy.");
1872        tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
1873        tf.getAccessibleContext().setAccessibleName(
1874                PolicyTool.getMessage("Signed.By."));
1875        tw.addNewComponent(this, tf, PE_SIGNEDBY_TEXTFIELD,
1876                           1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH);
1877
1878        // panel for principal buttons
1879        JPanel panel = new JPanel();
1880        panel.setLayout(new GridBagLayout());
1881
1882        JButton button = new JButton();
1883        ToolWindow.configureButton(button, "Add.Principal");
1884        button.addActionListener
1885                (new AddPrinButtonListener(tool, tw, this, edit));
1886        tw.addNewComponent(panel, button, PE_ADD_PRIN_BUTTON,
1887                0, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);
1888
1889        button = new JButton();
1890        ToolWindow.configureButton(button, "Edit.Principal");
1891        button.addActionListener(new EditPrinButtonListener
1892                                                (tool, tw, this, edit));
1893        tw.addNewComponent(panel, button, PE_EDIT_PRIN_BUTTON,
1894                1, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);
1895
1896        button = new JButton();
1897        ToolWindow.configureButton(button, "Remove.Principal");
1898        button.addActionListener(new RemovePrinButtonListener
1899                                        (tool, tw, this, edit));
1900        tw.addNewComponent(panel, button, PE_REMOVE_PRIN_BUTTON,
1901                2, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);
1902
1903        tw.addNewComponent(this, panel, PE_PANEL0,
1904                1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.HORIZONTAL,
1905                           ToolWindow.LITE_BOTTOM_PADDING);
1906
1907        // principal label and list
1908        label = new JLabel();
1909        tw.addNewComponent(this, label, PE_PRIN_LABEL,
1910                           0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
1911                           ToolWindow.R_BOTTOM_PADDING);
1912        JScrollPane scrollPane = new JScrollPane(prinList);
1913        ToolWindow.configureLabelFor(label, scrollPane, "Principals.");
1914        tw.addNewComponent(this, scrollPane, PE_PRIN_LIST,
1915                           1, 3, 3, 1, 0.0, prinList.getVisibleRowCount(), GridBagConstraints.BOTH,
1916                           ToolWindow.BOTTOM_PADDING);
1917
1918        // panel for permission buttons
1919        panel = new JPanel();
1920        panel.setLayout(new GridBagLayout());
1921
1922        button = new JButton();
1923        ToolWindow.configureButton(button, ".Add.Permission");
1924        button.addActionListener(new AddPermButtonListener
1925                                                (tool, tw, this, edit));
1926        tw.addNewComponent(panel, button, PE_ADD_PERM_BUTTON,
1927                0, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);
1928
1929        button = new JButton();
1930        ToolWindow.configureButton(button, ".Edit.Permission");
1931        button.addActionListener(new EditPermButtonListener
1932                                                (tool, tw, this, edit));
1933        tw.addNewComponent(panel, button, PE_EDIT_PERM_BUTTON,
1934                1, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);
1935
1936
1937        button = new JButton();
1938        ToolWindow.configureButton(button, "Remove.Permission");
1939        button.addActionListener(new RemovePermButtonListener
1940                                        (tool, tw, this, edit));
1941        tw.addNewComponent(panel, button, PE_REMOVE_PERM_BUTTON,
1942                2, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);
1943
1944        tw.addNewComponent(this, panel, PE_PANEL1,
1945                0, 4, 2, 1, 0.0, 0.0, GridBagConstraints.HORIZONTAL,
1946                ToolWindow.LITE_BOTTOM_PADDING);
1947
1948        // permission list
1949        scrollPane = new JScrollPane(permList);
1950        tw.addNewComponent(this, scrollPane, PE_PERM_LIST,
1951                           0, 5, 3, 1, 0.0, permList.getVisibleRowCount(), GridBagConstraints.BOTH,
1952                           ToolWindow.BOTTOM_PADDING);
1953
1954
1955        // panel for Done and Cancel buttons
1956        panel = new JPanel();
1957        panel.setLayout(new GridBagLayout());
1958
1959        // Done Button
1960        JButton okButton = new JButton(PolicyTool.getMessage("Done"));
1961        okButton.addActionListener
1962                (new AddEntryDoneButtonListener(tool, tw, this, edit));
1963        tw.addNewComponent(panel, okButton, PE_DONE_BUTTON,
1964                           0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
1965                           ToolWindow.LR_PADDING);
1966
1967        // Cancel Button
1968        JButton cancelButton = new JButton(PolicyTool.getMessage("Cancel"));
1969        ActionListener cancelListener = new CancelButtonListener(this);
1970        cancelButton.addActionListener(cancelListener);
1971        tw.addNewComponent(panel, cancelButton, PE_CANCEL_BUTTON,
1972                           1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
1973                           ToolWindow.LR_PADDING);
1974
1975        // add the panel
1976        tw.addNewComponent(this, panel, PE_PANEL2,
1977                0, 6, 2, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
1978
1979        getRootPane().setDefaultButton(okButton);
1980        getRootPane().registerKeyboardAction(cancelListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
1981
1982        pack();
1983        setLocationRelativeTo(tw);
1984        setVisible(true);
1985    }
1986
1987    /**
1988     * Read all the Policy information data in the dialog box
1989     * and construct a PolicyEntry object with it.
1990     */
1991    PolicyEntry getPolicyEntryFromDialog()
1992        throws InvalidParameterException, MalformedURLException,
1993        NoSuchMethodException, ClassNotFoundException, InstantiationException,
1994        IllegalAccessException, InvocationTargetException,
1995        CertificateException, IOException, Exception {
1996
1997        // get the Codebase
1998        JTextField tf = (JTextField)getComponent(PE_CODEBASE_TEXTFIELD);
1999        String codebase = null;
2000        if (tf.getText().trim().equals("") == false)
2001                codebase = new String(tf.getText().trim());
2002
2003        // get the SignedBy
2004        tf = (JTextField)getComponent(PE_SIGNEDBY_TEXTFIELD);
2005        String signedby = null;
2006        if (tf.getText().trim().equals("") == false)
2007                signedby = new String(tf.getText().trim());
2008
2009        // construct a new GrantEntry
2010        PolicyParser.GrantEntry ge =
2011                        new PolicyParser.GrantEntry(signedby, codebase);
2012
2013        // get the new Principals
2014        LinkedList<PolicyParser.PrincipalEntry> prins = new LinkedList<>();
2015        TaggedList prinList = (TaggedList)getComponent(PE_PRIN_LIST);
2016        for (int i = 0; i < prinList.getModel().getSize(); i++) {
2017            prins.add((PolicyParser.PrincipalEntry)prinList.getObject(i));
2018        }
2019        ge.principals = prins;
2020
2021        // get the new Permissions
2022        Vector<PolicyParser.PermissionEntry> perms = new Vector<>();
2023        TaggedList permList = (TaggedList)getComponent(PE_PERM_LIST);
2024        for (int i = 0; i < permList.getModel().getSize(); i++) {
2025            perms.addElement((PolicyParser.PermissionEntry)permList.getObject(i));
2026        }
2027        ge.permissionEntries = perms;
2028
2029        // construct a new PolicyEntry object
2030        PolicyEntry entry = new PolicyEntry(tool, ge);
2031
2032        return entry;
2033    }
2034
2035    /**
2036     * display a dialog box for the user to enter KeyStore information
2037     */
2038    void keyStoreDialog(int mode) {
2039
2040        // find where the PolicyTool gui is
2041        Point location = tw.getLocationOnScreen();
2042        //setBounds(location.x + 25, location.y + 100, 500, 300);
2043        setLayout(new GridBagLayout());
2044
2045        if (mode == EDIT_KEYSTORE) {
2046
2047            // KeyStore label and textfield
2048            JLabel label = new JLabel();
2049            tw.addNewComponent(this, label, KSD_NAME_LABEL,
2050                               0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2051                               ToolWindow.R_BOTTOM_PADDING);
2052            JTextField tf = new JTextField(tool.getKeyStoreName(), 30);
2053            ToolWindow.configureLabelFor(label, tf, "KeyStore.URL.");
2054            tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
2055
2056            // URL to U R L, so that accessibility reader will pronounce well
2057            tf.getAccessibleContext().setAccessibleName(
2058                PolicyTool.getMessage("KeyStore.U.R.L."));
2059            tw.addNewComponent(this, tf, KSD_NAME_TEXTFIELD,
2060                               1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH,
2061                               ToolWindow.BOTTOM_PADDING);
2062
2063            // KeyStore type and textfield
2064            label = new JLabel();
2065            tw.addNewComponent(this, label, KSD_TYPE_LABEL,
2066                               0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2067                               ToolWindow.R_BOTTOM_PADDING);
2068            tf = new JTextField(tool.getKeyStoreType(), 30);
2069            ToolWindow.configureLabelFor(label, tf, "KeyStore.Type.");
2070            tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
2071            tf.getAccessibleContext().setAccessibleName(
2072                PolicyTool.getMessage("KeyStore.Type."));
2073            tw.addNewComponent(this, tf, KSD_TYPE_TEXTFIELD,
2074                               1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH,
2075                               ToolWindow.BOTTOM_PADDING);
2076
2077            // KeyStore provider and textfield
2078            label = new JLabel();
2079            tw.addNewComponent(this, label, KSD_PROVIDER_LABEL,
2080                               0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2081                               ToolWindow.R_BOTTOM_PADDING);
2082            tf = new JTextField(tool.getKeyStoreProvider(), 30);
2083            ToolWindow.configureLabelFor(label, tf, "KeyStore.Provider.");
2084            tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
2085            tf.getAccessibleContext().setAccessibleName(
2086                PolicyTool.getMessage("KeyStore.Provider."));
2087            tw.addNewComponent(this, tf, KSD_PROVIDER_TEXTFIELD,
2088                               1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH,
2089                               ToolWindow.BOTTOM_PADDING);
2090
2091            // KeyStore password URL and textfield
2092            label = new JLabel();
2093            tw.addNewComponent(this, label, KSD_PWD_URL_LABEL,
2094                               0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2095                               ToolWindow.R_BOTTOM_PADDING);
2096            tf = new JTextField(tool.getKeyStorePwdURL(), 30);
2097            ToolWindow.configureLabelFor(label, tf, "KeyStore.Password.URL.");
2098            tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
2099            tf.getAccessibleContext().setAccessibleName(
2100                PolicyTool.getMessage("KeyStore.Password.U.R.L."));
2101            tw.addNewComponent(this, tf, KSD_PWD_URL_TEXTFIELD,
2102                               1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH,
2103                               ToolWindow.BOTTOM_PADDING);
2104
2105            // OK button
2106            JButton okButton = new JButton(PolicyTool.getMessage("OK"));
2107            okButton.addActionListener
2108                        (new ChangeKeyStoreOKButtonListener(tool, tw, this));
2109            tw.addNewComponent(this, okButton, KSD_OK_BUTTON,
2110                        0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
2111
2112            // cancel button
2113            JButton cancelButton = new JButton(PolicyTool.getMessage("Cancel"));
2114            ActionListener cancelListener = new CancelButtonListener(this);
2115            cancelButton.addActionListener(cancelListener);
2116            tw.addNewComponent(this, cancelButton, KSD_CANCEL_BUTTON,
2117                        1, 4, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
2118
2119            getRootPane().setDefaultButton(okButton);
2120            getRootPane().registerKeyboardAction(cancelListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
2121        }
2122
2123        pack();
2124        setLocationRelativeTo(tw);
2125        setVisible(true);
2126    }
2127
2128    /**
2129     * display a dialog box for the user to input Principal info
2130     *
2131     * if editPolicyEntry is false, then we are adding Principals to
2132     * a new PolicyEntry, and we only update the GUI listing
2133     * with the new Principal.
2134     *
2135     * if edit is true, then we are editing an existing Policy entry.
2136     */
2137    void displayPrincipalDialog(boolean editPolicyEntry, boolean edit) {
2138
2139        PolicyParser.PrincipalEntry editMe = null;
2140
2141        // get the Principal selected from the Principal List
2142        TaggedList prinList = (TaggedList)getComponent(PE_PRIN_LIST);
2143        int prinIndex = prinList.getSelectedIndex();
2144
2145        if (edit) {
2146            editMe = (PolicyParser.PrincipalEntry)prinList.getObject(prinIndex);
2147        }
2148
2149        ToolDialog newTD = new ToolDialog
2150                (PolicyTool.getMessage("Principals"), tool, tw, true);
2151        newTD.addWindowListener(new ChildWindowListener(newTD));
2152
2153        // find where the PolicyTool gui is
2154        Point location = getLocationOnScreen();
2155        //newTD.setBounds(location.x + 50, location.y + 100, 650, 190);
2156        newTD.setLayout(new GridBagLayout());
2157        newTD.setResizable(true);
2158
2159        // description label
2160        JLabel label = (edit ?
2161                new JLabel(PolicyTool.getMessage(".Edit.Principal.")) :
2162                new JLabel(PolicyTool.getMessage(".Add.New.Principal.")));
2163        tw.addNewComponent(newTD, label, PRD_DESC_LABEL,
2164                           0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2165                           ToolWindow.TOP_BOTTOM_PADDING);
2166
2167        // principal choice
2168        JComboBox<String> choice = new JComboBox<>();
2169        choice.addItem(PRIN_TYPE);
2170        choice.getAccessibleContext().setAccessibleName(PRIN_TYPE);
2171        for (int i = 0; i < PRIN_ARRAY.size(); i++) {
2172            Prin next = PRIN_ARRAY.get(i);
2173            choice.addItem(next.getSimpleName());
2174        }
2175
2176        if (edit) {
2177            if (PolicyParser.PrincipalEntry.WILDCARD_CLASS.equals
2178                                (editMe.getPrincipalClass())) {
2179                choice.setSelectedItem(PRIN_TYPE);
2180            } else {
2181                Prin inputPrin = getPrin(editMe.getPrincipalClass(), true);
2182                if (inputPrin != null) {
2183                    choice.setSelectedItem(inputPrin.getSimpleName());
2184                }
2185            }
2186        }
2187        // Add listener after selected item is set
2188        choice.addItemListener(new PrincipalTypeMenuListener(newTD));
2189
2190        tw.addNewComponent(newTD, choice, PRD_PRIN_CHOICE,
2191                           0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2192                           ToolWindow.LR_PADDING);
2193
2194        // principal textfield
2195        JTextField tf;
2196        tf = (edit ?
2197                new JTextField(editMe.getDisplayClass(), 30) :
2198                new JTextField(30));
2199        tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
2200        tf.getAccessibleContext().setAccessibleName(PRIN_TYPE);
2201        tw.addNewComponent(newTD, tf, PRD_PRIN_TEXTFIELD,
2202                           1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH,
2203                           ToolWindow.LR_PADDING);
2204
2205        // name label and textfield
2206        label = new JLabel(PRIN_NAME);
2207        tf = (edit ?
2208                new JTextField(editMe.getDisplayName(), 40) :
2209                new JTextField(40));
2210        tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
2211        tf.getAccessibleContext().setAccessibleName(PRIN_NAME);
2212
2213        tw.addNewComponent(newTD, label, PRD_NAME_LABEL,
2214                           0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2215                           ToolWindow.LR_PADDING);
2216        tw.addNewComponent(newTD, tf, PRD_NAME_TEXTFIELD,
2217                           1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH,
2218                           ToolWindow.LR_PADDING);
2219
2220        // OK button
2221        JButton okButton = new JButton(PolicyTool.getMessage("OK"));
2222        okButton.addActionListener(
2223            new NewPolicyPrinOKButtonListener
2224                                        (tool, tw, this, newTD, edit));
2225        tw.addNewComponent(newTD, okButton, PRD_OK_BUTTON,
2226                           0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
2227                           ToolWindow.TOP_BOTTOM_PADDING);
2228        // cancel button
2229        JButton cancelButton = new JButton(PolicyTool.getMessage("Cancel"));
2230        ActionListener cancelListener = new CancelButtonListener(newTD);
2231        cancelButton.addActionListener(cancelListener);
2232        tw.addNewComponent(newTD, cancelButton, PRD_CANCEL_BUTTON,
2233                           1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
2234                           ToolWindow.TOP_BOTTOM_PADDING);
2235
2236        newTD.getRootPane().setDefaultButton(okButton);
2237        newTD.getRootPane().registerKeyboardAction(cancelListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
2238
2239        newTD.pack();
2240        newTD.setLocationRelativeTo(tw);
2241        newTD.setVisible(true);
2242    }
2243
2244    /**
2245     * display a dialog box for the user to input Permission info
2246     *
2247     * if editPolicyEntry is false, then we are adding Permissions to
2248     * a new PolicyEntry, and we only update the GUI listing
2249     * with the new Permission.
2250     *
2251     * if edit is true, then we are editing an existing Permission entry.
2252     */
2253    void displayPermissionDialog(boolean editPolicyEntry, boolean edit) {
2254
2255        PolicyParser.PermissionEntry editMe = null;
2256
2257        // get the Permission selected from the Permission List
2258        TaggedList permList = (TaggedList)getComponent(PE_PERM_LIST);
2259        int permIndex = permList.getSelectedIndex();
2260
2261        if (edit) {
2262            editMe = (PolicyParser.PermissionEntry)permList.getObject(permIndex);
2263        }
2264
2265        ToolDialog newTD = new ToolDialog
2266                (PolicyTool.getMessage("Permissions"), tool, tw, true);
2267        newTD.addWindowListener(new ChildWindowListener(newTD));
2268
2269        // find where the PolicyTool gui is
2270        Point location = getLocationOnScreen();
2271        //newTD.setBounds(location.x + 50, location.y + 100, 700, 250);
2272        newTD.setLayout(new GridBagLayout());
2273        newTD.setResizable(true);
2274
2275        // description label
2276        JLabel label = (edit ?
2277                new JLabel(PolicyTool.getMessage(".Edit.Permission.")) :
2278                new JLabel(PolicyTool.getMessage(".Add.New.Permission.")));
2279        tw.addNewComponent(newTD, label, PD_DESC_LABEL,
2280                           0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2281                           ToolWindow.TOP_BOTTOM_PADDING);
2282
2283        // permission choice (added in alphabetical order)
2284        JComboBox<String> choice = new JComboBox<>();
2285        choice.addItem(PERM);
2286        choice.getAccessibleContext().setAccessibleName(PERM);
2287        for (int i = 0; i < PERM_ARRAY.size(); i++) {
2288            Perm next = PERM_ARRAY.get(i);
2289            choice.addItem(next.getSimpleName());
2290        }
2291        tw.addNewComponent(newTD, choice, PD_PERM_CHOICE,
2292                           0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2293                           ToolWindow.LR_BOTTOM_PADDING);
2294
2295        // permission textfield
2296        JTextField tf;
2297        tf = (edit ? new JTextField(editMe.permission, 30) : new JTextField(30));
2298        tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
2299        tf.getAccessibleContext().setAccessibleName(PERM);
2300        if (edit) {
2301            Perm inputPerm = getPerm(editMe.permission, true);
2302            if (inputPerm != null) {
2303                choice.setSelectedItem(inputPerm.getSimpleName());
2304            }
2305        }
2306        tw.addNewComponent(newTD, tf, PD_PERM_TEXTFIELD,
2307                           1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH,
2308                           ToolWindow.LR_BOTTOM_PADDING);
2309        choice.addItemListener(new PermissionMenuListener(newTD));
2310
2311        // name label and textfield
2312        choice = new JComboBox<>();
2313        choice.addItem(PERM_NAME);
2314        choice.getAccessibleContext().setAccessibleName(PERM_NAME);
2315        tf = (edit ? new JTextField(editMe.name, 40) : new JTextField(40));
2316        tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
2317        tf.getAccessibleContext().setAccessibleName(PERM_NAME);
2318        if (edit) {
2319            setPermissionNames(getPerm(editMe.permission, true), choice, tf);
2320        }
2321        tw.addNewComponent(newTD, choice, PD_NAME_CHOICE,
2322                           0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2323                           ToolWindow.LR_BOTTOM_PADDING);
2324        tw.addNewComponent(newTD, tf, PD_NAME_TEXTFIELD,
2325                           1, 2, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH,
2326                           ToolWindow.LR_BOTTOM_PADDING);
2327        choice.addItemListener(new PermissionNameMenuListener(newTD));
2328
2329        // actions label and textfield
2330        choice = new JComboBox<>();
2331        choice.addItem(PERM_ACTIONS);
2332        choice.getAccessibleContext().setAccessibleName(PERM_ACTIONS);
2333        tf = (edit ? new JTextField(editMe.action, 40) : new JTextField(40));
2334        tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
2335        tf.getAccessibleContext().setAccessibleName(PERM_ACTIONS);
2336        if (edit) {
2337            setPermissionActions(getPerm(editMe.permission, true), choice, tf);
2338        }
2339        tw.addNewComponent(newTD, choice, PD_ACTIONS_CHOICE,
2340                           0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2341                           ToolWindow.LR_BOTTOM_PADDING);
2342        tw.addNewComponent(newTD, tf, PD_ACTIONS_TEXTFIELD,
2343                           1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH,
2344                           ToolWindow.LR_BOTTOM_PADDING);
2345        choice.addItemListener(new PermissionActionsMenuListener(newTD));
2346
2347        // signedby label and textfield
2348        label = new JLabel(PolicyTool.getMessage("Signed.By."));
2349        tw.addNewComponent(newTD, label, PD_SIGNEDBY_LABEL,
2350                           0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2351                           ToolWindow.LR_BOTTOM_PADDING);
2352        tf = (edit ? new JTextField(editMe.signedBy, 40) : new JTextField(40));
2353        tf.setPreferredSize(new Dimension(tf.getPreferredSize().width, TEXTFIELD_HEIGHT));
2354        tf.getAccessibleContext().setAccessibleName(
2355                PolicyTool.getMessage("Signed.By."));
2356        tw.addNewComponent(newTD, tf, PD_SIGNEDBY_TEXTFIELD,
2357                           1, 4, 1, 1, 1.0, 0.0, GridBagConstraints.BOTH,
2358                           ToolWindow.LR_BOTTOM_PADDING);
2359
2360        // OK button
2361        JButton okButton = new JButton(PolicyTool.getMessage("OK"));
2362        okButton.addActionListener(
2363            new NewPolicyPermOKButtonListener
2364                                    (tool, tw, this, newTD, edit));
2365        tw.addNewComponent(newTD, okButton, PD_OK_BUTTON,
2366                           0, 5, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
2367                           ToolWindow.TOP_BOTTOM_PADDING);
2368
2369        // cancel button
2370        JButton cancelButton = new JButton(PolicyTool.getMessage("Cancel"));
2371        ActionListener cancelListener = new CancelButtonListener(newTD);
2372        cancelButton.addActionListener(cancelListener);
2373        tw.addNewComponent(newTD, cancelButton, PD_CANCEL_BUTTON,
2374                           1, 5, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
2375                           ToolWindow.TOP_BOTTOM_PADDING);
2376
2377        newTD.getRootPane().setDefaultButton(okButton);
2378        newTD.getRootPane().registerKeyboardAction(cancelListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
2379
2380        newTD.pack();
2381        newTD.setLocationRelativeTo(tw);
2382        newTD.setVisible(true);
2383    }
2384
2385    /**
2386     * construct a Principal object from the Principal Info Dialog Box
2387     */
2388    PolicyParser.PrincipalEntry getPrinFromDialog() throws Exception {
2389
2390        JTextField tf = (JTextField)getComponent(PRD_PRIN_TEXTFIELD);
2391        String pclass = new String(tf.getText().trim());
2392        tf = (JTextField)getComponent(PRD_NAME_TEXTFIELD);
2393        String pname = new String(tf.getText().trim());
2394        if (pclass.equals("*")) {
2395            pclass = PolicyParser.PrincipalEntry.WILDCARD_CLASS;
2396        }
2397        if (pname.equals("*")) {
2398            pname = PolicyParser.PrincipalEntry.WILDCARD_NAME;
2399        }
2400
2401        PolicyParser.PrincipalEntry pppe = null;
2402
2403        if ((pclass.equals(PolicyParser.PrincipalEntry.WILDCARD_CLASS)) &&
2404            (!pname.equals(PolicyParser.PrincipalEntry.WILDCARD_NAME))) {
2405            throw new Exception
2406                        (PolicyTool.getMessage("Cannot.Specify.Principal.with.a.Wildcard.Class.without.a.Wildcard.Name"));
2407        } else if (pname.equals("")) {
2408            throw new Exception
2409                        (PolicyTool.getMessage("Cannot.Specify.Principal.without.a.Name"));
2410        } else if (pclass.equals("")) {
2411            // make this consistent with what PolicyParser does
2412            // when it sees an empty principal class
2413            pclass = PolicyParser.PrincipalEntry.REPLACE_NAME;
2414            tool.warnings.addElement(
2415                        "Warning: Principal name '" + pname +
2416                                "' specified without a Principal class.\n" +
2417                        "\t'" + pname + "' will be interpreted " +
2418                                "as a key store alias.\n" +
2419                        "\tThe final principal class will be " +
2420                                X500Principal.class.getName() + ".\n" +
2421                        "\tThe final principal name will be " +
2422                                "determined by the following:\n" +
2423                        "\n" +
2424                        "\tIf the key store entry identified by '"
2425                                + pname + "'\n" +
2426                        "\tis a key entry, then the principal name will be\n" +
2427                        "\tthe subject distinguished name from the first\n" +
2428                        "\tcertificate in the entry's certificate chain.\n" +
2429                        "\n" +
2430                        "\tIf the key store entry identified by '" +
2431                                pname + "'\n" +
2432                        "\tis a trusted certificate entry, then the\n" +
2433                        "\tprincipal name will be the subject distinguished\n" +
2434                        "\tname from the trusted public key certificate.");
2435            tw.displayStatusDialog(this,
2436                        "'" + pname + "' will be interpreted as a key " +
2437                        "store alias.  View Warning Log for details.");
2438        }
2439        return new PolicyParser.PrincipalEntry(pclass, pname);
2440    }
2441
2442
2443    /**
2444     * construct a Permission object from the Permission Info Dialog Box
2445     */
2446    PolicyParser.PermissionEntry getPermFromDialog() {
2447
2448        JTextField tf = (JTextField)getComponent(PD_PERM_TEXTFIELD);
2449        String permission = new String(tf.getText().trim());
2450        tf = (JTextField)getComponent(PD_NAME_TEXTFIELD);
2451        String name = null;
2452        if (tf.getText().trim().equals("") == false)
2453            name = new String(tf.getText().trim());
2454        if (permission.equals("") ||
2455            (!permission.equals(AllPermission.class.getName()) && name == null)) {
2456            throw new InvalidParameterException(PolicyTool.getMessage
2457                ("Permission.and.Target.Name.must.have.a.value"));
2458        }
2459
2460        // When the permission is FilePermission, we need to check the name
2461        // to make sure it's not escaped. We believe --
2462        //
2463        // String             name.lastIndexOf("\\\\")
2464        // ----------------   ------------------------
2465        // c:\foo\bar         -1, legal
2466        // c:\\foo\\bar       2, illegal
2467        // \\server\share     0, legal
2468        // \\\\server\share   2, illegal
2469
2470        if (permission.equals(FilePermission.class.getName())
2471                && name.lastIndexOf("\\\\") > 0) {
2472            char result = tw.displayYesNoDialog(this,
2473                    PolicyTool.getMessage("Warning"),
2474                    PolicyTool.getMessage(
2475                        "Warning.File.name.may.include.escaped.backslash.characters.It.is.not.necessary.to.escape.backslash.characters.the.tool.escapes"),
2476                    PolicyTool.getMessage("Retain"),
2477                    PolicyTool.getMessage("Edit")
2478                    );
2479            if (result != 'Y') {
2480                // an invisible exception
2481                throw new NoDisplayException();
2482            }
2483        }
2484        // get the Actions
2485        tf = (JTextField)getComponent(PD_ACTIONS_TEXTFIELD);
2486        String actions = null;
2487        if (tf.getText().trim().equals("") == false)
2488            actions = new String(tf.getText().trim());
2489
2490        // get the Signed By
2491        tf = (JTextField)getComponent(PD_SIGNEDBY_TEXTFIELD);
2492        String signedBy = null;
2493        if (tf.getText().trim().equals("") == false)
2494            signedBy = new String(tf.getText().trim());
2495
2496        PolicyParser.PermissionEntry pppe = new PolicyParser.PermissionEntry
2497                                (permission, name, actions);
2498        pppe.signedBy = signedBy;
2499
2500        // see if the signers have public keys
2501        if (signedBy != null) {
2502                String signers[] = tool.parseSigners(pppe.signedBy);
2503                for (int i = 0; i < signers.length; i++) {
2504                try {
2505                    PublicKey pubKey = tool.getPublicKeyAlias(signers[i]);
2506                    if (pubKey == null) {
2507                        MessageFormat form = new MessageFormat
2508                            (PolicyTool.getMessage
2509                            ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));
2510                        Object[] source = {signers[i]};
2511                        tool.warnings.addElement(form.format(source));
2512                        tw.displayStatusDialog(this, form.format(source));
2513                    }
2514                } catch (Exception e) {
2515                    tw.displayErrorDialog(this, e);
2516                }
2517            }
2518        }
2519        return pppe;
2520    }
2521
2522    /**
2523     * confirm that the user REALLY wants to remove the Policy Entry
2524     */
2525    void displayConfirmRemovePolicyEntry() {
2526
2527        // find the entry to be removed
2528        @SuppressWarnings("unchecked")
2529        JList<String> list = (JList<String>)tw.getComponent(ToolWindow.MW_POLICY_LIST);
2530        int index = list.getSelectedIndex();
2531        PolicyEntry entries[] = tool.getEntry();
2532
2533        // find where the PolicyTool gui is
2534        Point location = tw.getLocationOnScreen();
2535        //setBounds(location.x + 25, location.y + 100, 600, 400);
2536        setLayout(new GridBagLayout());
2537
2538        // ask the user do they really want to do this?
2539        JLabel label = new JLabel
2540                (PolicyTool.getMessage("Remove.this.Policy.Entry."));
2541        tw.addNewComponent(this, label, CRPE_LABEL1,
2542                           0, 0, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2543                           ToolWindow.BOTTOM_PADDING);
2544
2545        // display the policy entry
2546        label = new JLabel(entries[index].codebaseToString());
2547        tw.addNewComponent(this, label, CRPE_LABEL2,
2548                        0, 1, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH);
2549        label = new JLabel(entries[index].principalsToString().trim());
2550        tw.addNewComponent(this, label, CRPE_LABEL2+1,
2551                        0, 2, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH);
2552        Vector<PolicyParser.PermissionEntry> perms =
2553                        entries[index].getGrantEntry().permissionEntries;
2554        for (int i = 0; i < perms.size(); i++) {
2555            PolicyParser.PermissionEntry nextPerm = perms.elementAt(i);
2556            String permString = ToolDialog.PermissionEntryToUserFriendlyString(nextPerm);
2557            label = new JLabel("    " + permString);
2558            if (i == (perms.size()-1)) {
2559                tw.addNewComponent(this, label, CRPE_LABEL2 + 2 + i,
2560                                 1, 3 + i, 1, 1, 0.0, 0.0,
2561                                 GridBagConstraints.BOTH,
2562                                 ToolWindow.BOTTOM_PADDING);
2563            } else {
2564                tw.addNewComponent(this, label, CRPE_LABEL2 + 2 + i,
2565                                 1, 3 + i, 1, 1, 0.0, 0.0,
2566                                 GridBagConstraints.BOTH);
2567            }
2568        }
2569
2570
2571        // add OK/CANCEL buttons in a new panel
2572        JPanel panel = new JPanel();
2573        panel.setLayout(new GridBagLayout());
2574
2575        // OK button
2576        JButton okButton = new JButton(PolicyTool.getMessage("OK"));
2577        okButton.addActionListener
2578                (new ConfirmRemovePolicyEntryOKButtonListener(tool, tw, this));
2579        tw.addNewComponent(panel, okButton, CRPE_PANEL_OK,
2580                           0, 0, 1, 1, 0.0, 0.0,
2581                           GridBagConstraints.VERTICAL, ToolWindow.LR_PADDING);
2582
2583        // cancel button
2584        JButton cancelButton = new JButton(PolicyTool.getMessage("Cancel"));
2585        ActionListener cancelListener = new CancelButtonListener(this);
2586        cancelButton.addActionListener(cancelListener);
2587        tw.addNewComponent(panel, cancelButton, CRPE_PANEL_CANCEL,
2588                           1, 0, 1, 1, 0.0, 0.0,
2589                           GridBagConstraints.VERTICAL, ToolWindow.LR_PADDING);
2590
2591        tw.addNewComponent(this, panel, CRPE_LABEL2 + 2 + perms.size(),
2592                           0, 3 + perms.size(), 2, 1, 0.0, 0.0,
2593                           GridBagConstraints.VERTICAL, ToolWindow.TOP_BOTTOM_PADDING);
2594
2595        getRootPane().setDefaultButton(okButton);
2596        getRootPane().registerKeyboardAction(cancelListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
2597
2598        pack();
2599        setLocationRelativeTo(tw);
2600        setVisible(true);
2601    }
2602
2603    /**
2604     * perform SAVE AS
2605     */
2606    void displaySaveAsDialog(int nextEvent) {
2607
2608        // pop up a dialog box for the user to enter a filename.
2609        FileDialog fd = new FileDialog
2610                (tw, PolicyTool.getMessage("Save.As"), FileDialog.SAVE);
2611        fd.addWindowListener(new WindowAdapter() {
2612            public void windowClosing(WindowEvent e) {
2613                e.getWindow().setVisible(false);
2614            }
2615        });
2616        fd.setVisible(true);
2617
2618        // see if the user hit cancel
2619        if (fd.getFile() == null ||
2620            fd.getFile().equals(""))
2621            return;
2622
2623        // get the entered filename
2624        File saveAsFile = new File(fd.getDirectory(), fd.getFile());
2625        String filename = saveAsFile.getPath();
2626        fd.dispose();
2627
2628        try {
2629            // save the policy entries to a file
2630            tool.savePolicy(filename);
2631
2632            // display status
2633            MessageFormat form = new MessageFormat(PolicyTool.getMessage
2634                    ("Policy.successfully.written.to.filename"));
2635            Object[] source = {filename};
2636            tw.displayStatusDialog(null, form.format(source));
2637
2638            // display the new policy filename
2639            JTextField newFilename = (JTextField)tw.getComponent
2640                            (ToolWindow.MW_FILENAME_TEXTFIELD);
2641            newFilename.setText(filename);
2642            tw.setVisible(true);
2643
2644            // now continue with the originally requested command
2645            // (QUIT, NEW, or OPEN)
2646            userSaveContinue(tool, tw, this, nextEvent);
2647
2648        } catch (FileNotFoundException fnfe) {
2649            if (filename == null || filename.equals("")) {
2650                tw.displayErrorDialog(null, new FileNotFoundException
2651                            (PolicyTool.getMessage("null.filename")));
2652            } else {
2653                tw.displayErrorDialog(null, fnfe);
2654            }
2655        } catch (Exception ee) {
2656            tw.displayErrorDialog(null, ee);
2657        }
2658    }
2659
2660    /**
2661     * ask user if they want to save changes
2662     */
2663    void displayUserSave(int select) {
2664
2665        if (tool.modified == true) {
2666
2667            // find where the PolicyTool gui is
2668            Point location = tw.getLocationOnScreen();
2669            //setBounds(location.x + 75, location.y + 100, 400, 150);
2670            setLayout(new GridBagLayout());
2671
2672            JLabel label = new JLabel
2673                (PolicyTool.getMessage("Save.changes."));
2674            tw.addNewComponent(this, label, USC_LABEL,
2675                               0, 0, 3, 1, 0.0, 0.0, GridBagConstraints.BOTH,
2676                               ToolWindow.L_TOP_BOTTOM_PADDING);
2677
2678            JPanel panel = new JPanel();
2679            panel.setLayout(new GridBagLayout());
2680
2681            JButton yesButton = new JButton();
2682            ToolWindow.configureButton(yesButton, "Yes");
2683            yesButton.addActionListener
2684                        (new UserSaveYesButtonListener(this, tool, tw, select));
2685            tw.addNewComponent(panel, yesButton, USC_YES_BUTTON,
2686                               0, 0, 1, 1, 0.0, 0.0,
2687                               GridBagConstraints.VERTICAL,
2688                               ToolWindow.LR_BOTTOM_PADDING);
2689            JButton noButton = new JButton();
2690            ToolWindow.configureButton(noButton, "No");
2691            noButton.addActionListener
2692                        (new UserSaveNoButtonListener(this, tool, tw, select));
2693            tw.addNewComponent(panel, noButton, USC_NO_BUTTON,
2694                               1, 0, 1, 1, 0.0, 0.0,
2695                               GridBagConstraints.VERTICAL,
2696                               ToolWindow.LR_BOTTOM_PADDING);
2697            JButton cancelButton = new JButton();
2698            ToolWindow.configureButton(cancelButton, "Cancel");
2699            ActionListener cancelListener = new CancelButtonListener(this);
2700            cancelButton.addActionListener(cancelListener);
2701            tw.addNewComponent(panel, cancelButton, USC_CANCEL_BUTTON,
2702                               2, 0, 1, 1, 0.0, 0.0,
2703                               GridBagConstraints.VERTICAL,
2704                               ToolWindow.LR_BOTTOM_PADDING);
2705
2706            tw.addNewComponent(this, panel, USC_PANEL,
2707                               0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
2708
2709            getRootPane().registerKeyboardAction(cancelListener, escKey, JComponent.WHEN_IN_FOCUSED_WINDOW);
2710
2711            pack();
2712            setLocationRelativeTo(tw);
2713            setVisible(true);
2714        } else {
2715            // just do the original request (QUIT, NEW, or OPEN)
2716            userSaveContinue(tool, tw, this, select);
2717        }
2718    }
2719
2720    /**
2721     * when the user sees the 'YES', 'NO', 'CANCEL' buttons on the
2722     * displayUserSave dialog, and the click on one of them,
2723     * we need to continue the originally requested action
2724     * (either QUITting, opening NEW policy file, or OPENing an existing
2725     * policy file.  do that now.
2726     */
2727    @SuppressWarnings("fallthrough")
2728    void userSaveContinue(PolicyTool tool, ToolWindow tw,
2729                        ToolDialog us, int select) {
2730
2731        // now either QUIT, open a NEW policy file, or OPEN an existing policy
2732        switch(select) {
2733        case ToolDialog.QUIT:
2734
2735            tw.setVisible(false);
2736            tw.dispose();
2737            System.exit(0);
2738
2739        case ToolDialog.NEW:
2740
2741            try {
2742                tool.openPolicy(null);
2743            } catch (Exception ee) {
2744                tool.modified = false;
2745                tw.displayErrorDialog(null, ee);
2746            }
2747
2748            // display the policy entries via the policy list textarea
2749            JList<String> list = new JList<>(new DefaultListModel<>());
2750            list.setVisibleRowCount(15);
2751            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
2752            list.addMouseListener(new PolicyListListener(tool, tw));
2753            tw.replacePolicyList(list);
2754
2755            // display null policy filename and keystore
2756            JTextField newFilename = (JTextField)tw.getComponent(
2757                    ToolWindow.MW_FILENAME_TEXTFIELD);
2758            newFilename.setText("");
2759            tw.setVisible(true);
2760            break;
2761
2762        case ToolDialog.OPEN:
2763
2764            // pop up a dialog box for the user to enter a filename.
2765            FileDialog fd = new FileDialog
2766                (tw, PolicyTool.getMessage("Open"), FileDialog.LOAD);
2767            fd.addWindowListener(new WindowAdapter() {
2768                public void windowClosing(WindowEvent e) {
2769                    e.getWindow().setVisible(false);
2770                }
2771            });
2772            fd.setVisible(true);
2773
2774            // see if the user hit 'cancel'
2775            if (fd.getFile() == null ||
2776                fd.getFile().equals(""))
2777                return;
2778
2779            // get the entered filename
2780            String policyFile = new File(fd.getDirectory(), fd.getFile()).getPath();
2781
2782            try {
2783                // open the policy file
2784                tool.openPolicy(policyFile);
2785
2786                // display the policy entries via the policy list textarea
2787                DefaultListModel<String> listModel = new DefaultListModel<>();
2788                list = new JList<>(listModel);
2789                list.setVisibleRowCount(15);
2790                list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
2791                list.addMouseListener(new PolicyListListener(tool, tw));
2792                PolicyEntry entries[] = tool.getEntry();
2793                if (entries != null) {
2794                    for (int i = 0; i < entries.length; i++) {
2795                        listModel.addElement(entries[i].headerToString());
2796                    }
2797                }
2798                tw.replacePolicyList(list);
2799                tool.modified = false;
2800
2801                // display the new policy filename
2802                newFilename = (JTextField)tw.getComponent(
2803                        ToolWindow.MW_FILENAME_TEXTFIELD);
2804                newFilename.setText(policyFile);
2805                tw.setVisible(true);
2806
2807                // inform user of warnings
2808                if (tool.newWarning == true) {
2809                    tw.displayStatusDialog(null, PolicyTool.getMessage
2810                        ("Errors.have.occurred.while.opening.the.policy.configuration.View.the.Warning.Log.for.more.information."));
2811                }
2812
2813            } catch (Exception e) {
2814                // add blank policy listing
2815                list = new JList<>(new DefaultListModel<>());
2816                list.setVisibleRowCount(15);
2817                list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
2818                list.addMouseListener(new PolicyListListener(tool, tw));
2819                tw.replacePolicyList(list);
2820                tool.setPolicyFileName(null);
2821                tool.modified = false;
2822
2823                // display a null policy filename
2824                newFilename = (JTextField)tw.getComponent(
2825                        ToolWindow.MW_FILENAME_TEXTFIELD);
2826                newFilename.setText("");
2827                tw.setVisible(true);
2828
2829                // display the error
2830                MessageFormat form = new MessageFormat(PolicyTool.getMessage
2831                    ("Could.not.open.policy.file.policyFile.e.toString."));
2832                Object[] source = {policyFile, e.toString()};
2833                tw.displayErrorDialog(null, form.format(source));
2834            }
2835            break;
2836        }
2837    }
2838
2839    /**
2840     * Return a Menu list of names for a given permission
2841     *
2842     * If inputPerm's TARGETS are null, then this means TARGETS are
2843     * not allowed to be entered (and the TextField is set to be
2844     * non-editable).
2845     *
2846     * If TARGETS are valid but there are no standard ones
2847     * (user must enter them by hand) then the TARGETS array may be empty
2848     * (and of course non-null).
2849     */
2850    void setPermissionNames(Perm inputPerm, JComboBox<String> names, JTextField field) {
2851        names.removeAllItems();
2852        names.addItem(PERM_NAME);
2853
2854        if (inputPerm == null) {
2855            // custom permission
2856            field.setEditable(true);
2857        } else if (inputPerm.TARGETS == null) {
2858            // standard permission with no targets
2859            field.setEditable(false);
2860        } else {
2861            // standard permission with standard targets
2862            field.setEditable(true);
2863            for (int i = 0; i < inputPerm.TARGETS.length; i++) {
2864                names.addItem(inputPerm.TARGETS[i]);
2865            }
2866        }
2867    }
2868
2869    /**
2870     * Return a Menu list of actions for a given permission
2871     *
2872     * If inputPerm's ACTIONS are null, then this means ACTIONS are
2873     * not allowed to be entered (and the TextField is set to be
2874     * non-editable).  This is typically true for BasicPermissions.
2875     *
2876     * If ACTIONS are valid but there are no standard ones
2877     * (user must enter them by hand) then the ACTIONS array may be empty
2878     * (and of course non-null).
2879     */
2880    void setPermissionActions(Perm inputPerm, JComboBox<String> actions, JTextField field) {
2881        actions.removeAllItems();
2882        actions.addItem(PERM_ACTIONS);
2883
2884        if (inputPerm == null) {
2885            // custom permission
2886            field.setEditable(true);
2887        } else if (inputPerm.ACTIONS == null) {
2888            // standard permission with no actions
2889            field.setEditable(false);
2890        } else {
2891            // standard permission with standard actions
2892            field.setEditable(true);
2893            for (int i = 0; i < inputPerm.ACTIONS.length; i++) {
2894                actions.addItem(inputPerm.ACTIONS[i]);
2895            }
2896        }
2897    }
2898
2899    static String PermissionEntryToUserFriendlyString(PolicyParser.PermissionEntry pppe) {
2900        String result = pppe.permission;
2901        if (pppe.name != null) {
2902            result += " " + pppe.name;
2903        }
2904        if (pppe.action != null) {
2905            result += ", \"" + pppe.action + "\"";
2906        }
2907        if (pppe.signedBy != null) {
2908            result += ", signedBy " + pppe.signedBy;
2909        }
2910        return result;
2911    }
2912
2913    static String PrincipalEntryToUserFriendlyString(PolicyParser.PrincipalEntry pppe) {
2914        StringWriter sw = new StringWriter();
2915        PrintWriter pw = new PrintWriter(sw);
2916        pppe.write(pw);
2917        return sw.toString();
2918    }
2919}
2920
2921/**
2922 * Event handler for the PolicyTool window
2923 */
2924@SuppressWarnings({"deprecation",
2925                   "removal"}) // PolicyTool
2926class ToolWindowListener implements WindowListener {
2927
2928    private PolicyTool tool;
2929    private ToolWindow tw;
2930
2931    ToolWindowListener(PolicyTool tool, ToolWindow tw) {
2932        this.tool = tool;
2933        this.tw = tw;
2934    }
2935
2936    public void windowOpened(WindowEvent we) {
2937    }
2938
2939    public void windowClosing(WindowEvent we) {
2940        // Closing the window acts the same as choosing Menu->Exit.
2941
2942        // ask user if they want to save changes
2943        ToolDialog td = new ToolDialog(PolicyTool.getMessage("Save.Changes"), tool, tw, true);
2944        td.displayUserSave(ToolDialog.QUIT);
2945
2946        // the above method will perform the QUIT as long as the
2947        // user does not CANCEL the request
2948    }
2949
2950    public void windowClosed(WindowEvent we) {
2951        System.exit(0);
2952    }
2953
2954    public void windowIconified(WindowEvent we) {
2955    }
2956
2957    public void windowDeiconified(WindowEvent we) {
2958    }
2959
2960    public void windowActivated(WindowEvent we) {
2961    }
2962
2963    public void windowDeactivated(WindowEvent we) {
2964    }
2965}
2966
2967/**
2968 * Event handler for the Policy List
2969 */
2970@SuppressWarnings({"deprecation",
2971                   "removal"}) // PolicyTool
2972class PolicyListListener extends MouseAdapter implements ActionListener {
2973
2974    private PolicyTool tool;
2975    private ToolWindow tw;
2976
2977    PolicyListListener(PolicyTool tool, ToolWindow tw) {
2978        this.tool = tool;
2979        this.tw = tw;
2980
2981    }
2982
2983    public void actionPerformed(ActionEvent e) {
2984
2985        // display the permission list for a policy entry
2986        ToolDialog td = new ToolDialog
2987                (PolicyTool.getMessage("Policy.Entry"), tool, tw, true);
2988        td.displayPolicyEntryDialog(true);
2989    }
2990
2991    public void mouseClicked(MouseEvent evt) {
2992        if (evt.getClickCount() == 2) {
2993            actionPerformed(null);
2994        }
2995    }
2996}
2997
2998/**
2999 * Event handler for the File Menu
3000 */
3001@SuppressWarnings({"deprecation",
3002                   "removal"}) // PolicyTool
3003class FileMenuListener implements ActionListener {
3004
3005    private PolicyTool tool;
3006    private ToolWindow tw;
3007
3008    FileMenuListener(PolicyTool tool, ToolWindow tw) {
3009        this.tool = tool;
3010        this.tw = tw;
3011    }
3012
3013    public void actionPerformed(ActionEvent e) {
3014
3015        if (PolicyTool.collator.compare(e.getActionCommand(),
3016                                       ToolWindow.QUIT) == 0) {
3017
3018            // ask user if they want to save changes
3019            ToolDialog td = new ToolDialog
3020                (PolicyTool.getMessage("Save.Changes"), tool, tw, true);
3021            td.displayUserSave(ToolDialog.QUIT);
3022
3023            // the above method will perform the QUIT as long as the
3024            // user does not CANCEL the request
3025
3026        } else if (PolicyTool.collator.compare(e.getActionCommand(),
3027                                   ToolWindow.NEW_POLICY_FILE) == 0) {
3028
3029            // ask user if they want to save changes
3030            ToolDialog td = new ToolDialog
3031                (PolicyTool.getMessage("Save.Changes"), tool, tw, true);
3032            td.displayUserSave(ToolDialog.NEW);
3033
3034            // the above method will perform the NEW as long as the
3035            // user does not CANCEL the request
3036
3037        } else if (PolicyTool.collator.compare(e.getActionCommand(),
3038                                  ToolWindow.OPEN_POLICY_FILE) == 0) {
3039
3040            // ask user if they want to save changes
3041            ToolDialog td = new ToolDialog
3042                (PolicyTool.getMessage("Save.Changes"), tool, tw, true);
3043            td.displayUserSave(ToolDialog.OPEN);
3044
3045            // the above method will perform the OPEN as long as the
3046            // user does not CANCEL the request
3047
3048        } else if (PolicyTool.collator.compare(e.getActionCommand(),
3049                                  ToolWindow.SAVE_POLICY_FILE) == 0) {
3050
3051            // get the previously entered filename
3052            String filename = ((JTextField)tw.getComponent(
3053                    ToolWindow.MW_FILENAME_TEXTFIELD)).getText();
3054
3055            // if there is no filename, do a SAVE_AS
3056            if (filename == null || filename.length() == 0) {
3057                // user wants to SAVE AS
3058                ToolDialog td = new ToolDialog
3059                        (PolicyTool.getMessage("Save.As"), tool, tw, true);
3060                td.displaySaveAsDialog(ToolDialog.NOACTION);
3061            } else {
3062                try {
3063                    // save the policy entries to a file
3064                    tool.savePolicy(filename);
3065
3066                    // display status
3067                    MessageFormat form = new MessageFormat
3068                        (PolicyTool.getMessage
3069                        ("Policy.successfully.written.to.filename"));
3070                    Object[] source = {filename};
3071                    tw.displayStatusDialog(null, form.format(source));
3072                } catch (FileNotFoundException fnfe) {
3073                    if (filename == null || filename.equals("")) {
3074                        tw.displayErrorDialog(null, new FileNotFoundException
3075                                (PolicyTool.getMessage("null.filename")));
3076                    } else {
3077                        tw.displayErrorDialog(null, fnfe);
3078                    }
3079                } catch (Exception ee) {
3080                    tw.displayErrorDialog(null, ee);
3081                }
3082            }
3083        } else if (PolicyTool.collator.compare(e.getActionCommand(),
3084                               ToolWindow.SAVE_AS_POLICY_FILE) == 0) {
3085
3086            // user wants to SAVE AS
3087            ToolDialog td = new ToolDialog
3088                (PolicyTool.getMessage("Save.As"), tool, tw, true);
3089            td.displaySaveAsDialog(ToolDialog.NOACTION);
3090
3091        } else if (PolicyTool.collator.compare(e.getActionCommand(),
3092                                     ToolWindow.VIEW_WARNINGS) == 0) {
3093            tw.displayWarningLog(null);
3094        }
3095    }
3096}
3097
3098/**
3099 * Event handler for the main window buttons and Edit Menu
3100 */
3101@SuppressWarnings({"deprecation",
3102                   "removal"}) // PolicyTool
3103class MainWindowListener implements ActionListener {
3104
3105    private PolicyTool tool;
3106    private ToolWindow tw;
3107
3108    MainWindowListener(PolicyTool tool, ToolWindow tw) {
3109        this.tool = tool;
3110        this.tw = tw;
3111    }
3112
3113    public void actionPerformed(ActionEvent e) {
3114
3115        if (PolicyTool.collator.compare(e.getActionCommand(),
3116                           ToolWindow.ADD_POLICY_ENTRY) == 0) {
3117
3118            // display a dialog box for the user to enter policy info
3119            ToolDialog td = new ToolDialog
3120                (PolicyTool.getMessage("Policy.Entry"), tool, tw, true);
3121            td.displayPolicyEntryDialog(false);
3122
3123        } else if (PolicyTool.collator.compare(e.getActionCommand(),
3124                               ToolWindow.REMOVE_POLICY_ENTRY) == 0) {
3125
3126            // get the selected entry
3127            @SuppressWarnings("unchecked")
3128            JList<String> list = (JList<String>)tw.getComponent(ToolWindow.MW_POLICY_LIST);
3129            int index = list.getSelectedIndex();
3130            if (index < 0) {
3131                tw.displayErrorDialog(null, new Exception
3132                        (PolicyTool.getMessage("No.Policy.Entry.selected")));
3133                return;
3134            }
3135
3136            // ask the user if they really want to remove the policy entry
3137            ToolDialog td = new ToolDialog(PolicyTool.getMessage
3138                ("Remove.Policy.Entry"), tool, tw, true);
3139            td.displayConfirmRemovePolicyEntry();
3140
3141        } else if (PolicyTool.collator.compare(e.getActionCommand(),
3142                                 ToolWindow.EDIT_POLICY_ENTRY) == 0) {
3143
3144            // get the selected entry
3145            @SuppressWarnings("unchecked")
3146            JList<String> list = (JList<String>)tw.getComponent(ToolWindow.MW_POLICY_LIST);
3147            int index = list.getSelectedIndex();
3148            if (index < 0) {
3149                tw.displayErrorDialog(null, new Exception
3150                        (PolicyTool.getMessage("No.Policy.Entry.selected")));
3151                return;
3152            }
3153
3154            // display the permission list for a policy entry
3155            ToolDialog td = new ToolDialog
3156                (PolicyTool.getMessage("Policy.Entry"), tool, tw, true);
3157            td.displayPolicyEntryDialog(true);
3158
3159        } else if (PolicyTool.collator.compare(e.getActionCommand(),
3160                                     ToolWindow.EDIT_KEYSTORE) == 0) {
3161
3162            // display a dialog box for the user to enter keystore info
3163            ToolDialog td = new ToolDialog
3164                (PolicyTool.getMessage("KeyStore"), tool, tw, true);
3165            td.keyStoreDialog(ToolDialog.EDIT_KEYSTORE);
3166        }
3167    }
3168}
3169
3170/**
3171 * Event handler for AddEntryDoneButton button
3172 *
3173 * -- if edit is TRUE, then we are EDITing an existing PolicyEntry
3174 *    and we need to update both the policy and the GUI listing.
3175 *    if edit is FALSE, then we are ADDing a new PolicyEntry,
3176 *    so we only need to update the GUI listing.
3177 */
3178@SuppressWarnings({"deprecation",
3179                   "removal"}) // PolicyTool
3180class AddEntryDoneButtonListener implements ActionListener {
3181
3182    private PolicyTool tool;
3183    private ToolWindow tw;
3184    private ToolDialog td;
3185    private boolean edit;
3186
3187    AddEntryDoneButtonListener(PolicyTool tool, ToolWindow tw,
3188                                ToolDialog td, boolean edit) {
3189        this.tool = tool;
3190        this.tw = tw;
3191        this.td = td;
3192        this.edit = edit;
3193    }
3194
3195    public void actionPerformed(ActionEvent e) {
3196
3197        try {
3198            // get a PolicyEntry object from the dialog policy info
3199            PolicyEntry newEntry = td.getPolicyEntryFromDialog();
3200            PolicyParser.GrantEntry newGe = newEntry.getGrantEntry();
3201
3202            // see if all the signers have public keys
3203            if (newGe.signedBy != null) {
3204                String signers[] = tool.parseSigners(newGe.signedBy);
3205                for (int i = 0; i < signers.length; i++) {
3206                    PublicKey pubKey = tool.getPublicKeyAlias(signers[i]);
3207                    if (pubKey == null) {
3208                        MessageFormat form = new MessageFormat
3209                            (PolicyTool.getMessage
3210                            ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));
3211                        Object[] source = {signers[i]};
3212                        tool.warnings.addElement(form.format(source));
3213                        tw.displayStatusDialog(td, form.format(source));
3214                    }
3215                }
3216            }
3217
3218            // add the entry
3219            @SuppressWarnings("unchecked")
3220            JList<String> policyList = (JList<String>)tw.getComponent(ToolWindow.MW_POLICY_LIST);
3221            if (edit) {
3222                int listIndex = policyList.getSelectedIndex();
3223                tool.addEntry(newEntry, listIndex);
3224                String newCodeBaseStr = newEntry.headerToString();
3225                if (PolicyTool.collator.compare
3226                        (newCodeBaseStr, policyList.getModel().getElementAt(listIndex)) != 0)
3227                    tool.modified = true;
3228                ((DefaultListModel<String>)policyList.getModel()).set(listIndex, newCodeBaseStr);
3229            } else {
3230                tool.addEntry(newEntry, -1);
3231                ((DefaultListModel<String>)policyList.getModel()).addElement(newEntry.headerToString());
3232                tool.modified = true;
3233            }
3234            td.setVisible(false);
3235            td.dispose();
3236
3237        } catch (Exception eee) {
3238            tw.displayErrorDialog(td, eee);
3239        }
3240    }
3241}
3242
3243/**
3244 * Event handler for ChangeKeyStoreOKButton button
3245 */
3246@SuppressWarnings({"deprecation",
3247                   "removal"}) // PolicyTool
3248class ChangeKeyStoreOKButtonListener implements ActionListener {
3249
3250    private PolicyTool tool;
3251    private ToolWindow tw;
3252    private ToolDialog td;
3253
3254    ChangeKeyStoreOKButtonListener(PolicyTool tool, ToolWindow tw,
3255                ToolDialog td) {
3256        this.tool = tool;
3257        this.tw = tw;
3258        this.td = td;
3259    }
3260
3261    public void actionPerformed(ActionEvent e) {
3262
3263        String URLString = ((JTextField)td.getComponent(
3264                ToolDialog.KSD_NAME_TEXTFIELD)).getText().trim();
3265        String type = ((JTextField)td.getComponent(
3266                ToolDialog.KSD_TYPE_TEXTFIELD)).getText().trim();
3267        String provider = ((JTextField)td.getComponent(
3268                ToolDialog.KSD_PROVIDER_TEXTFIELD)).getText().trim();
3269        String pwdURL = ((JTextField)td.getComponent(
3270                ToolDialog.KSD_PWD_URL_TEXTFIELD)).getText().trim();
3271
3272        try {
3273            tool.openKeyStore
3274                        ((URLString.length() == 0 ? null : URLString),
3275                        (type.length() == 0 ? null : type),
3276                        (provider.length() == 0 ? null : provider),
3277                        (pwdURL.length() == 0 ? null : pwdURL));
3278            tool.modified = true;
3279        } catch (Exception ex) {
3280            MessageFormat form = new MessageFormat(PolicyTool.getMessage
3281                ("Unable.to.open.KeyStore.ex.toString."));
3282            Object[] source = {ex.toString()};
3283            tw.displayErrorDialog(td, form.format(source));
3284            return;
3285        }
3286
3287        td.dispose();
3288    }
3289}
3290
3291/**
3292 * Event handler for AddPrinButton button
3293 */
3294@SuppressWarnings({"deprecation",
3295                   "removal"}) // PolicyTool
3296class AddPrinButtonListener implements ActionListener {
3297
3298    private PolicyTool tool;
3299    private ToolWindow tw;
3300    private ToolDialog td;
3301    private boolean editPolicyEntry;
3302
3303    AddPrinButtonListener(PolicyTool tool, ToolWindow tw,
3304                                ToolDialog td, boolean editPolicyEntry) {
3305        this.tool = tool;
3306        this.tw = tw;
3307        this.td = td;
3308        this.editPolicyEntry = editPolicyEntry;
3309    }
3310
3311    public void actionPerformed(ActionEvent e) {
3312
3313        // display a dialog box for the user to enter principal info
3314        td.displayPrincipalDialog(editPolicyEntry, false);
3315    }
3316}
3317
3318/**
3319 * Event handler for AddPermButton button
3320 */
3321@SuppressWarnings({"deprecation",
3322                   "removal"}) // PolicyTool
3323class AddPermButtonListener implements ActionListener {
3324
3325    private PolicyTool tool;
3326    private ToolWindow tw;
3327    private ToolDialog td;
3328    private boolean editPolicyEntry;
3329
3330    AddPermButtonListener(PolicyTool tool, ToolWindow tw,
3331                                ToolDialog td, boolean editPolicyEntry) {
3332        this.tool = tool;
3333        this.tw = tw;
3334        this.td = td;
3335        this.editPolicyEntry = editPolicyEntry;
3336    }
3337
3338    public void actionPerformed(ActionEvent e) {
3339
3340        // display a dialog box for the user to enter permission info
3341        td.displayPermissionDialog(editPolicyEntry, false);
3342    }
3343}
3344
3345/**
3346 * Event handler for AddPrinOKButton button
3347 */
3348@SuppressWarnings({"deprecation",
3349                   "removal"}) // PolicyTool
3350class NewPolicyPrinOKButtonListener implements ActionListener {
3351
3352    private PolicyTool tool;
3353    private ToolWindow tw;
3354    private ToolDialog listDialog;
3355    private ToolDialog infoDialog;
3356    private boolean edit;
3357
3358    NewPolicyPrinOKButtonListener(PolicyTool tool,
3359                                ToolWindow tw,
3360                                ToolDialog listDialog,
3361                                ToolDialog infoDialog,
3362                                boolean edit) {
3363        this.tool = tool;
3364        this.tw = tw;
3365        this.listDialog = listDialog;
3366        this.infoDialog = infoDialog;
3367        this.edit = edit;
3368    }
3369
3370    public void actionPerformed(ActionEvent e) {
3371
3372        try {
3373            // read in the new principal info from Dialog Box
3374            PolicyParser.PrincipalEntry pppe =
3375                        infoDialog.getPrinFromDialog();
3376            if (pppe != null) {
3377                try {
3378                    tool.verifyPrincipal(pppe.getPrincipalClass(),
3379                                        pppe.getPrincipalName());
3380                } catch (ClassNotFoundException cnfe) {
3381                    MessageFormat form = new MessageFormat
3382                                (PolicyTool.getMessage
3383                                ("Warning.Class.not.found.class"));
3384                    Object[] source = {pppe.getPrincipalClass()};
3385                    tool.warnings.addElement(form.format(source));
3386                    tw.displayStatusDialog(infoDialog, form.format(source));
3387                }
3388
3389                // add the principal to the GUI principal list
3390                TaggedList prinList =
3391                    (TaggedList)listDialog.getComponent(ToolDialog.PE_PRIN_LIST);
3392
3393                String prinString = ToolDialog.PrincipalEntryToUserFriendlyString(pppe);
3394                if (edit) {
3395                    // if editing, replace the original principal
3396                    int index = prinList.getSelectedIndex();
3397                    prinList.replaceTaggedItem(prinString, pppe, index);
3398                } else {
3399                    // if adding, just add it to the end
3400                    prinList.addTaggedItem(prinString, pppe);
3401                }
3402            }
3403            infoDialog.dispose();
3404        } catch (Exception ee) {
3405            tw.displayErrorDialog(infoDialog, ee);
3406        }
3407    }
3408}
3409
3410/**
3411 * Event handler for AddPermOKButton button
3412 */
3413@SuppressWarnings({"deprecation",
3414                   "removal"}) // PolicyTool
3415class NewPolicyPermOKButtonListener implements ActionListener {
3416
3417    private PolicyTool tool;
3418    private ToolWindow tw;
3419    private ToolDialog listDialog;
3420    private ToolDialog infoDialog;
3421    private boolean edit;
3422
3423    NewPolicyPermOKButtonListener(PolicyTool tool,
3424                                ToolWindow tw,
3425                                ToolDialog listDialog,
3426                                ToolDialog infoDialog,
3427                                boolean edit) {
3428        this.tool = tool;
3429        this.tw = tw;
3430        this.listDialog = listDialog;
3431        this.infoDialog = infoDialog;
3432        this.edit = edit;
3433    }
3434
3435    public void actionPerformed(ActionEvent e) {
3436
3437        try {
3438            // read in the new permission info from Dialog Box
3439            PolicyParser.PermissionEntry pppe =
3440                        infoDialog.getPermFromDialog();
3441
3442            try {
3443                tool.verifyPermission(pppe.permission, pppe.name, pppe.action);
3444            } catch (ClassNotFoundException cnfe) {
3445                MessageFormat form = new MessageFormat(PolicyTool.getMessage
3446                                ("Warning.Class.not.found.class"));
3447                Object[] source = {pppe.permission};
3448                tool.warnings.addElement(form.format(source));
3449                tw.displayStatusDialog(infoDialog, form.format(source));
3450            }
3451
3452            // add the permission to the GUI permission list
3453            TaggedList permList =
3454                (TaggedList)listDialog.getComponent(ToolDialog.PE_PERM_LIST);
3455
3456            String permString = ToolDialog.PermissionEntryToUserFriendlyString(pppe);
3457            if (edit) {
3458                // if editing, replace the original permission
3459                int which = permList.getSelectedIndex();
3460                permList.replaceTaggedItem(permString, pppe, which);
3461            } else {
3462                // if adding, just add it to the end
3463                permList.addTaggedItem(permString, pppe);
3464            }
3465            infoDialog.dispose();
3466
3467        } catch (InvocationTargetException ite) {
3468            tw.displayErrorDialog(infoDialog, ite.getTargetException());
3469        } catch (Exception ee) {
3470            tw.displayErrorDialog(infoDialog, ee);
3471        }
3472    }
3473}
3474
3475/**
3476 * Event handler for RemovePrinButton button
3477 */
3478@SuppressWarnings({"deprecation",
3479                   "removal"}) // PolicyTool
3480class RemovePrinButtonListener implements ActionListener {
3481
3482    private PolicyTool tool;
3483    private ToolWindow tw;
3484    private ToolDialog td;
3485    private boolean edit;
3486
3487    RemovePrinButtonListener(PolicyTool tool, ToolWindow tw,
3488                                ToolDialog td, boolean edit) {
3489        this.tool = tool;
3490        this.tw = tw;
3491        this.td = td;
3492        this.edit = edit;
3493    }
3494
3495    public void actionPerformed(ActionEvent e) {
3496
3497        // get the Principal selected from the Principal List
3498        TaggedList prinList = (TaggedList)td.getComponent(
3499                ToolDialog.PE_PRIN_LIST);
3500        int prinIndex = prinList.getSelectedIndex();
3501
3502        if (prinIndex < 0) {
3503            tw.displayErrorDialog(td, new Exception
3504                (PolicyTool.getMessage("No.principal.selected")));
3505            return;
3506        }
3507        // remove the principal from the display
3508        prinList.removeTaggedItem(prinIndex);
3509    }
3510}
3511
3512/**
3513 * Event handler for RemovePermButton button
3514 */
3515@SuppressWarnings({"deprecation",
3516                   "removal"}) // PolicyTool
3517class RemovePermButtonListener implements ActionListener {
3518
3519    private PolicyTool tool;
3520    private ToolWindow tw;
3521    private ToolDialog td;
3522    private boolean edit;
3523
3524    RemovePermButtonListener(PolicyTool tool, ToolWindow tw,
3525                                ToolDialog td, boolean edit) {
3526        this.tool = tool;
3527        this.tw = tw;
3528        this.td = td;
3529        this.edit = edit;
3530    }
3531
3532    public void actionPerformed(ActionEvent e) {
3533
3534        // get the Permission selected from the Permission List
3535        TaggedList permList = (TaggedList)td.getComponent(
3536                ToolDialog.PE_PERM_LIST);
3537        int permIndex = permList.getSelectedIndex();
3538
3539        if (permIndex < 0) {
3540            tw.displayErrorDialog(td, new Exception
3541                (PolicyTool.getMessage("No.permission.selected")));
3542            return;
3543        }
3544        // remove the permission from the display
3545        permList.removeTaggedItem(permIndex);
3546
3547    }
3548}
3549
3550/**
3551 * Event handler for Edit Principal button
3552 *
3553 * We need the editPolicyEntry boolean to tell us if the user is
3554 * adding a new PolicyEntry at this time, or editing an existing entry.
3555 * If the user is adding a new PolicyEntry, we ONLY update the
3556 * GUI listing.  If the user is editing an existing PolicyEntry, we
3557 * update both the GUI listing and the actual PolicyEntry.
3558 */
3559@SuppressWarnings({"deprecation",
3560                   "removal"}) // PolicyTool
3561class EditPrinButtonListener extends MouseAdapter implements ActionListener {
3562
3563    private PolicyTool tool;
3564    private ToolWindow tw;
3565    private ToolDialog td;
3566    private boolean editPolicyEntry;
3567
3568    EditPrinButtonListener(PolicyTool tool, ToolWindow tw,
3569                                ToolDialog td, boolean editPolicyEntry) {
3570        this.tool = tool;
3571        this.tw = tw;
3572        this.td = td;
3573        this.editPolicyEntry = editPolicyEntry;
3574    }
3575
3576    public void actionPerformed(ActionEvent e) {
3577
3578        // get the Principal selected from the Principal List
3579        TaggedList list = (TaggedList)td.getComponent(
3580                ToolDialog.PE_PRIN_LIST);
3581        int prinIndex = list.getSelectedIndex();
3582
3583        if (prinIndex < 0) {
3584            tw.displayErrorDialog(td, new Exception
3585                (PolicyTool.getMessage("No.principal.selected")));
3586            return;
3587        }
3588        td.displayPrincipalDialog(editPolicyEntry, true);
3589    }
3590
3591    public void mouseClicked(MouseEvent evt) {
3592        if (evt.getClickCount() == 2) {
3593            actionPerformed(null);
3594        }
3595    }
3596}
3597
3598/**
3599 * Event handler for Edit Permission button
3600 *
3601 * We need the editPolicyEntry boolean to tell us if the user is
3602 * adding a new PolicyEntry at this time, or editing an existing entry.
3603 * If the user is adding a new PolicyEntry, we ONLY update the
3604 * GUI listing.  If the user is editing an existing PolicyEntry, we
3605 * update both the GUI listing and the actual PolicyEntry.
3606 */
3607@SuppressWarnings({"deprecation",
3608                   "removal"}) // PolicyTool
3609class EditPermButtonListener extends MouseAdapter implements ActionListener {
3610
3611    private PolicyTool tool;
3612    private ToolWindow tw;
3613    private ToolDialog td;
3614    private boolean editPolicyEntry;
3615
3616    EditPermButtonListener(PolicyTool tool, ToolWindow tw,
3617                                ToolDialog td, boolean editPolicyEntry) {
3618        this.tool = tool;
3619        this.tw = tw;
3620        this.td = td;
3621        this.editPolicyEntry = editPolicyEntry;
3622    }
3623
3624    public void actionPerformed(ActionEvent e) {
3625
3626        // get the Permission selected from the Permission List
3627        @SuppressWarnings("unchecked")
3628        JList<String> list = (JList<String>)td.getComponent(ToolDialog.PE_PERM_LIST);
3629        int permIndex = list.getSelectedIndex();
3630
3631        if (permIndex < 0) {
3632            tw.displayErrorDialog(td, new Exception
3633                (PolicyTool.getMessage("No.permission.selected")));
3634            return;
3635        }
3636        td.displayPermissionDialog(editPolicyEntry, true);
3637    }
3638
3639    public void mouseClicked(MouseEvent evt) {
3640        if (evt.getClickCount() == 2) {
3641            actionPerformed(null);
3642        }
3643    }
3644}
3645
3646/**
3647 * Event handler for Principal Popup Menu
3648 */
3649@SuppressWarnings({"deprecation",
3650                   "removal"}) // PolicyTool
3651class PrincipalTypeMenuListener implements ItemListener {
3652
3653    private ToolDialog td;
3654
3655    PrincipalTypeMenuListener(ToolDialog td) {
3656        this.td = td;
3657    }
3658
3659    public void itemStateChanged(ItemEvent e) {
3660        if (e.getStateChange() == ItemEvent.DESELECTED) {
3661            // We're only interested in SELECTED events
3662            return;
3663        }
3664
3665        @SuppressWarnings("unchecked")
3666        JComboBox<String> prin = (JComboBox<String>)td.getComponent(ToolDialog.PRD_PRIN_CHOICE);
3667        JTextField prinField = (JTextField)td.getComponent(
3668                ToolDialog.PRD_PRIN_TEXTFIELD);
3669        JTextField nameField = (JTextField)td.getComponent(
3670                ToolDialog.PRD_NAME_TEXTFIELD);
3671
3672        prin.getAccessibleContext().setAccessibleName(
3673            PolicyTool.splitToWords((String)e.getItem()));
3674        if (((String)e.getItem()).equals(ToolDialog.PRIN_TYPE)) {
3675            // ignore if they choose "Principal Type:" item
3676            if (prinField.getText() != null &&
3677                prinField.getText().length() > 0) {
3678                Prin inputPrin = ToolDialog.getPrin(prinField.getText(), true);
3679                prin.setSelectedItem(inputPrin.getSimpleName());
3680            }
3681            return;
3682        }
3683
3684        // if you change the principal, clear the name
3685        if (prinField.getText().indexOf((String)e.getItem()) == -1) {
3686            nameField.setText("");
3687        }
3688
3689        // set the text in the textfield and also modify the
3690        // pull-down choice menus to reflect the correct possible
3691        // set of names and actions
3692        Prin inputPrin = ToolDialog.getPrin((String)e.getItem(), false);
3693        if (inputPrin != null) {
3694            prinField.setText(inputPrin.getName());
3695        }
3696    }
3697}
3698
3699/**
3700 * Event handler for Permission Popup Menu
3701 */
3702@SuppressWarnings({"deprecation",
3703                   "removal"}) // PolicyTool
3704class PermissionMenuListener implements ItemListener {
3705
3706    private ToolDialog td;
3707
3708    PermissionMenuListener(ToolDialog td) {
3709        this.td = td;
3710    }
3711
3712    public void itemStateChanged(ItemEvent e) {
3713        if (e.getStateChange() == ItemEvent.DESELECTED) {
3714            // We're only interested in SELECTED events
3715            return;
3716        }
3717
3718        @SuppressWarnings("unchecked")
3719        JComboBox<String> perms = (JComboBox<String>)td.getComponent(
3720                ToolDialog.PD_PERM_CHOICE);
3721        @SuppressWarnings("unchecked")
3722        JComboBox<String> names = (JComboBox<String>)td.getComponent(
3723                ToolDialog.PD_NAME_CHOICE);
3724        @SuppressWarnings("unchecked")
3725        JComboBox<String> actions = (JComboBox<String>)td.getComponent(
3726                ToolDialog.PD_ACTIONS_CHOICE);
3727        JTextField nameField = (JTextField)td.getComponent(
3728                ToolDialog.PD_NAME_TEXTFIELD);
3729        JTextField actionsField = (JTextField)td.getComponent(
3730                ToolDialog.PD_ACTIONS_TEXTFIELD);
3731        JTextField permField = (JTextField)td.getComponent(
3732                ToolDialog.PD_PERM_TEXTFIELD);
3733        JTextField signedbyField = (JTextField)td.getComponent(
3734                ToolDialog.PD_SIGNEDBY_TEXTFIELD);
3735
3736        perms.getAccessibleContext().setAccessibleName(
3737            PolicyTool.splitToWords((String)e.getItem()));
3738
3739        // ignore if they choose the 'Permission:' item
3740        if (PolicyTool.collator.compare((String)e.getItem(),
3741                                      ToolDialog.PERM) == 0) {
3742            if (permField.getText() != null &&
3743                permField.getText().length() > 0) {
3744
3745                Perm inputPerm = ToolDialog.getPerm(permField.getText(), true);
3746                if (inputPerm != null) {
3747                    perms.setSelectedItem(inputPerm.getSimpleName());
3748                }
3749            }
3750            return;
3751        }
3752
3753        // if you change the permission, clear the name, actions, and signedBy
3754        if (permField.getText().indexOf((String)e.getItem()) == -1) {
3755            nameField.setText("");
3756            actionsField.setText("");
3757            signedbyField.setText("");
3758        }
3759
3760        // set the text in the textfield and also modify the
3761        // pull-down choice menus to reflect the correct possible
3762        // set of names and actions
3763
3764        Perm inputPerm = ToolDialog.getPerm((String)e.getItem(), false);
3765        if (inputPerm == null) {
3766            permField.setText("");
3767        } else {
3768            permField.setText(inputPerm.getName());
3769        }
3770        td.setPermissionNames(inputPerm, names, nameField);
3771        td.setPermissionActions(inputPerm, actions, actionsField);
3772    }
3773}
3774
3775/**
3776 * Event handler for Permission Name Popup Menu
3777 */
3778@SuppressWarnings({"deprecation",
3779                   "removal"}) // PolicyTool
3780class PermissionNameMenuListener implements ItemListener {
3781
3782    private ToolDialog td;
3783
3784    PermissionNameMenuListener(ToolDialog td) {
3785        this.td = td;
3786    }
3787
3788    public void itemStateChanged(ItemEvent e) {
3789        if (e.getStateChange() == ItemEvent.DESELECTED) {
3790            // We're only interested in SELECTED events
3791            return;
3792        }
3793
3794        @SuppressWarnings("unchecked")
3795        JComboBox<String> names = (JComboBox<String>)td.getComponent(ToolDialog.PD_NAME_CHOICE);
3796        names.getAccessibleContext().setAccessibleName(
3797            PolicyTool.splitToWords((String)e.getItem()));
3798
3799        if (((String)e.getItem()).indexOf(ToolDialog.PERM_NAME) != -1)
3800            return;
3801
3802        JTextField tf = (JTextField)td.getComponent(ToolDialog.PD_NAME_TEXTFIELD);
3803        tf.setText((String)e.getItem());
3804    }
3805}
3806
3807/**
3808 * Event handler for Permission Actions Popup Menu
3809 */
3810class PermissionActionsMenuListener implements ItemListener {
3811
3812    private ToolDialog td;
3813
3814    PermissionActionsMenuListener(ToolDialog td) {
3815        this.td = td;
3816    }
3817
3818    public void itemStateChanged(ItemEvent e) {
3819        if (e.getStateChange() == ItemEvent.DESELECTED) {
3820            // We're only interested in SELECTED events
3821            return;
3822        }
3823
3824        @SuppressWarnings("unchecked")
3825        JComboBox<String> actions = (JComboBox<String>)td.getComponent(
3826                ToolDialog.PD_ACTIONS_CHOICE);
3827        actions.getAccessibleContext().setAccessibleName((String)e.getItem());
3828
3829        if (((String)e.getItem()).indexOf(ToolDialog.PERM_ACTIONS) != -1)
3830            return;
3831
3832        JTextField tf = (JTextField)td.getComponent(
3833                ToolDialog.PD_ACTIONS_TEXTFIELD);
3834        if (tf.getText() == null || tf.getText().equals("")) {
3835            tf.setText((String)e.getItem());
3836        } else {
3837            if (tf.getText().indexOf((String)e.getItem()) == -1)
3838                tf.setText(tf.getText() + ", " + (String)e.getItem());
3839        }
3840    }
3841}
3842
3843/**
3844 * Event handler for all the children dialogs/windows
3845 */
3846class ChildWindowListener implements WindowListener {
3847
3848    private ToolDialog td;
3849
3850    ChildWindowListener(ToolDialog td) {
3851        this.td = td;
3852    }
3853
3854    public void windowOpened(WindowEvent we) {
3855    }
3856
3857    public void windowClosing(WindowEvent we) {
3858        // same as pressing the "cancel" button
3859        td.setVisible(false);
3860        td.dispose();
3861    }
3862
3863    public void windowClosed(WindowEvent we) {
3864    }
3865
3866    public void windowIconified(WindowEvent we) {
3867    }
3868
3869    public void windowDeiconified(WindowEvent we) {
3870    }
3871
3872    public void windowActivated(WindowEvent we) {
3873    }
3874
3875    public void windowDeactivated(WindowEvent we) {
3876    }
3877}
3878
3879/**
3880 * Event handler for CancelButton button
3881 */
3882class CancelButtonListener implements ActionListener {
3883
3884    private ToolDialog td;
3885
3886    CancelButtonListener(ToolDialog td) {
3887        this.td = td;
3888    }
3889
3890    public void actionPerformed(ActionEvent e) {
3891        td.setVisible(false);
3892        td.dispose();
3893    }
3894}
3895
3896/**
3897 * Event handler for ErrorOKButton button
3898 */
3899class ErrorOKButtonListener implements ActionListener {
3900
3901    private ToolDialog ed;
3902
3903    ErrorOKButtonListener(ToolDialog ed) {
3904        this.ed = ed;
3905    }
3906
3907    public void actionPerformed(ActionEvent e) {
3908        ed.setVisible(false);
3909        ed.dispose();
3910    }
3911}
3912
3913/**
3914 * Event handler for StatusOKButton button
3915 */
3916class StatusOKButtonListener implements ActionListener {
3917
3918    private ToolDialog sd;
3919
3920    StatusOKButtonListener(ToolDialog sd) {
3921        this.sd = sd;
3922    }
3923
3924    public void actionPerformed(ActionEvent e) {
3925        sd.setVisible(false);
3926        sd.dispose();
3927    }
3928}
3929
3930/**
3931 * Event handler for UserSaveYes button
3932 */
3933@SuppressWarnings({"deprecation",
3934                   "removal"}) // PolicyTool
3935class UserSaveYesButtonListener implements ActionListener {
3936
3937    private ToolDialog us;
3938    private PolicyTool tool;
3939    private ToolWindow tw;
3940    private int select;
3941
3942    UserSaveYesButtonListener(ToolDialog us, PolicyTool tool,
3943                        ToolWindow tw, int select) {
3944        this.us = us;
3945        this.tool = tool;
3946        this.tw = tw;
3947        this.select = select;
3948    }
3949
3950    public void actionPerformed(ActionEvent e) {
3951
3952        // first get rid of the window
3953        us.setVisible(false);
3954        us.dispose();
3955
3956        try {
3957            String filename = ((JTextField)tw.getComponent(
3958                    ToolWindow.MW_FILENAME_TEXTFIELD)).getText();
3959            if (filename == null || filename.equals("")) {
3960                us.displaySaveAsDialog(select);
3961
3962                // the above dialog will continue with the originally
3963                // requested command if necessary
3964            } else {
3965                // save the policy entries to a file
3966                tool.savePolicy(filename);
3967
3968                // display status
3969                MessageFormat form = new MessageFormat
3970                        (PolicyTool.getMessage
3971                        ("Policy.successfully.written.to.filename"));
3972                Object[] source = {filename};
3973                tw.displayStatusDialog(null, form.format(source));
3974
3975                // now continue with the originally requested command
3976                // (QUIT, NEW, or OPEN)
3977                us.userSaveContinue(tool, tw, us, select);
3978            }
3979        } catch (Exception ee) {
3980            // error -- just report it and bail
3981            tw.displayErrorDialog(null, ee);
3982        }
3983    }
3984}
3985
3986/**
3987 * Event handler for UserSaveNoButton
3988 */
3989@SuppressWarnings({"deprecation",
3990                   "removal"}) // PolicyTool
3991class UserSaveNoButtonListener implements ActionListener {
3992
3993    private PolicyTool tool;
3994    private ToolWindow tw;
3995    private ToolDialog us;
3996    private int select;
3997
3998    UserSaveNoButtonListener(ToolDialog us, PolicyTool tool,
3999                        ToolWindow tw, int select) {
4000        this.us = us;
4001        this.tool = tool;
4002        this.tw = tw;
4003        this.select = select;
4004    }
4005
4006    public void actionPerformed(ActionEvent e) {
4007        us.setVisible(false);
4008        us.dispose();
4009
4010        // now continue with the originally requested command
4011        // (QUIT, NEW, or OPEN)
4012        us.userSaveContinue(tool, tw, us, select);
4013    }
4014}
4015
4016/**
4017 * Event handler for UserSaveCancelButton
4018 */
4019class UserSaveCancelButtonListener implements ActionListener {
4020
4021    private ToolDialog us;
4022
4023    UserSaveCancelButtonListener(ToolDialog us) {
4024        this.us = us;
4025    }
4026
4027    public void actionPerformed(ActionEvent e) {
4028        us.setVisible(false);
4029        us.dispose();
4030
4031        // do NOT continue with the originally requested command
4032        // (QUIT, NEW, or OPEN)
4033    }
4034}
4035
4036/**
4037 * Event handler for ConfirmRemovePolicyEntryOKButtonListener
4038 */
4039@SuppressWarnings({"deprecation",
4040                   "removal"}) // PolicyTool
4041class ConfirmRemovePolicyEntryOKButtonListener implements ActionListener {
4042
4043    private PolicyTool tool;
4044    private ToolWindow tw;
4045    private ToolDialog us;
4046
4047    ConfirmRemovePolicyEntryOKButtonListener(PolicyTool tool,
4048                                ToolWindow tw, ToolDialog us) {
4049        this.tool = tool;
4050        this.tw = tw;
4051        this.us = us;
4052    }
4053
4054    public void actionPerformed(ActionEvent e) {
4055        // remove the entry
4056        @SuppressWarnings("unchecked")
4057        JList<String> list = (JList<String>)tw.getComponent(ToolWindow.MW_POLICY_LIST);
4058        int index = list.getSelectedIndex();
4059        PolicyEntry entries[] = tool.getEntry();
4060        tool.removeEntry(entries[index]);
4061
4062        // redraw the window listing
4063        DefaultListModel<String> listModel = new DefaultListModel<>();
4064        list = new JList<>(listModel);
4065        list.setVisibleRowCount(15);
4066        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
4067        list.addMouseListener(new PolicyListListener(tool, tw));
4068        entries = tool.getEntry();
4069        if (entries != null) {
4070                for (int i = 0; i < entries.length; i++) {
4071                    listModel.addElement(entries[i].headerToString());
4072                }
4073        }
4074        tw.replacePolicyList(list);
4075        us.setVisible(false);
4076        us.dispose();
4077    }
4078}
4079
4080/**
4081 * Just a special name, so that the codes dealing with this exception knows
4082 * it's special, and does not pop out a warning box.
4083 */
4084class NoDisplayException extends RuntimeException {
4085    private static final long serialVersionUID = -4611761427108719794L;
4086}
4087
4088/**
4089 * This is a java.awt.List that bind an Object to each String it holds.
4090 */
4091class TaggedList extends JList<String> {
4092    private static final long serialVersionUID = -5676238110427785853L;
4093
4094    private java.util.List<Object> data = new LinkedList<>();
4095    public TaggedList(int i, boolean b) {
4096        super(new DefaultListModel<>());
4097        setVisibleRowCount(i);
4098        setSelectionMode(b ? ListSelectionModel.MULTIPLE_INTERVAL_SELECTION : ListSelectionModel.SINGLE_SELECTION);
4099    }
4100
4101    public Object getObject(int index) {
4102        return data.get(index);
4103    }
4104
4105    public void addTaggedItem(String string, Object object) {
4106        ((DefaultListModel<String>)getModel()).addElement(string);
4107        data.add(object);
4108    }
4109
4110    public void replaceTaggedItem(String string, Object object, int index) {
4111        ((DefaultListModel<String>)getModel()).set(index, string);
4112        data.set(index, object);
4113    }
4114
4115    public void removeTaggedItem(int index) {
4116        ((DefaultListModel<String>)getModel()).remove(index);
4117        data.remove(index);
4118    }
4119}
4120
4121/**
4122 * Convenience Principal Classes
4123 */
4124
4125class Prin {
4126    final Class<? extends Principal> CLASS;
4127
4128    Prin(Class<? extends Principal> clazz) {
4129        this.CLASS = clazz;
4130    }
4131
4132    String getName() {
4133        return CLASS.getName();
4134    }
4135
4136    String getSimpleName() {
4137        return CLASS.getSimpleName();
4138    }
4139}
4140
4141class KrbPrin extends Prin {
4142    KrbPrin() {
4143        super(javax.security.auth.kerberos.KerberosPrincipal.class);
4144    }
4145}
4146
4147class X500Prin extends Prin {
4148    X500Prin() {
4149        super(javax.security.auth.x500.X500Principal.class);
4150    }
4151}
4152
4153/**
4154 * Convenience Permission Classes
4155 */
4156
4157class Perm {
4158    final Class<? extends Permission> CLASS;
4159    final String[] TARGETS;
4160    final String[] ACTIONS;
4161
4162    Perm(Class<? extends Permission> clazz,
4163                String[] targets, String[] actions) {
4164
4165        this.CLASS = clazz;
4166        this.TARGETS = targets;
4167        this.ACTIONS = actions;
4168    }
4169
4170    String getName() {
4171        return CLASS.getName();
4172    }
4173
4174    String getSimpleName() {
4175        return CLASS.getSimpleName();
4176    }
4177}
4178
4179class AllPerm extends Perm {
4180    AllPerm() {
4181        super(java.security.AllPermission.class, null, null);
4182    }
4183}
4184
4185class AudioPerm extends Perm {
4186    AudioPerm() {
4187        super(javax.sound.sampled.AudioPermission.class,
4188            new String[]    {
4189                "play",
4190                "record"
4191                },
4192            null);
4193    }
4194}
4195
4196@SuppressWarnings({"deprecation",
4197                   "removal"}) // PolicyTool
4198class AuthPerm extends Perm {
4199    AuthPerm() {
4200        super(javax.security.auth.AuthPermission.class,
4201            new String[]    {
4202                "doAs",
4203                "doAsPrivileged",
4204                "getSubject",
4205                "getSubjectFromDomainCombiner",
4206                "setReadOnly",
4207                "modifyPrincipals",
4208                "modifyPublicCredentials",
4209                "modifyPrivateCredentials",
4210                "refreshCredential",
4211                "destroyCredential",
4212                "createLoginContext.<" + PolicyTool.getMessage("name") + ">",
4213                "getLoginConfiguration",
4214                "setLoginConfiguration",
4215                "createLoginConfiguration.<" +
4216                        PolicyTool.getMessage("configuration.type") + ">",
4217                "refreshLoginConfiguration"
4218                },
4219            null);
4220    }
4221}
4222
4223class AWTPerm extends Perm {
4224    AWTPerm() {
4225        super(java.awt.AWTPermission.class,
4226            new String[]    {
4227                "accessClipboard",
4228                "accessEventQueue",
4229                "accessSystemTray",
4230                "createRobot",
4231                "fullScreenExclusive",
4232                "listenToAllAWTEvents",
4233                "readDisplayPixels",
4234                "replaceKeyboardFocusManager",
4235                "setAppletStub",
4236                "setWindowAlwaysOnTop",
4237                "showWindowWithoutWarningBanner",
4238                "toolkitModality",
4239                "watchMousePointer"
4240                },
4241            null);
4242    }
4243}
4244
4245class DelegationPerm extends Perm {
4246    DelegationPerm() {
4247        super(javax.security.auth.kerberos.DelegationPermission.class,
4248            new String[]    {
4249                // allow user input
4250                },
4251            null);
4252    }
4253}
4254
4255class FilePerm extends Perm {
4256    FilePerm() {
4257        super(java.io.FilePermission.class,
4258            new String[]    {
4259                "<<ALL FILES>>"
4260                },
4261            new String[]    {
4262                "read",
4263                "write",
4264                "delete",
4265                "execute"
4266                });
4267    }
4268}
4269
4270@SuppressWarnings({"deprecation",
4271                   "removal"}) // PolicyTool
4272class URLPerm extends Perm {
4273    URLPerm() {
4274        super(java.net.URLPermission.class,
4275            new String[]    {
4276                "<"+ PolicyTool.getMessage("url") + ">",
4277            },
4278            new String[]    {
4279                "<" + PolicyTool.getMessage("method.list") + ">:<"
4280                    + PolicyTool.getMessage("request.headers.list") + ">",
4281            });
4282    }
4283}
4284
4285class InqSecContextPerm extends Perm {
4286    InqSecContextPerm() {
4287        super(com.sun.security.jgss.InquireSecContextPermission.class,
4288            new String[]    {
4289                "KRB5_GET_SESSION_KEY",
4290                "KRB5_GET_TKT_FLAGS",
4291                "KRB5_GET_AUTHZ_DATA",
4292                "KRB5_GET_AUTHTIME"
4293                },
4294            null);
4295    }
4296}
4297
4298class LogPerm extends Perm {
4299    LogPerm() {
4300        super(java.util.logging.LoggingPermission.class,
4301            new String[]    {
4302                "control"
4303                },
4304            null);
4305    }
4306}
4307
4308class MgmtPerm extends Perm {
4309    MgmtPerm() {
4310        super(java.lang.management.ManagementPermission.class,
4311            new String[]    {
4312                "control",
4313                "monitor"
4314                },
4315            null);
4316    }
4317}
4318
4319class MBeanPerm extends Perm {
4320    MBeanPerm() {
4321        super(javax.management.MBeanPermission.class,
4322            new String[]    {
4323                // allow user input
4324                },
4325            new String[]    {
4326                "addNotificationListener",
4327                "getAttribute",
4328                "getClassLoader",
4329                "getClassLoaderFor",
4330                "getClassLoaderRepository",
4331                "getDomains",
4332                "getMBeanInfo",
4333                "getObjectInstance",
4334                "instantiate",
4335                "invoke",
4336                "isInstanceOf",
4337                "queryMBeans",
4338                "queryNames",
4339                "registerMBean",
4340                "removeNotificationListener",
4341                "setAttribute",
4342                "unregisterMBean"
4343                });
4344    }
4345}
4346
4347class MBeanSvrPerm extends Perm {
4348    MBeanSvrPerm() {
4349        super(javax.management.MBeanServerPermission.class,
4350            new String[]    {
4351                "createMBeanServer",
4352                "findMBeanServer",
4353                "newMBeanServer",
4354                "releaseMBeanServer"
4355                },
4356            null);
4357    }
4358}
4359
4360class MBeanTrustPerm extends Perm {
4361    MBeanTrustPerm() {
4362        super(javax.management.MBeanTrustPermission.class,
4363            new String[]    {
4364                "register"
4365                },
4366            null);
4367    }
4368}
4369
4370class NetPerm extends Perm {
4371    NetPerm() {
4372        super(java.net.NetPermission.class,
4373            new String[]    {
4374                "allowHttpTrace",
4375                "setDefaultAuthenticator",
4376                "requestPasswordAuthentication",
4377                "specifyStreamHandler",
4378                "getNetworkInformation",
4379                "setProxySelector",
4380                "getProxySelector",
4381                "setCookieHandler",
4382                "getCookieHandler",
4383                "setResponseCache",
4384                "getResponseCache"
4385                },
4386            null);
4387    }
4388}
4389
4390class NetworkPerm extends Perm {
4391    NetworkPerm() {
4392        super(jdk.net.NetworkPermission.class,
4393            new String[]    {
4394                "setOption.SO_FLOW_SLA",
4395                "getOption.SO_FLOW_SLA"
4396                },
4397            null);
4398    }
4399}
4400
4401class PrivCredPerm extends Perm {
4402    PrivCredPerm() {
4403        super(javax.security.auth.PrivateCredentialPermission.class,
4404            new String[]    {
4405                // allow user input
4406                },
4407            new String[]    {
4408                "read"
4409                });
4410    }
4411}
4412
4413class PropPerm extends Perm {
4414    PropPerm() {
4415        super(java.util.PropertyPermission.class,
4416            new String[]    {
4417                // allow user input
4418                },
4419            new String[]    {
4420                "read",
4421                "write"
4422                });
4423    }
4424}
4425
4426class ReflectPerm extends Perm {
4427    ReflectPerm() {
4428        super(java.lang.reflect.ReflectPermission.class,
4429            new String[]    {
4430                "suppressAccessChecks"
4431                },
4432            null);
4433    }
4434}
4435
4436@SuppressWarnings({"deprecation",
4437                   "removal"}) // PolicyTool
4438class RuntimePerm extends Perm {
4439    RuntimePerm() {
4440        super(java.lang.RuntimePermission.class,
4441            new String[]    {
4442                "createClassLoader",
4443                "getClassLoader",
4444                "setContextClassLoader",
4445                "enableContextClassLoaderOverride",
4446                "setSecurityManager",
4447                "createSecurityManager",
4448                "getenv.<" +
4449                    PolicyTool.getMessage("environment.variable.name") + ">",
4450                "exitVM",
4451                "shutdownHooks",
4452                "setFactory",
4453                "setIO",
4454                "modifyThread",
4455                "stopThread",
4456                "modifyThreadGroup",
4457                "getProtectionDomain",
4458                "readFileDescriptor",
4459                "writeFileDescriptor",
4460                "loadLibrary.<" +
4461                    PolicyTool.getMessage("library.name") + ">",
4462                "accessClassInPackage.<" +
4463                    PolicyTool.getMessage("package.name")+">",
4464                "defineClassInPackage.<" +
4465                    PolicyTool.getMessage("package.name")+">",
4466                "accessDeclaredMembers",
4467                "queuePrintJob",
4468                "getStackTrace",
4469                "setDefaultUncaughtExceptionHandler",
4470                "preferences",
4471                "usePolicy",
4472                // "inheritedChannel"
4473                },
4474            null);
4475    }
4476}
4477
4478@SuppressWarnings({"deprecation",
4479                   "removal"}) // PolicyTool
4480class SecurityPerm extends Perm {
4481    SecurityPerm() {
4482        super(java.security.SecurityPermission.class,
4483            new String[]    {
4484                "createAccessControlContext",
4485                "getDomainCombiner",
4486                "getPolicy",
4487                "setPolicy",
4488                "createPolicy.<" +
4489                    PolicyTool.getMessage("policy.type") + ">",
4490                "getProperty.<" +
4491                    PolicyTool.getMessage("property.name") + ">",
4492                "setProperty.<" +
4493                    PolicyTool.getMessage("property.name") + ">",
4494                "insertProvider.<" +
4495                    PolicyTool.getMessage("provider.name") + ">",
4496                "removeProvider.<" +
4497                    PolicyTool.getMessage("provider.name") + ">",
4498                //"setSystemScope",
4499                //"setIdentityPublicKey",
4500                //"setIdentityInfo",
4501                //"addIdentityCertificate",
4502                //"removeIdentityCertificate",
4503                //"printIdentity",
4504                "clearProviderProperties.<" +
4505                    PolicyTool.getMessage("provider.name") + ">",
4506                "putProviderProperty.<" +
4507                    PolicyTool.getMessage("provider.name") + ">",
4508                "removeProviderProperty.<" +
4509                    PolicyTool.getMessage("provider.name") + ">",
4510                //"getSignerPrivateKey",
4511                //"setSignerKeyPair"
4512                },
4513            null);
4514    }
4515}
4516
4517class SerialPerm extends Perm {
4518    SerialPerm() {
4519        super(java.io.SerializablePermission.class,
4520            new String[]    {
4521                "enableSubclassImplementation",
4522                "enableSubstitution"
4523                },
4524            null);
4525    }
4526}
4527
4528class ServicePerm extends Perm {
4529    ServicePerm() {
4530        super(javax.security.auth.kerberos.ServicePermission.class,
4531            new String[]    {
4532                // allow user input
4533                },
4534            new String[]    {
4535                "initiate",
4536                "accept"
4537                });
4538    }
4539}
4540
4541class SocketPerm extends Perm {
4542    SocketPerm() {
4543        super(java.net.SocketPermission.class,
4544            new String[]    {
4545                // allow user input
4546                },
4547            new String[]    {
4548                "accept",
4549                "connect",
4550                "listen",
4551                "resolve"
4552                });
4553    }
4554}
4555
4556class SQLPerm extends Perm {
4557    SQLPerm() {
4558        super(java.sql.SQLPermission.class,
4559            new String[]    {
4560                "setLog",
4561                "callAbort",
4562                "setSyncFactory",
4563                "setNetworkTimeout",
4564                },
4565            null);
4566    }
4567}
4568
4569class SSLPerm extends Perm {
4570    SSLPerm() {
4571        super(javax.net.ssl.SSLPermission.class,
4572            new String[]    {
4573                "setHostnameVerifier",
4574                "getSSLSessionContext"
4575                },
4576            null);
4577    }
4578}
4579
4580class SubjDelegPerm extends Perm {
4581    SubjDelegPerm() {
4582        super(javax.management.remote.SubjectDelegationPermission.class,
4583            new String[]    {
4584                // allow user input
4585                },
4586            null);
4587    }
4588}
4589