PolicyTool.java 148.5 KB
Newer Older
D
duke 已提交
1
/*
L
Merge  
lana 已提交
2
 * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25
 */

26
package sun.security.tools.policytool;
D
duke 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

import java.io.*;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Vector;
import java.util.Enumeration;
import java.net.URL;
import java.net.MalformedURLException;
import java.lang.reflect.*;
import java.text.Collator;
import java.text.MessageFormat;
import sun.security.util.PropertyExpander;
import sun.security.util.PropertyExpander.ExpandException;
import java.awt.*;
import java.awt.event.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.*;
import sun.security.provider.*;
import sun.security.util.PolicyUtil;
import javax.security.auth.x500.X500Principal;

/**
 * PolicyTool may be used by users and administrators to configure the
 * overall java security policy (currently stored in the policy file).
 * Using PolicyTool administators may add and remove policies from
 * the policy file. <p>
 *
 * @see java.security.Policy
 * @since   1.2
 */

public class PolicyTool {

    // for i18n
    static final java.util.ResourceBundle rb =
        java.util.ResourceBundle.getBundle("sun.security.util.Resources");
    static final Collator collator = Collator.getInstance();
    static {
        // this is for case insensitive string comparisons
        collator.setStrength(Collator.PRIMARY);
    };

    // anyone can add warnings
    Vector<String> warnings;
    boolean newWarning = false;

    // set to true if policy modified.
    // this way upon exit we know if to ask the user to save changes
    boolean modified = false;

    private static final boolean testing = false;
    private static final Class[] TWOPARAMS = { String.class, String.class };
    private static final Class[] ONEPARAMS = { String.class };
    private static final Class[] NOPARAMS  = {};
    /*
     * All of the policy entries are read in from the
     * policy file and stored here.  Updates to the policy entries
     * using addEntry() and removeEntry() are made here.  To ultimately save
     * the policy entries back to the policy file, the SavePolicy button
     * must be clicked.
     **/
    private static String policyFileName = null;
    private Vector<PolicyEntry> policyEntries = null;
    private PolicyParser parser = null;

    /* The public key alias information is stored here.  */
    private KeyStore keyStore = null;
    private String keyStoreName = " ";
    private String keyStoreType = " ";
    private String keyStoreProvider = " ";
    private String keyStorePwdURL = " ";

    /* standard PKCS11 KeyStore type */
    private static final String P11KEYSTORE = "PKCS11";

    /* reserved word for PKCS11 KeyStores */
    private static final String NONE = "NONE";

    /**
     * default constructor
     */
    private PolicyTool() {
        policyEntries = new Vector<PolicyEntry>();
        parser = new PolicyParser();
        warnings = new Vector<String>();
    }

    /**
     * get the PolicyFileName
     */
    String getPolicyFileName() {
        return policyFileName;
    }

    /**
     * set the PolicyFileName
     */
    void setPolicyFileName(String policyFileName) {
        this.policyFileName = policyFileName;
    }

   /**
    * clear keyStore info
    */
    void clearKeyStoreInfo() {
        this.keyStoreName = null;
        this.keyStoreType = null;
        this.keyStoreProvider = null;
        this.keyStorePwdURL = null;

        this.keyStore = null;
    }

    /**
     * get the keyStore URL name
     */
    String getKeyStoreName() {
        return keyStoreName;
    }

    /**
     * get the keyStore Type
     */
    String getKeyStoreType() {
        return keyStoreType;
    }

    /**
     * get the keyStore Provider
     */
    String getKeyStoreProvider() {
        return keyStoreProvider;
    }

    /**
     * get the keyStore password URL
     */
    String getKeyStorePwdURL() {
        return keyStorePwdURL;
    }

    /**
     * Open and read a policy file
     */
    void openPolicy(String filename) throws FileNotFoundException,
                                        PolicyParser.ParsingException,
                                        KeyStoreException,
                                        CertificateException,
                                        InstantiationException,
                                        MalformedURLException,
                                        IOException,
                                        NoSuchAlgorithmException,
                                        IllegalAccessException,
                                        NoSuchMethodException,
                                        UnrecoverableKeyException,
                                        NoSuchProviderException,
                                        ClassNotFoundException,
                                        PropertyExpander.ExpandException,
                                        InvocationTargetException {

        newWarning = false;

        // start fresh - blow away the current state
        policyEntries = new Vector<PolicyEntry>();
        parser = new PolicyParser();
        warnings = new Vector<String>();
        setPolicyFileName(null);
        clearKeyStoreInfo();

        // see if user is opening a NEW policy file
        if (filename == null) {
            modified = false;
            return;
        }

        // Read in the policy entries from the file and
        // populate the parser vector table.  The parser vector
        // table only holds the entries as strings, so it only
        // guarantees that the policies are syntactically
        // correct.
        setPolicyFileName(filename);
        parser.read(new FileReader(filename));

        // open the keystore
        openKeyStore(parser.getKeyStoreUrl(), parser.getKeyStoreType(),
                parser.getKeyStoreProvider(), parser.getStorePassURL());

        // Update the local vector with the same policy entries.
        // This guarantees that the policy entries are not only
        // syntactically correct, but semantically valid as well.
        Enumeration<PolicyParser.GrantEntry> enum_ = parser.grantElements();
        while (enum_.hasMoreElements()) {
            PolicyParser.GrantEntry ge = enum_.nextElement();

            // see if all the signers have public keys
            if (ge.signedBy != null) {

                String signers[] = parseSigners(ge.signedBy);
                for (int i = 0; i < signers.length; i++) {
                    PublicKey pubKey = getPublicKeyAlias(signers[i]);
                    if (pubKey == null) {
                        newWarning = true;
                        MessageFormat form = new MessageFormat(rb.getString
231
                            ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));
D
duke 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
                        Object[] source = {signers[i]};
                        warnings.addElement(form.format(source));
                    }
                }
            }

            // check to see if the Principals are valid
            ListIterator<PolicyParser.PrincipalEntry> prinList =
                                                ge.principals.listIterator(0);
            while (prinList.hasNext()) {
                PolicyParser.PrincipalEntry pe = prinList.next();
                try {
                    verifyPrincipal(pe.getPrincipalClass(),
                                pe.getPrincipalName());
                } catch (ClassNotFoundException fnfe) {
                    newWarning = true;
                    MessageFormat form = new MessageFormat(rb.getString
249
                                ("Warning.Class.not.found.class"));
D
duke 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
                    Object[] source = {pe.getPrincipalClass()};
                    warnings.addElement(form.format(source));
                }
            }

            // check to see if the Permissions are valid
            Enumeration<PolicyParser.PermissionEntry> perms =
                                                ge.permissionElements();
            while (perms.hasMoreElements()) {
                PolicyParser.PermissionEntry pe = perms.nextElement();
                try {
                    verifyPermission(pe.permission, pe.name, pe.action);
                } catch (ClassNotFoundException fnfe) {
                    newWarning = true;
                    MessageFormat form = new MessageFormat(rb.getString
265
                                ("Warning.Class.not.found.class"));
D
duke 已提交
266 267 268 269 270
                    Object[] source = {pe.permission};
                    warnings.addElement(form.format(source));
                } catch (InvocationTargetException ite) {
                    newWarning = true;
                    MessageFormat form = new MessageFormat(rb.getString
271
                        ("Warning.Invalid.argument.s.for.constructor.arg"));
D
duke 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285
                    Object[] source = {pe.permission};
                    warnings.addElement(form.format(source));
                }

                // see if all the permission signers have public keys
                if (pe.signedBy != null) {

                    String signers[] = parseSigners(pe.signedBy);

                    for (int i = 0; i < signers.length; i++) {
                        PublicKey pubKey = getPublicKeyAlias(signers[i]);
                        if (pubKey == null) {
                            newWarning = true;
                            MessageFormat form = new MessageFormat(rb.getString
286
                                ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));
D
duke 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
                            Object[] source = {signers[i]};
                            warnings.addElement(form.format(source));
                        }
                    }
                }
            }
            PolicyEntry pEntry = new PolicyEntry(this, ge);
            policyEntries.addElement(pEntry);
        }

        // just read in the policy -- nothing has been modified yet
        modified = false;
    }


    /**
     * Save a policy to a file
     */
    void savePolicy(String filename)
    throws FileNotFoundException, IOException {
        // save the policy entries to a file
        parser.setKeyStoreUrl(keyStoreName);
        parser.setKeyStoreType(keyStoreType);
        parser.setKeyStoreProvider(keyStoreProvider);
        parser.setStorePassURL(keyStorePwdURL);
        parser.write(new FileWriter(filename));
        modified = false;
    }

    /**
     * Open the KeyStore
     */
    void openKeyStore(String name,
                String type,
                String provider,
                String pwdURL) throws   KeyStoreException,
                                        NoSuchAlgorithmException,
                                        UnrecoverableKeyException,
                                        IOException,
                                        CertificateException,
                                        NoSuchProviderException,
                                        ExpandException {

        if (name == null && type == null &&
            provider == null && pwdURL == null) {

            // policy did not specify a keystore during open
            // or use wants to reset keystore values

            this.keyStoreName = null;
            this.keyStoreType = null;
            this.keyStoreProvider = null;
            this.keyStorePwdURL = null;

            // caller will set (tool.modified = true) if appropriate

            return;
        }

        URL policyURL = null;
        if (policyFileName != null) {
            File pfile = new File(policyFileName);
            policyURL = new URL("file:" + pfile.getCanonicalPath());
        }

        // although PolicyUtil.getKeyStore may properly handle
        // defaults and property expansion, we do it here so that
        // if the call is successful, we can set the proper values
        // (PolicyUtil.getKeyStore does not return expanded values)

        if (name != null && name.length() > 0) {
            name = PropertyExpander.expand(name).replace
                                        (File.separatorChar, '/');
        }
        if (type == null || type.length() == 0) {
            type = KeyStore.getDefaultType();
        }
        if (pwdURL != null && pwdURL.length() > 0) {
            pwdURL = PropertyExpander.expand(pwdURL).replace
                                        (File.separatorChar, '/');
        }

        try {
            this.keyStore = PolicyUtil.getKeyStore(policyURL,
                                                name,
                                                type,
                                                provider,
                                                pwdURL,
                                                null);
        } catch (IOException ioe) {

            // copied from sun.security.pkcs11.SunPKCS11
            String MSG = "no password provided, and no callback handler " +
                        "available for retrieving password";

            Throwable cause = ioe.getCause();
            if (cause != null &&
                cause instanceof javax.security.auth.login.LoginException &&
                MSG.equals(cause.getMessage())) {

                // throw a more friendly exception message
                throw new IOException(MSG);
            } else {
                throw ioe;
            }
        }

        this.keyStoreName = name;
        this.keyStoreType = type;
        this.keyStoreProvider = provider;
        this.keyStorePwdURL = pwdURL;

        // caller will set (tool.modified = true)
    }

    /**
     * Add a Grant entry to the overall policy at the specified index.
     * A policy entry consists of a CodeSource.
     */
    boolean addEntry(PolicyEntry pe, int index) {

        if (index < 0) {
            // new entry -- just add it to the end
            policyEntries.addElement(pe);
            parser.add(pe.getGrantEntry());
        } else {
            // existing entry -- replace old one
            PolicyEntry origPe = policyEntries.elementAt(index);
            parser.replace(origPe.getGrantEntry(), pe.getGrantEntry());
            policyEntries.setElementAt(pe, index);
        }
        return true;
    }

    /**
     * Add a Principal entry to an existing PolicyEntry at the specified index.
     * A Principal entry consists of a class, and name.
     *
     * If the principal already exists, it is not added again.
     */
    boolean addPrinEntry(PolicyEntry pe,
                        PolicyParser.PrincipalEntry newPrin,
                        int index) {

        // first add the principal to the Policy Parser entry
        PolicyParser.GrantEntry grantEntry = pe.getGrantEntry();
        if (grantEntry.contains(newPrin) == true)
            return false;

        LinkedList<PolicyParser.PrincipalEntry> prinList =
                                                grantEntry.principals;
        if (index != -1)
            prinList.set(index, newPrin);
        else
            prinList.add(newPrin);

        modified = true;
        return true;
    }

    /**
     * Add a Permission entry to an existing PolicyEntry at the specified index.
     * A Permission entry consists of a permission, name, and actions.
     *
     * If the permission already exists, it is not added again.
     */
    boolean addPermEntry(PolicyEntry pe,
                        PolicyParser.PermissionEntry newPerm,
                        int index) {

        // first add the permission to the Policy Parser Vector
        PolicyParser.GrantEntry grantEntry = pe.getGrantEntry();
        if (grantEntry.contains(newPerm) == true)
            return false;

        Vector<PolicyParser.PermissionEntry> permList =
                                                grantEntry.permissionEntries;
        if (index != -1)
            permList.setElementAt(newPerm, index);
        else
            permList.addElement(newPerm);

        modified = true;
        return true;
    }

    /**
     * Remove a Permission entry from an existing PolicyEntry.
     */
    boolean removePermEntry(PolicyEntry pe,
                        PolicyParser.PermissionEntry perm) {

        // remove the Permission from the GrantEntry
        PolicyParser.GrantEntry ppge = pe.getGrantEntry();
        modified = ppge.remove(perm);
        return modified;
    }

    /**
     * remove an entry from the overall policy
     */
    boolean removeEntry(PolicyEntry pe) {

        parser.remove(pe.getGrantEntry());
        modified = true;
        return (policyEntries.removeElement(pe));
    }

    /**
     * retrieve all Policy Entries
     */
    PolicyEntry[] getEntry() {

        if (policyEntries.size() > 0) {
            PolicyEntry entries[] = new PolicyEntry[policyEntries.size()];
            for (int i = 0; i < policyEntries.size(); i++)
                entries[i] = policyEntries.elementAt(i);
            return entries;
        }
        return null;
    }

    /**
     * Retrieve the public key mapped to a particular name.
     * If the key has expired, a KeyException is thrown.
     */
    PublicKey getPublicKeyAlias(String name) throws KeyStoreException {
        if (keyStore == null) {
            return null;
        }

        Certificate cert = keyStore.getCertificate(name);
        if (cert == null) {
            return null;
        }
        PublicKey pubKey = cert.getPublicKey();
        return pubKey;
    }

    /**
     * Retrieve all the alias names stored in the certificate database
     */
    String[] getPublicKeyAlias() throws KeyStoreException {

        int numAliases = 0;
        String aliases[] = null;

        if (keyStore == null) {
            return null;
        }
        Enumeration<String> enum_ = keyStore.aliases();

        // first count the number of elements
        while (enum_.hasMoreElements()) {
            enum_.nextElement();
            numAliases++;
        }

        if (numAliases > 0) {
            // now copy them into an array
            aliases = new String[numAliases];
            numAliases = 0;
            enum_ = keyStore.aliases();
            while (enum_.hasMoreElements()) {
                aliases[numAliases] = new String(enum_.nextElement());
                numAliases++;
            }
        }
        return aliases;
    }

    /**
     * This method parses a single string of signers separated by commas
     * ("jordan, duke, pippen") into an array of individual strings.
     */
    String[] parseSigners(String signedBy) {

        String signers[] = null;
        int numSigners = 1;
        int signedByIndex = 0;
        int commaIndex = 0;
        int signerNum = 0;

        // first pass thru "signedBy" counts the number of signers
        while (commaIndex >= 0) {
            commaIndex = signedBy.indexOf(',', signedByIndex);
            if (commaIndex >= 0) {
                numSigners++;
                signedByIndex = commaIndex + 1;
            }
        }
        signers = new String[numSigners];

        // second pass thru "signedBy" transfers signers to array
        commaIndex = 0;
        signedByIndex = 0;
        while (commaIndex >= 0) {
            if ((commaIndex = signedBy.indexOf(',', signedByIndex)) >= 0) {
                // transfer signer and ignore trailing part of the string
                signers[signerNum] =
                        signedBy.substring(signedByIndex, commaIndex).trim();
                signerNum++;
                signedByIndex = commaIndex + 1;
            } else {
                // we are at the end of the string -- transfer signer
                signers[signerNum] = signedBy.substring(signedByIndex).trim();
            }
        }
        return signers;
    }

    /**
     * Check to see if the Principal contents are OK
     */
    void verifyPrincipal(String type, String name)
        throws ClassNotFoundException,
               InstantiationException
    {
        if (type.equals(PolicyParser.PrincipalEntry.WILDCARD_CLASS) ||
            type.equals(PolicyParser.REPLACE_NAME)) {
            return;
        };
        Class<?> PRIN = Class.forName("java.security.Principal");
        Class<?> pc = Class.forName(type, true,
                Thread.currentThread().getContextClassLoader());
        if (!PRIN.isAssignableFrom(pc)) {
            MessageFormat form = new MessageFormat(rb.getString
614
                        ("Illegal.Principal.Type.type"));
D
duke 已提交
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
            Object[] source = {type};
            throw new InstantiationException(form.format(source));
        }

        if (ToolDialog.X500_PRIN_CLASS.equals(pc.getName())) {
            // PolicyParser checks validity of X500Principal name
            // - PolicyTool needs to as well so that it doesn't store
            //   an invalid name that can't be read in later
            //
            // this can throw an IllegalArgumentException
            X500Principal newP = new X500Principal(name);
        }
    }

    /**
     * Check to see if the Permission contents are OK
     */
    void verifyPermission(String type,
                                    String name,
                                    String actions)
        throws ClassNotFoundException,
               InstantiationException,
               IllegalAccessException,
               NoSuchMethodException,
               InvocationTargetException
    {

        //XXX we might want to keep a hash of created factories...
        Class<?> pc = Class.forName(type, true,
                Thread.currentThread().getContextClassLoader());
        Constructor<?> c = null;
        Vector<String> objects = new Vector<String>(2);
        if (name != null) objects.add(name);
        if (actions != null) objects.add(actions);
        switch (objects.size()) {
        case 0:
            try {
                c = pc.getConstructor(NOPARAMS);
                break;
            } catch (NoSuchMethodException ex) {
                // proceed to the one-param constructor
                objects.add(null);
            }
        case 1:
            try {
                c = pc.getConstructor(ONEPARAMS);
                break;
            } catch (NoSuchMethodException ex) {
                // proceed to the two-param constructor
                objects.add(null);
            }
        case 2:
            c = pc.getConstructor(TWOPARAMS);
            break;
        }
        Object parameters[] = objects.toArray();
        Permission p = (Permission)c.newInstance(parameters);
    }

    /*
     * Parse command line arguments.
     */
    static void parseArgs(String args[]) {
        /* parse flags */
        int n = 0;

        for (n=0; (n < args.length) && args[n].startsWith("-"); n++) {

            String flags = args[n];

            if (collator.compare(flags, "-file") == 0) {
                if (++n == args.length) usage();
                policyFileName = args[n];
            } else {
                MessageFormat form = new MessageFormat(rb.getString
690
                                ("Illegal.option.option"));
D
duke 已提交
691 692 693 694 695 696 697 698
                Object[] source = { flags };
                System.err.println(form.format(source));
                usage();
            }
        }
    }

    static void usage() {
699
        System.out.println(rb.getString("Usage.policytool.options."));
D
duke 已提交
700 701
        System.out.println();
        System.out.println(rb.getString
702
                (".file.file.policy.file.location"));
D
duke 已提交
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
        System.out.println();

        System.exit(1);
    }

    /**
     * run the PolicyTool
     */
    public static void main(String args[]) {
        parseArgs(args);
        ToolWindow tw = new ToolWindow(new PolicyTool());
        tw.displayToolWindow(args);
    }

    // split instr to words according to capitalization,
    // like, AWTControl -> A W T Control
    // this method is for easy pronounciation
    static String splitToWords(String instr) {
        return instr.replaceAll("([A-Z])", " $1");
    }

}

/**
 * Each entry in the policy configuration file is represented by a
 * PolicyEntry object.
 *
 * A PolicyEntry is a (CodeSource,Permission) pair.  The
 * CodeSource contains the (URL, PublicKey) that together identify
 * where the Java bytecodes come from and who (if anyone) signed
 * them.  The URL could refer to localhost.  The URL could also be
 * null, meaning that this policy entry is given to all comers, as
 * long as they match the signer field.  The signer could be null,
 * meaning the code is not signed.
 *
 * The Permission contains the (Type, Name, Action) triplet.
 *
 */
class PolicyEntry {

    private CodeSource codesource;
    private PolicyTool tool;
    private PolicyParser.GrantEntry grantEntry;
    private boolean testing = false;

    /**
     * Create a PolicyEntry object from the information read in
     * from a policy file.
     */
    PolicyEntry(PolicyTool tool, PolicyParser.GrantEntry ge)
    throws MalformedURLException, NoSuchMethodException,
    ClassNotFoundException, InstantiationException, IllegalAccessException,
    InvocationTargetException, CertificateException,
    IOException, NoSuchAlgorithmException, UnrecoverableKeyException {

        this.tool = tool;

        URL location = null;

        // construct the CodeSource
        if (ge.codeBase != null)
            location = new URL(ge.codeBase);
        this.codesource = new CodeSource(location,
            (java.security.cert.Certificate[]) null);

        if (testing) {
            System.out.println("Adding Policy Entry:");
            System.out.println("    CodeBase = " + location);
            System.out.println("    Signers = " + ge.signedBy);
            System.out.println("    with " + ge.principals.size() +
                    " Principals");
        }

        this.grantEntry = ge;
    }

    /**
     * get the codesource associated with this PolicyEntry
     */
    CodeSource getCodeSource() {
        return codesource;
    }

    /**
     * get the GrantEntry associated with this PolicyEntry
     */
    PolicyParser.GrantEntry getGrantEntry() {
        return grantEntry;
    }

    /**
     * convert the header portion, i.e. codebase, signer, principals, of
     * this policy entry into a string
     */
    String headerToString() {
        String pString = principalsToString();
        if (pString.length() == 0) {
            return codebaseToString();
        } else {
            return codebaseToString() + ", " + pString;
        }
    }

    /**
     * convert the Codebase/signer portion of this policy entry into a string
     */
    String codebaseToString() {

        String stringEntry = new String();

        if (grantEntry.codeBase != null &&
            grantEntry.codeBase.equals("") == false)
            stringEntry = stringEntry.concat
                                ("CodeBase \"" +
                                grantEntry.codeBase +
                                "\"");

        if (grantEntry.signedBy != null &&
            grantEntry.signedBy.equals("") == false)
            stringEntry = ((stringEntry.length() > 0) ?
                stringEntry.concat(", SignedBy \"" +
                                grantEntry.signedBy +
                                "\"") :
                stringEntry.concat("SignedBy \"" +
                                grantEntry.signedBy +
                                "\""));

        if (stringEntry.length() == 0)
            return new String("CodeBase <ALL>");
        return stringEntry;
    }

    /**
     * convert the Principals portion of this policy entry into a string
     */
    String principalsToString() {
        String result = "";
        if ((grantEntry.principals != null) &&
            (!grantEntry.principals.isEmpty())) {
            StringBuffer buffer = new StringBuffer(200);
            ListIterator<PolicyParser.PrincipalEntry> list =
                                grantEntry.principals.listIterator();
            while (list.hasNext()) {
                PolicyParser.PrincipalEntry pppe = list.next();
                buffer.append(" Principal " + pppe.getDisplayClass() + " " +
                    pppe.getDisplayName(true));
                if (list.hasNext()) buffer.append(", ");
            }
            result = buffer.toString();
        }
        return result;
    }

    /**
     * convert this policy entry into a PolicyParser.PermissionEntry
     */
    PolicyParser.PermissionEntry toPermissionEntry(Permission perm) {

        String actions = null;

        // get the actions
        if (perm.getActions() != null &&
            perm.getActions().trim() != "")
                actions = perm.getActions();

        PolicyParser.PermissionEntry pe = new PolicyParser.PermissionEntry
                        (perm.getClass().getName(),
                        perm.getName(),
                        actions);
        return pe;
    }
}

/**
 * The main window for the PolicyTool
 */
class ToolWindow extends Frame {
    // use serialVersionUID from JDK 1.2.2 for interoperability
    private static final long serialVersionUID = 5682568601210376777L;

    /* external paddings */
    public static final Insets TOP_PADDING = new Insets(25,0,0,0);
    public static final Insets BOTTOM_PADDING = new Insets(0,0,25,0);
    public static final Insets LITE_BOTTOM_PADDING = new Insets(0,0,10,0);
    public static final Insets LR_PADDING = new Insets(0,10,0,10);
    public static final Insets TOP_BOTTOM_PADDING = new Insets(15, 0, 15, 0);
    public static final Insets L_TOP_BOTTOM_PADDING = new Insets(5,10,15,0);
    public static final Insets LR_BOTTOM_PADDING = new Insets(0,10,5,10);
    public static final Insets L_BOTTOM_PADDING = new Insets(0,10,5,0);
    public static final Insets R_BOTTOM_PADDING = new Insets(0,0,5,10);

    /* buttons and menus */
    public static final String NEW_POLICY_FILE          =
                        PolicyTool.rb.getString("New");
    public static final String OPEN_POLICY_FILE         =
                        PolicyTool.rb.getString("Open");
    public static final String SAVE_POLICY_FILE         =
                        PolicyTool.rb.getString("Save");
    public static final String SAVE_AS_POLICY_FILE      =
902
                        PolicyTool.rb.getString("Save.As");
D
duke 已提交
903
    public static final String VIEW_WARNINGS            =
904
                        PolicyTool.rb.getString("View.Warning.Log");
D
duke 已提交
905 906 907
    public static final String QUIT                     =
                        PolicyTool.rb.getString("Exit");
    public static final String ADD_POLICY_ENTRY         =
908
                        PolicyTool.rb.getString("Add.Policy.Entry");
D
duke 已提交
909
    public static final String EDIT_POLICY_ENTRY        =
910
                        PolicyTool.rb.getString("Edit.Policy.Entry");
D
duke 已提交
911
    public static final String REMOVE_POLICY_ENTRY      =
912
                        PolicyTool.rb.getString("Remove.Policy.Entry");
D
duke 已提交
913 914 915
    public static final String EDIT_KEYSTORE            =
                        PolicyTool.rb.getString("Edit");
    public static final String ADD_PUBKEY_ALIAS         =
916
                        PolicyTool.rb.getString("Add.Public.Key.Alias");
D
duke 已提交
917
    public static final String REMOVE_PUBKEY_ALIAS      =
918
                        PolicyTool.rb.getString("Remove.Public.Key.Alias");
D
duke 已提交
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966

    /* gridbag index for components in the main window (MW) */
    public static final int MW_FILENAME_LABEL           = 0;
    public static final int MW_FILENAME_TEXTFIELD       = 1;
    public static final int MW_PANEL                    = 2;
    public static final int MW_ADD_BUTTON               = 0;
    public static final int MW_EDIT_BUTTON              = 1;
    public static final int MW_REMOVE_BUTTON            = 2;
    public static final int MW_POLICY_LIST              = 3; // follows MW_PANEL

    private PolicyTool tool;

    /**
     * Constructor
     */
    ToolWindow(PolicyTool tool) {
        this.tool = tool;
    }

    /**
     * Initialize the PolicyTool window with the necessary components
     */
    private void initWindow() {

        // create the top menu bar
        MenuBar menuBar = new MenuBar();

        // create a File menu
        Menu menu = new Menu(PolicyTool.rb.getString("File"));
        menu.add(NEW_POLICY_FILE);
        menu.add(OPEN_POLICY_FILE);
        menu.add(SAVE_POLICY_FILE);
        menu.add(SAVE_AS_POLICY_FILE);
        menu.add(VIEW_WARNINGS);
        menu.add(QUIT);
        menu.addActionListener(new FileMenuListener(tool, this));
        menuBar.add(menu);
        setMenuBar(menuBar);

        // create a KeyStore menu
        menu = new Menu(PolicyTool.rb.getString("KeyStore"));
        menu.add(EDIT_KEYSTORE);
        menu.addActionListener(new MainWindowListener(tool, this));
        menuBar.add(menu);
        setMenuBar(menuBar);


        // policy entry listing
967
        Label label = new Label(PolicyTool.rb.getString("Policy.File."));
D
duke 已提交
968 969 970 971 972
        addNewComponent(this, label, MW_FILENAME_LABEL,
                        0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                        TOP_BOTTOM_PADDING);
        TextField tf = new TextField(50);
        tf.getAccessibleContext().setAccessibleName(
973
                PolicyTool.rb.getString("Policy.File."));
D
duke 已提交
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
        tf.setEditable(false);
        addNewComponent(this, tf, MW_FILENAME_TEXTFIELD,
                        1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                        TOP_BOTTOM_PADDING);


        // add ADD/REMOVE/EDIT buttons in a new panel
        Panel panel = new Panel();
        panel.setLayout(new GridBagLayout());

        Button button = new Button(ADD_POLICY_ENTRY);
        button.addActionListener(new MainWindowListener(tool, this));
        addNewComponent(panel, button, MW_ADD_BUTTON,
                        0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                        LR_PADDING);

        button = new Button(EDIT_POLICY_ENTRY);
        button.addActionListener(new MainWindowListener(tool, this));
        addNewComponent(panel, button, MW_EDIT_BUTTON,
                        1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                        LR_PADDING);

        button = new Button(REMOVE_POLICY_ENTRY);
        button.addActionListener(new MainWindowListener(tool, this));
        addNewComponent(panel, button, MW_REMOVE_BUTTON,
                        2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                        LR_PADDING);

        addNewComponent(this, panel, MW_PANEL,
                        0, 2, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                        BOTTOM_PADDING);


        String policyFile = tool.getPolicyFileName();
        if (policyFile == null) {
            String userHome;
            userHome = java.security.AccessController.doPrivileged(
                    new sun.security.action.GetPropertyAction("user.home"));
            policyFile = userHome + File.separatorChar + ".java.policy";
        }

        try {
            // open the policy file
            tool.openPolicy(policyFile);

            // display the policy entries via the policy list textarea
            List list = new List(40, false);
            list.addActionListener(new PolicyListListener(tool, this));
            PolicyEntry entries[] = tool.getEntry();
            if (entries != null) {
                for (int i = 0; i < entries.length; i++)
                    list.add(entries[i].headerToString());
            }
            TextField newFilename = (TextField)
                                getComponent(MW_FILENAME_TEXTFIELD);
            newFilename.setText(policyFile);
            initPolicyList(list);

        } catch (FileNotFoundException fnfe) {
            // add blank policy listing
            List list = new List(40, false);
            list.addActionListener(new PolicyListListener(tool, this));
            initPolicyList(list);
            tool.setPolicyFileName(null);
            tool.modified = false;
            setVisible(true);

            // just add warning
            tool.warnings.addElement(fnfe.toString());

        } catch (Exception e) {
            // add blank policy listing
            List list = new List(40, false);
            list.addActionListener(new PolicyListListener(tool, this));
            initPolicyList(list);
            tool.setPolicyFileName(null);
            tool.modified = false;
            setVisible(true);

            // display the error
            MessageFormat form = new MessageFormat(PolicyTool.rb.getString
1055
                ("Could.not.open.policy.file.policyFile.e.toString."));
D
duke 已提交
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
            Object[] source = {policyFile, e.toString()};
            displayErrorDialog(null, form.format(source));
        }
    }


    /**
     * Add a component to the PolicyTool window
     */
    void addNewComponent(Container container, Component component,
        int index, int gridx, int gridy, int gridwidth, int gridheight,
        double weightx, double weighty, int fill, Insets is) {

        // add the component at the specified gridbag index
        container.add(component, index);

        // set the constraints
        GridBagLayout gbl = (GridBagLayout)container.getLayout();
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = gridx;
        gbc.gridy = gridy;
        gbc.gridwidth = gridwidth;
        gbc.gridheight = gridheight;
        gbc.weightx = weightx;
        gbc.weighty = weighty;
        gbc.fill = fill;
        if (is != null) gbc.insets = is;
        gbl.setConstraints(component, gbc);
    }


    /**
     * Add a component to the PolicyTool window without external padding
     */
    void addNewComponent(Container container, Component component,
        int index, int gridx, int gridy, int gridwidth, int gridheight,
        double weightx, double weighty, int fill) {

        // delegate with "null" external padding
        addNewComponent(container, component, index, gridx, gridy,
                        gridwidth, gridheight, weightx, weighty,
                        fill, null);
    }


    /**
     * Init the policy_entry_list TEXTAREA component in the
     * PolicyTool window
     */
    void initPolicyList(List policyList) {

        // add the policy list to the window
        addNewComponent(this, policyList, MW_POLICY_LIST,
                        0, 3, 2, 1, 1.0, 1.0, GridBagConstraints.BOTH);
    }

    /**
     * Replace the policy_entry_list TEXTAREA component in the
     * PolicyTool window with an updated one.
     */
    void replacePolicyList(List policyList) {

        // remove the original list of Policy Entries
        // and add the new list of entries
        List list = (List)getComponent(MW_POLICY_LIST);
        list.removeAll();
        String newItems[] = policyList.getItems();
        for (int i = 0; i < newItems.length; i++)
            list.add(newItems[i]);
    }

    /**
     * display the main PolicyTool window
     */
    void displayToolWindow(String args[]) {

1132
        setTitle(PolicyTool.rb.getString("Policy.Tool"));
D
duke 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
        setResizable(true);
        addWindowListener(new ToolWindowListener(this));
        setBounds(135, 80, 500, 500);
        setLayout(new GridBagLayout());

        initWindow();

        // display it
        setVisible(true);

        if (tool.newWarning == true) {
            displayStatusDialog(this, PolicyTool.rb.getString
1145
                ("Errors.have.occurred.while.opening.the.policy.configuration.View.the.Warning.Log.for.more.information."));
D
duke 已提交
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
        }
    }

    /**
     * displays a dialog box describing an error which occurred.
     */
    void displayErrorDialog(Window w, String error) {
        ToolDialog ed = new ToolDialog
                (PolicyTool.rb.getString("Error"), tool, this, true);

        // find where the PolicyTool gui is
        Point location = ((w == null) ?
                getLocationOnScreen() : w.getLocationOnScreen());
        ed.setBounds(location.x + 50, location.y + 50, 600, 100);
        ed.setLayout(new GridBagLayout());

        Label label = new Label(error);
        addNewComponent(ed, label, 0,
                        0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);

        Button okButton = new Button(PolicyTool.rb.getString("OK"));
        okButton.addActionListener(new ErrorOKButtonListener(ed));
        addNewComponent(ed, okButton, 1,
                        0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);

        ed.pack();
        ed.setVisible(true);
    }

    /**
     * displays a dialog box describing an error which occurred.
     */
    void displayErrorDialog(Window w, Throwable t) {
        if (t instanceof NoDisplayException) {
            return;
        }
        displayErrorDialog(w, t.toString());
    }

    /**
     * displays a dialog box describing the status of an event
     */
    void displayStatusDialog(Window w, String status) {
        ToolDialog sd = new ToolDialog
                (PolicyTool.rb.getString("Status"), tool, this, true);

        // find the location of the PolicyTool gui
        Point location = ((w == null) ?
                getLocationOnScreen() : w.getLocationOnScreen());
        sd.setBounds(location.x + 50, location.y + 50, 500, 100);
        sd.setLayout(new GridBagLayout());

        Label label = new Label(status);
        addNewComponent(sd, label, 0,
                        0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);

        Button okButton = new Button(PolicyTool.rb.getString("OK"));
        okButton.addActionListener(new StatusOKButtonListener(sd));
        addNewComponent(sd, okButton, 1,
                        0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);
        sd.pack();
        sd.setVisible(true);
    }

    /**
     * display the warning log
     */
    void displayWarningLog(Window w) {

        ToolDialog wd = new ToolDialog
                (PolicyTool.rb.getString("Warning"), tool, this, true);

        // find the location of the PolicyTool gui
        Point location = ((w == null) ?
                getLocationOnScreen() : w.getLocationOnScreen());
        wd.setBounds(location.x + 50, location.y + 50, 500, 100);
        wd.setLayout(new GridBagLayout());

        TextArea ta = new TextArea();
        ta.setEditable(false);
        for (int i = 0; i < tool.warnings.size(); i++) {
            ta.append(tool.warnings.elementAt(i));
1228
            ta.append(PolicyTool.rb.getString("NEWLINE"));
D
duke 已提交
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
        }
        addNewComponent(wd, ta, 0,
                        0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                        BOTTOM_PADDING);
        ta.setFocusable(false);

        Button okButton = new Button(PolicyTool.rb.getString("OK"));
        okButton.addActionListener(new CancelButtonListener(wd));
        addNewComponent(wd, okButton, 1,
                        0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                        LR_PADDING);

        wd.pack();
        wd.setVisible(true);
    }

    char displayYesNoDialog(Window w, String title, String prompt, String yes, String no) {

        final ToolDialog tw = new ToolDialog
                (title, tool, this, true);
        Point location = ((w == null) ?
                getLocationOnScreen() : w.getLocationOnScreen());
        tw.setBounds(location.x + 75, location.y + 100, 400, 150);
        tw.setLayout(new GridBagLayout());

        TextArea ta = new TextArea(prompt, 10, 50, TextArea.SCROLLBARS_VERTICAL_ONLY);
        ta.setEditable(false);
        addNewComponent(tw, ta, 0,
                0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
        ta.setFocusable(false);

        Panel panel = new Panel();
        panel.setLayout(new GridBagLayout());

        // StringBuffer to store button press. Must be final.
        final StringBuffer chooseResult = new StringBuffer();

        Button button = new Button(yes);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                chooseResult.append('Y');
                tw.setVisible(false);
                tw.dispose();
            }
        });
        addNewComponent(panel, button, 0,
                           0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                           LR_PADDING);

        button = new Button(no);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                chooseResult.append('N');
                tw.setVisible(false);
                tw.dispose();
            }
        });
        addNewComponent(panel, button, 1,
                           1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                           LR_PADDING);

        addNewComponent(tw, panel, 1,
                0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);

        tw.pack();
        tw.setVisible(true);
        if (chooseResult.length() > 0) {
            return chooseResult.charAt(0);
        } else {
            // I did encounter this once, don't why.
            return 'N';
        }
    }

}

/**
 * General dialog window
 */
class ToolDialog extends Dialog {
    // use serialVersionUID from JDK 1.2.2 for interoperability
    private static final long serialVersionUID = -372244357011301190L;

    /* necessary constants */
    public static final int NOACTION            = 0;
    public static final int QUIT                = 1;
    public static final int NEW                 = 2;
    public static final int OPEN                = 3;

    public static final String ALL_PERM_CLASS   =
                "java.security.AllPermission";
    public static final String FILE_PERM_CLASS  =
                "java.io.FilePermission";

    public static final String X500_PRIN_CLASS         =
                "javax.security.auth.x500.X500Principal";

    /* popup menus */
    public static final String PERM             =
        PolicyTool.rb.getString
1329
        ("Permission.");
D
duke 已提交
1330 1331

    public static final String PRIN_TYPE        =
1332
        PolicyTool.rb.getString("Principal.Type.");
D
duke 已提交
1333
    public static final String PRIN_NAME        =
1334
        PolicyTool.rb.getString("Principal.Name.");
D
duke 已提交
1335 1336 1337 1338

    /* more popu menus */
    public static final String PERM_NAME        =
        PolicyTool.rb.getString
1339
        ("Target.Name.");
D
duke 已提交
1340 1341 1342 1343

    /* and more popup menus */
    public static final String PERM_ACTIONS             =
      PolicyTool.rb.getString
1344
      ("Actions.");
D
duke 已提交
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450

    /* gridbag index for display OverWriteFile (OW) components */
    public static final int OW_LABEL                    = 0;
    public static final int OW_OK_BUTTON                = 1;
    public static final int OW_CANCEL_BUTTON            = 2;

    /* gridbag index for display PolicyEntry (PE) components */
    public static final int PE_CODEBASE_LABEL           = 0;
    public static final int PE_CODEBASE_TEXTFIELD       = 1;
    public static final int PE_SIGNEDBY_LABEL           = 2;
    public static final int PE_SIGNEDBY_TEXTFIELD       = 3;

    public static final int PE_PANEL0                   = 4;
    public static final int PE_ADD_PRIN_BUTTON          = 0;
    public static final int PE_EDIT_PRIN_BUTTON         = 1;
    public static final int PE_REMOVE_PRIN_BUTTON       = 2;

    public static final int PE_PRIN_LABEL               = 5;
    public static final int PE_PRIN_LIST                = 6;

    public static final int PE_PANEL1                   = 7;
    public static final int PE_ADD_PERM_BUTTON          = 0;
    public static final int PE_EDIT_PERM_BUTTON         = 1;
    public static final int PE_REMOVE_PERM_BUTTON       = 2;

    public static final int PE_PERM_LIST                = 8;

    public static final int PE_PANEL2                   = 9;
    public static final int PE_CANCEL_BUTTON            = 1;
    public static final int PE_DONE_BUTTON              = 0;

    /* the gridbag index for components in the Principal Dialog (PRD) */
    public static final int PRD_DESC_LABEL              = 0;
    public static final int PRD_PRIN_CHOICE             = 1;
    public static final int PRD_PRIN_TEXTFIELD          = 2;
    public static final int PRD_NAME_LABEL              = 3;
    public static final int PRD_NAME_TEXTFIELD          = 4;
    public static final int PRD_CANCEL_BUTTON           = 6;
    public static final int PRD_OK_BUTTON               = 5;

    /* the gridbag index for components in the Permission Dialog (PD) */
    public static final int PD_DESC_LABEL               = 0;
    public static final int PD_PERM_CHOICE              = 1;
    public static final int PD_PERM_TEXTFIELD           = 2;
    public static final int PD_NAME_CHOICE              = 3;
    public static final int PD_NAME_TEXTFIELD           = 4;
    public static final int PD_ACTIONS_CHOICE           = 5;
    public static final int PD_ACTIONS_TEXTFIELD        = 6;
    public static final int PD_SIGNEDBY_LABEL           = 7;
    public static final int PD_SIGNEDBY_TEXTFIELD       = 8;
    public static final int PD_CANCEL_BUTTON            = 10;
    public static final int PD_OK_BUTTON                = 9;

    /* modes for KeyStore */
    public static final int EDIT_KEYSTORE               = 0;

    /* the gridbag index for components in the Change KeyStore Dialog (KSD) */
    public static final int KSD_NAME_LABEL              = 0;
    public static final int KSD_NAME_TEXTFIELD          = 1;
    public static final int KSD_TYPE_LABEL              = 2;
    public static final int KSD_TYPE_TEXTFIELD          = 3;
    public static final int KSD_PROVIDER_LABEL          = 4;
    public static final int KSD_PROVIDER_TEXTFIELD      = 5;
    public static final int KSD_PWD_URL_LABEL           = 6;
    public static final int KSD_PWD_URL_TEXTFIELD       = 7;
    public static final int KSD_CANCEL_BUTTON           = 9;
    public static final int KSD_OK_BUTTON               = 8;

    /* the gridbag index for components in the User Save Changes Dialog (USC) */
    public static final int USC_LABEL                   = 0;
    public static final int USC_PANEL                   = 1;
    public static final int USC_YES_BUTTON              = 0;
    public static final int USC_NO_BUTTON               = 1;
    public static final int USC_CANCEL_BUTTON           = 2;

    /* gridbag index for the ConfirmRemovePolicyEntryDialog (CRPE) */
    public static final int CRPE_LABEL1                 = 0;
    public static final int CRPE_LABEL2                 = 1;
    public static final int CRPE_PANEL                  = 2;
    public static final int CRPE_PANEL_OK               = 0;
    public static final int CRPE_PANEL_CANCEL           = 1;

    /* some private static finals */
    private static final int PERMISSION                 = 0;
    private static final int PERMISSION_NAME            = 1;
    private static final int PERMISSION_ACTIONS         = 2;
    private static final int PERMISSION_SIGNEDBY        = 3;
    private static final int PRINCIPAL_TYPE             = 4;
    private static final int PRINCIPAL_NAME             = 5;

    public static java.util.ArrayList<Perm> PERM_ARRAY;
    public static java.util.ArrayList<Prin> PRIN_ARRAY;
    PolicyTool tool;
    ToolWindow tw;

    static {

        // set up permission objects

        PERM_ARRAY = new java.util.ArrayList<Perm>();
        PERM_ARRAY.add(new AllPerm());
        PERM_ARRAY.add(new AudioPerm());
        PERM_ARRAY.add(new AuthPerm());
        PERM_ARRAY.add(new AWTPerm());
        PERM_ARRAY.add(new DelegationPerm());
        PERM_ARRAY.add(new FilePerm());
1451
        PERM_ARRAY.add(new InqSecContextPerm());
D
duke 已提交
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
        PERM_ARRAY.add(new LogPerm());
        PERM_ARRAY.add(new MgmtPerm());
        PERM_ARRAY.add(new MBeanPerm());
        PERM_ARRAY.add(new MBeanSvrPerm());
        PERM_ARRAY.add(new MBeanTrustPerm());
        PERM_ARRAY.add(new NetPerm());
        PERM_ARRAY.add(new PrivCredPerm());
        PERM_ARRAY.add(new PropPerm());
        PERM_ARRAY.add(new ReflectPerm());
        PERM_ARRAY.add(new RuntimePerm());
        PERM_ARRAY.add(new SecurityPerm());
        PERM_ARRAY.add(new SerialPerm());
        PERM_ARRAY.add(new ServicePerm());
        PERM_ARRAY.add(new SocketPerm());
        PERM_ARRAY.add(new SQLPerm());
        PERM_ARRAY.add(new SSLPerm());
        PERM_ARRAY.add(new SubjDelegPerm());

        // set up principal objects

        PRIN_ARRAY = new java.util.ArrayList<Prin>();
        PRIN_ARRAY.add(new KrbPrin());
        PRIN_ARRAY.add(new X500Prin());
    }

    ToolDialog(String title, PolicyTool tool, ToolWindow tw, boolean modal) {
        super(tw, modal);
        setTitle(title);
        this.tool = tool;
        this.tw = tw;
        addWindowListener(new ChildWindowListener(this));
    }

    /**
     * get the Perm instance based on either the (shortened) class name
     * or the fully qualified class name
     */
    static Perm getPerm(String clazz, boolean fullClassName) {
        for (int i = 0; i < PERM_ARRAY.size(); i++) {
            Perm next = PERM_ARRAY.get(i);
            if (fullClassName) {
                if (next.FULL_CLASS.equals(clazz)) {
                    return next;
                }
            } else {
                if (next.CLASS.equals(clazz)) {
                    return next;
                }
            }
        }
        return null;
    }

    /**
     * get the Prin instance based on either the (shortened) class name
     * or the fully qualified class name
     */
    static Prin getPrin(String clazz, boolean fullClassName) {
        for (int i = 0; i < PRIN_ARRAY.size(); i++) {
            Prin next = PRIN_ARRAY.get(i);
            if (fullClassName) {
                if (next.FULL_CLASS.equals(clazz)) {
                    return next;
                }
            } else {
                if (next.CLASS.equals(clazz)) {
                    return next;
                }
            }
        }
        return null;
    }

    /**
     * ask user if they want to overwrite an existing file
     */
    void displayOverWriteFileDialog(String filename, int nextEvent) {

        // find where the PolicyTool gui is
        Point location = tw.getLocationOnScreen();
        setBounds(location.x + 75, location.y + 100, 400, 150);
        setLayout(new GridBagLayout());

        // ask the user if they want to over write the existing file
        MessageFormat form = new MessageFormat(PolicyTool.rb.getString
1537
                ("OK.to.overwrite.existing.file.filename."));
D
duke 已提交
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
        Object[] source = {filename};
        Label label = new Label(form.format(source));
        tw.addNewComponent(this, label, OW_LABEL,
                           0, 0, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.TOP_PADDING);

        // OK button
        Button button = new Button(PolicyTool.rb.getString("OK"));
        button.addActionListener(new OverWriteFileOKButtonListener
                (tool, tw, this, filename, nextEvent));
        tw.addNewComponent(this, button, OW_OK_BUTTON,
                           0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                           tw.TOP_PADDING);

        // Cancel button
        // -- if the user hits cancel, do NOT go on to the next event
        button = new Button(PolicyTool.rb.getString("Cancel"));
        button.addActionListener(new CancelButtonListener(this));
        tw.addNewComponent(this, button, OW_CANCEL_BUTTON,
                           1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                           tw.TOP_PADDING);

        setVisible(true);
    }

    /**
     * pop up a dialog so the user can enter info to add a new PolicyEntry
     * - if edit is TRUE, then the user is editing an existing entry
     *   and we should display the original info as well.
     *
     * - the other reason we need the 'edit' boolean is we need to know
     *   when we are adding a NEW policy entry.  in this case, we can
     *   not simply update the existing entry, because it doesn't exist.
     *   we ONLY update the GUI listing/info, and then when the user
     *   finally clicks 'OK' or 'DONE', then we can collect that info
     *   and add it to the policy.
     */
    void displayPolicyEntryDialog(boolean edit) {

        int listIndex = 0;
        PolicyEntry entries[] = null;
        TaggedList prinList = new TaggedList(3, false);
        prinList.getAccessibleContext().setAccessibleName(
1581
                PolicyTool.rb.getString("Principal.List"));
D
duke 已提交
1582 1583 1584 1585
        prinList.addActionListener
                (new EditPrinButtonListener(tool, tw, this, edit));
        TaggedList permList = new TaggedList(10, false);
        permList.getAccessibleContext().setAccessibleName(
1586
                PolicyTool.rb.getString("Permission.List"));
D
duke 已提交
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
        permList.addActionListener
                (new EditPermButtonListener(tool, tw, this, edit));

        // find where the PolicyTool gui is
        Point location = tw.getLocationOnScreen();
        setBounds(location.x + 75, location.y + 200, 650, 500);
        setLayout(new GridBagLayout());
        setResizable(true);

        if (edit) {
            // get the selected item
            entries = tool.getEntry();
            List policyList = (List)tw.getComponent(tw.MW_POLICY_LIST);
            listIndex = policyList.getSelectedIndex();

            // get principal list
            LinkedList principals =
                entries[listIndex].getGrantEntry().principals;
            for (int i = 0; i < principals.size(); i++) {
                String prinString = null;
                PolicyParser.PrincipalEntry nextPrin =
                        (PolicyParser.PrincipalEntry)principals.get(i);
                prinList.addTaggedItem(PrincipalEntryToUserFriendlyString(nextPrin), nextPrin);
            }

            // get permission list
            Vector<PolicyParser.PermissionEntry> permissions =
                entries[listIndex].getGrantEntry().permissionEntries;
            for (int i = 0; i < permissions.size(); i++) {
                String permString = null;
                PolicyParser.PermissionEntry nextPerm =
                                                permissions.elementAt(i);
                permList.addTaggedItem(ToolDialog.PermissionEntryToUserFriendlyString(nextPerm), nextPerm);
            }
        }

        // codebase label and textfield
1624
        Label label = new Label(PolicyTool.rb.getString("CodeBase."));
D
duke 已提交
1625 1626 1627 1628 1629 1630 1631
        tw.addNewComponent(this, label, PE_CODEBASE_LABEL,
                0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
        TextField tf;
        tf = (edit ?
                new TextField(entries[listIndex].getGrantEntry().codeBase, 60) :
                new TextField(60));
        tf.getAccessibleContext().setAccessibleName(
1632
                PolicyTool.rb.getString("Code.Base"));
D
duke 已提交
1633 1634 1635 1636
        tw.addNewComponent(this, tf, PE_CODEBASE_TEXTFIELD,
                1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);

        // signedby label and textfield
1637
        label = new Label(PolicyTool.rb.getString("SignedBy."));
D
duke 已提交
1638 1639 1640 1641 1642 1643
        tw.addNewComponent(this, label, PE_SIGNEDBY_LABEL,
                           0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);
        tf = (edit ?
                new TextField(entries[listIndex].getGrantEntry().signedBy, 60) :
                new TextField(60));
        tf.getAccessibleContext().setAccessibleName(
1644
                PolicyTool.rb.getString("Signed.By."));
D
duke 已提交
1645 1646 1647 1648 1649 1650 1651
        tw.addNewComponent(this, tf, PE_SIGNEDBY_TEXTFIELD,
                           1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);

        // panel for principal buttons
        Panel panel = new Panel();
        panel.setLayout(new GridBagLayout());

1652
        Button button = new Button(PolicyTool.rb.getString("Add.Principal"));
D
duke 已提交
1653 1654 1655 1656 1657
        button.addActionListener
                (new AddPrinButtonListener(tool, tw, this, edit));
        tw.addNewComponent(panel, button, PE_ADD_PRIN_BUTTON,
                0, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);

1658
        button = new Button(PolicyTool.rb.getString("Edit.Principal"));
D
duke 已提交
1659 1660 1661 1662 1663
        button.addActionListener(new EditPrinButtonListener
                                                (tool, tw, this, edit));
        tw.addNewComponent(panel, button, PE_EDIT_PRIN_BUTTON,
                1, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);

1664
        button = new Button(PolicyTool.rb.getString("Remove.Principal"));
D
duke 已提交
1665 1666 1667 1668 1669 1670 1671 1672 1673
        button.addActionListener(new RemovePrinButtonListener
                                        (tool, tw, this, edit));
        tw.addNewComponent(panel, button, PE_REMOVE_PRIN_BUTTON,
                2, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);

        tw.addNewComponent(this, panel, PE_PANEL0,
                1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.HORIZONTAL);

        // principal label and list
1674
        label = new Label(PolicyTool.rb.getString("Principals."));
D
duke 已提交
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
        tw.addNewComponent(this, label, PE_PRIN_LABEL,
                           0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.BOTTOM_PADDING);
        tw.addNewComponent(this, prinList, PE_PRIN_LIST,
                           1, 3, 3, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.BOTTOM_PADDING);

        // panel for permission buttons
        panel = new Panel();
        panel.setLayout(new GridBagLayout());

1686
        button = new Button(PolicyTool.rb.getString(".Add.Permission"));
D
duke 已提交
1687 1688 1689 1690 1691
        button.addActionListener(new AddPermButtonListener
                                                (tool, tw, this, edit));
        tw.addNewComponent(panel, button, PE_ADD_PERM_BUTTON,
                0, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);

1692
        button = new Button(PolicyTool.rb.getString(".Edit.Permission"));
D
duke 已提交
1693 1694 1695 1696 1697 1698
        button.addActionListener(new EditPermButtonListener
                                                (tool, tw, this, edit));
        tw.addNewComponent(panel, button, PE_EDIT_PERM_BUTTON,
                1, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);


1699
        button = new Button(PolicyTool.rb.getString("Remove.Permission"));
D
duke 已提交
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
        button.addActionListener(new RemovePermButtonListener
                                        (tool, tw, this, edit));
        tw.addNewComponent(panel, button, PE_REMOVE_PERM_BUTTON,
                2, 0, 1, 1, 100.0, 0.0, GridBagConstraints.HORIZONTAL);

        tw.addNewComponent(this, panel, PE_PANEL1,
                0, 4, 2, 1, 0.0, 0.0, GridBagConstraints.HORIZONTAL,
                tw.LITE_BOTTOM_PADDING);

        // permission list
        tw.addNewComponent(this, permList, PE_PERM_LIST,
                           0, 5, 3, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.BOTTOM_PADDING);


        // panel for Done and Cancel buttons
        panel = new Panel();
        panel.setLayout(new GridBagLayout());

        // Done Button
        button = new Button(PolicyTool.rb.getString("Done"));
        button.addActionListener
                (new AddEntryDoneButtonListener(tool, tw, this, edit));
        tw.addNewComponent(panel, button, PE_DONE_BUTTON,
                           0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                           tw.LR_PADDING);

        // Cancel Button
        button = new Button(PolicyTool.rb.getString("Cancel"));
        button.addActionListener(new CancelButtonListener(this));
        tw.addNewComponent(panel, button, PE_CANCEL_BUTTON,
                           1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                           tw.LR_PADDING);

        // add the panel
        tw.addNewComponent(this, panel, PE_PANEL2,
                0, 6, 2, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);

        setVisible(true);
    }

    /**
     * Read all the Policy information data in the dialog box
     * and construct a PolicyEntry object with it.
     */
    PolicyEntry getPolicyEntryFromDialog()
        throws InvalidParameterException, MalformedURLException,
        NoSuchMethodException, ClassNotFoundException, InstantiationException,
        IllegalAccessException, InvocationTargetException,
        CertificateException, IOException, Exception {

        // get the Codebase
        TextField tf = (TextField)getComponent(PE_CODEBASE_TEXTFIELD);
        String codebase = null;
        if (tf.getText().trim().equals("") == false)
                codebase = new String(tf.getText().trim());

        // get the SignedBy
        tf = (TextField)getComponent(PE_SIGNEDBY_TEXTFIELD);
        String signedby = null;
        if (tf.getText().trim().equals("") == false)
                signedby = new String(tf.getText().trim());

        // construct a new GrantEntry
        PolicyParser.GrantEntry ge =
                        new PolicyParser.GrantEntry(signedby, codebase);

        // get the new Principals
        LinkedList<PolicyParser.PrincipalEntry> prins =
                                new LinkedList<PolicyParser.PrincipalEntry>();
        TaggedList prinList = (TaggedList)getComponent(PE_PRIN_LIST);
        for (int i = 0; i < prinList.getItemCount(); i++) {
            prins.add((PolicyParser.PrincipalEntry)prinList.getObject(i));
        }
        ge.principals = prins;

        // get the new Permissions
        Vector<PolicyParser.PermissionEntry> perms =
                        new Vector<PolicyParser.PermissionEntry>();
        TaggedList permList = (TaggedList)getComponent(PE_PERM_LIST);
        for (int i = 0; i < permList.getItemCount(); i++) {
            perms.addElement((PolicyParser.PermissionEntry)permList.getObject(i));
        }
        ge.permissionEntries = perms;

        // construct a new PolicyEntry object
        PolicyEntry entry = new PolicyEntry(tool, ge);

        return entry;
    }

    /**
     * display a dialog box for the user to enter KeyStore information
     */
    void keyStoreDialog(int mode) {

        // find where the PolicyTool gui is
        Point location = tw.getLocationOnScreen();
        setBounds(location.x + 25, location.y + 100, 500, 300);
        setLayout(new GridBagLayout());

        if (mode == EDIT_KEYSTORE) {

            // KeyStore label and textfield
            Label label = new Label
1805
                        (PolicyTool.rb.getString("KeyStore.URL."));
D
duke 已提交
1806 1807 1808 1809 1810 1811 1812
            tw.addNewComponent(this, label, KSD_NAME_LABEL,
                               0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                               tw.BOTTOM_PADDING);
            TextField tf = new TextField(tool.getKeyStoreName(), 30);

            // URL to U R L, so that accessibility reader will pronounce well
            tf.getAccessibleContext().setAccessibleName(
1813
                PolicyTool.rb.getString("KeyStore.U.R.L."));
D
duke 已提交
1814 1815 1816 1817 1818
            tw.addNewComponent(this, tf, KSD_NAME_TEXTFIELD,
                               1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                               tw.BOTTOM_PADDING);

            // KeyStore type and textfield
1819
            label = new Label(PolicyTool.rb.getString("KeyStore.Type."));
D
duke 已提交
1820 1821 1822 1823 1824
            tw.addNewComponent(this, label, KSD_TYPE_LABEL,
                               0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                               tw.BOTTOM_PADDING);
            tf = new TextField(tool.getKeyStoreType(), 30);
            tf.getAccessibleContext().setAccessibleName(
1825
                PolicyTool.rb.getString("KeyStore.Type."));
D
duke 已提交
1826 1827 1828 1829 1830 1831
            tw.addNewComponent(this, tf, KSD_TYPE_TEXTFIELD,
                               1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                               tw.BOTTOM_PADDING);

            // KeyStore provider and textfield
            label = new Label(PolicyTool.rb.getString
1832
                                ("KeyStore.Provider."));
D
duke 已提交
1833 1834 1835 1836 1837
            tw.addNewComponent(this, label, KSD_PROVIDER_LABEL,
                               0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                               tw.BOTTOM_PADDING);
            tf = new TextField(tool.getKeyStoreProvider(), 30);
            tf.getAccessibleContext().setAccessibleName(
1838
                PolicyTool.rb.getString("KeyStore.Provider."));
D
duke 已提交
1839 1840 1841 1842 1843 1844
            tw.addNewComponent(this, tf, KSD_PROVIDER_TEXTFIELD,
                               1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                               tw.BOTTOM_PADDING);

            // KeyStore password URL and textfield
            label = new Label(PolicyTool.rb.getString
1845
                                ("KeyStore.Password.URL."));
D
duke 已提交
1846 1847 1848 1849 1850
            tw.addNewComponent(this, label, KSD_PWD_URL_LABEL,
                               0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                               tw.BOTTOM_PADDING);
            tf = new TextField(tool.getKeyStorePwdURL(), 30);
            tf.getAccessibleContext().setAccessibleName(
1851
                PolicyTool.rb.getString("KeyStore.Password.U.R.L."));
D
duke 已提交
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
            tw.addNewComponent(this, tf, KSD_PWD_URL_TEXTFIELD,
                               1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                               tw.BOTTOM_PADDING);

            // OK button
            Button okButton = new Button(PolicyTool.rb.getString("OK"));
            okButton.addActionListener
                        (new ChangeKeyStoreOKButtonListener(tool, tw, this));
            tw.addNewComponent(this, okButton, KSD_OK_BUTTON,
                        0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);

            // cancel button
            Button cancelButton = new Button(PolicyTool.rb.getString("Cancel"));
            cancelButton.addActionListener(new CancelButtonListener(this));
            tw.addNewComponent(this, cancelButton, KSD_CANCEL_BUTTON,
                        1, 4, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL);

        }
        setVisible(true);
    }

    /**
     * display a dialog box for the user to input Principal info
     *
     * if editPolicyEntry is false, then we are adding Principals to
     * a new PolicyEntry, and we only update the GUI listing
     * with the new Principal.
     *
     * if edit is true, then we are editing an existing Policy entry.
     */
    void displayPrincipalDialog(boolean editPolicyEntry, boolean edit) {

        PolicyParser.PrincipalEntry editMe = null;

        // get the Principal selected from the Principal List
        TaggedList prinList = (TaggedList)getComponent(PE_PRIN_LIST);
        int prinIndex = prinList.getSelectedIndex();

        if (edit) {
            editMe = (PolicyParser.PrincipalEntry)prinList.getObject(prinIndex);
        }

        ToolDialog newTD = new ToolDialog
                (PolicyTool.rb.getString("Principals"), tool, tw, true);
        newTD.addWindowListener(new ChildWindowListener(newTD));

        // find where the PolicyTool gui is
        Point location = getLocationOnScreen();
        newTD.setBounds(location.x + 50, location.y + 100, 650, 190);
        newTD.setLayout(new GridBagLayout());
        newTD.setResizable(true);

        // description label
        Label label = (edit ?
1906 1907
                new Label(PolicyTool.rb.getString(".Edit.Principal.")) :
                new Label(PolicyTool.rb.getString(".Add.New.Principal.")));
D
duke 已提交
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
        tw.addNewComponent(newTD, label, PRD_DESC_LABEL,
                           0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.TOP_BOTTOM_PADDING);

        // principal choice
        Choice choice = new Choice();
        choice.add(PRIN_TYPE);
        choice.getAccessibleContext().setAccessibleName(PRIN_TYPE);
        for (int i = 0; i < PRIN_ARRAY.size(); i++) {
            Prin next = PRIN_ARRAY.get(i);
            choice.add(next.CLASS);
        }

        choice.addItemListener(new PrincipalTypeMenuListener(newTD));
        if (edit) {
            if (PolicyParser.PrincipalEntry.WILDCARD_CLASS.equals
                                (editMe.getPrincipalClass())) {
                choice.select(PRIN_TYPE);
            } else {
                Prin inputPrin = getPrin(editMe.getPrincipalClass(), true);
                if (inputPrin != null) {
                    choice.select(inputPrin.CLASS);
                }
            }
        }

        tw.addNewComponent(newTD, choice, PRD_PRIN_CHOICE,
                           0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);

        // principal textfield
        TextField tf;
        tf = (edit ?
                new TextField(editMe.getDisplayClass(), 30) :
                new TextField(30));
        tf.getAccessibleContext().setAccessibleName(PRIN_TYPE);
        tw.addNewComponent(newTD, tf, PRD_PRIN_TEXTFIELD,
                           1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);

        // name label and textfield
        label = new Label(PRIN_NAME);
        tf = (edit ?
                new TextField(editMe.getDisplayName(), 40) :
                new TextField(40));
        tf.getAccessibleContext().setAccessibleName(PRIN_NAME);

        tw.addNewComponent(newTD, label, PRD_NAME_LABEL,
                           0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);
        tw.addNewComponent(newTD, tf, PRD_NAME_TEXTFIELD,
                           1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);

        // OK button
        Button okButton = new Button(PolicyTool.rb.getString("OK"));
        okButton.addActionListener(
            new NewPolicyPrinOKButtonListener
                                        (tool, tw, this, newTD, edit));
        tw.addNewComponent(newTD, okButton, PRD_OK_BUTTON,
                           0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                           tw.TOP_BOTTOM_PADDING);
        // cancel button
        Button cancelButton = new Button(PolicyTool.rb.getString("Cancel"));
        cancelButton.addActionListener(new CancelButtonListener(newTD));
        tw.addNewComponent(newTD, cancelButton, PRD_CANCEL_BUTTON,
                           1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                           tw.TOP_BOTTOM_PADDING);

        newTD.setVisible(true);
    }

    /**
     * display a dialog box for the user to input Permission info
     *
     * if editPolicyEntry is false, then we are adding Permissions to
     * a new PolicyEntry, and we only update the GUI listing
     * with the new Permission.
     *
     * if edit is true, then we are editing an existing Permission entry.
     */
    void displayPermissionDialog(boolean editPolicyEntry, boolean edit) {

        PolicyParser.PermissionEntry editMe = null;

        // get the Permission selected from the Permission List
        TaggedList permList = (TaggedList)getComponent(PE_PERM_LIST);
        int permIndex = permList.getSelectedIndex();

        if (edit) {
            editMe = (PolicyParser.PermissionEntry)permList.getObject(permIndex);
        }

        ToolDialog newTD = new ToolDialog
                (PolicyTool.rb.getString("Permissions"), tool, tw, true);
        newTD.addWindowListener(new ChildWindowListener(newTD));

        // find where the PolicyTool gui is
        Point location = getLocationOnScreen();
        newTD.setBounds(location.x + 50, location.y + 100, 700, 250);
        newTD.setLayout(new GridBagLayout());
        newTD.setResizable(true);

        // description label
        Label label = (edit ?
2013 2014
                new Label(PolicyTool.rb.getString(".Edit.Permission.")) :
                new Label(PolicyTool.rb.getString(".Add.New.Permission.")));
D
duke 已提交
2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080
        tw.addNewComponent(newTD, label, PD_DESC_LABEL,
                           0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.TOP_BOTTOM_PADDING);

        // permission choice (added in alphabetical order)
        Choice choice = new Choice();
        choice.add(PERM);
        choice.getAccessibleContext().setAccessibleName(PERM);
        for (int i = 0; i < PERM_ARRAY.size(); i++) {
            Perm next = PERM_ARRAY.get(i);
            choice.add(next.CLASS);
        }
        choice.addItemListener(new PermissionMenuListener(newTD));
        tw.addNewComponent(newTD, choice, PD_PERM_CHOICE,
                           0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);

        // permission textfield
        TextField tf;
        tf = (edit ? new TextField(editMe.permission, 30) : new TextField(30));
        tf.getAccessibleContext().setAccessibleName(PERM);
        if (edit) {
            Perm inputPerm = getPerm(editMe.permission, true);
            if (inputPerm != null) {
                choice.select(inputPerm.CLASS);
            }
        }
        tw.addNewComponent(newTD, tf, PD_PERM_TEXTFIELD,
                           1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);

        // name label and textfield
        choice = new Choice();
        choice.add(PERM_NAME);
        choice.getAccessibleContext().setAccessibleName(PERM_NAME);
        choice.addItemListener(new PermissionNameMenuListener(newTD));
        tf = (edit ? new TextField(editMe.name, 40) : new TextField(40));
        tf.getAccessibleContext().setAccessibleName(PERM_NAME);
        if (edit) {
            setPermissionNames(getPerm(editMe.permission, true), choice, tf);
        }
        tw.addNewComponent(newTD, choice, PD_NAME_CHOICE,
                           0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);
        tw.addNewComponent(newTD, tf, PD_NAME_TEXTFIELD,
                           1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);

        // actions label and textfield
        choice = new Choice();
        choice.add(PERM_ACTIONS);
        choice.getAccessibleContext().setAccessibleName(PERM_ACTIONS);
        choice.addItemListener(new PermissionActionsMenuListener(newTD));
        tf = (edit ? new TextField(editMe.action, 40) : new TextField(40));
        tf.getAccessibleContext().setAccessibleName(PERM_ACTIONS);
        if (edit) {
            setPermissionActions(getPerm(editMe.permission, true), choice, tf);
        }
        tw.addNewComponent(newTD, choice, PD_ACTIONS_CHOICE,
                           0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);
        tw.addNewComponent(newTD, tf, PD_ACTIONS_TEXTFIELD,
                           1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);

        // signedby label and textfield
2081
        label = new Label(PolicyTool.rb.getString("Signed.By."));
D
duke 已提交
2082 2083 2084 2085 2086
        tw.addNewComponent(newTD, label, PD_SIGNEDBY_LABEL,
                           0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);
        tf = (edit ? new TextField(editMe.signedBy, 40) : new TextField(40));
        tf.getAccessibleContext().setAccessibleName(
2087
                PolicyTool.rb.getString("Signed.By."));
D
duke 已提交
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
        tw.addNewComponent(newTD, tf, PD_SIGNEDBY_TEXTFIELD,
                           1, 4, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.LR_PADDING);

        // OK button
        Button okButton = new Button(PolicyTool.rb.getString("OK"));
        okButton.addActionListener(
            new NewPolicyPermOKButtonListener
                                    (tool, tw, this, newTD, edit));
        tw.addNewComponent(newTD, okButton, PD_OK_BUTTON,
                           0, 5, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                           tw.TOP_BOTTOM_PADDING);

        // cancel button
        Button cancelButton = new Button(PolicyTool.rb.getString("Cancel"));
        cancelButton.addActionListener(new CancelButtonListener(newTD));
        tw.addNewComponent(newTD, cancelButton, PD_CANCEL_BUTTON,
                           1, 5, 1, 1, 0.0, 0.0, GridBagConstraints.VERTICAL,
                           tw.TOP_BOTTOM_PADDING);

        newTD.setVisible(true);
    }

    /**
     * construct a Principal object from the Principal Info Dialog Box
     */
    PolicyParser.PrincipalEntry getPrinFromDialog() throws Exception {

        TextField tf = (TextField)getComponent(PRD_PRIN_TEXTFIELD);
        String pclass = new String(tf.getText().trim());
        tf = (TextField)getComponent(PRD_NAME_TEXTFIELD);
        String pname = new String(tf.getText().trim());
        if (pclass.equals("*")) {
            pclass = PolicyParser.PrincipalEntry.WILDCARD_CLASS;
        }
        if (pname.equals("*")) {
            pname = PolicyParser.PrincipalEntry.WILDCARD_NAME;
        }

        PolicyParser.PrincipalEntry pppe = null;

        if ((pclass.equals(PolicyParser.PrincipalEntry.WILDCARD_CLASS)) &&
            (!pname.equals(PolicyParser.PrincipalEntry.WILDCARD_NAME))) {
            throw new Exception
2132
                        (PolicyTool.rb.getString("Cannot.Specify.Principal.with.a.Wildcard.Class.without.a.Wildcard.Name"));
D
duke 已提交
2133 2134
        } else if (pname.equals("")) {
            throw new Exception
2135
                        (PolicyTool.rb.getString("Cannot.Specify.Principal.without.a.Name"));
D
duke 已提交
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
        } else if (pclass.equals("")) {
            // make this consistent with what PolicyParser does
            // when it sees an empty principal class
            pclass = PolicyParser.REPLACE_NAME;
            tool.warnings.addElement(
                        "Warning: Principal name '" + pname +
                                "' specified without a Principal class.\n" +
                        "\t'" + pname + "' will be interpreted " +
                                "as a key store alias.\n" +
                        "\tThe final principal class will be " +
                                ToolDialog.X500_PRIN_CLASS + ".\n" +
                        "\tThe final principal name will be " +
                                "determined by the following:\n" +
                        "\n" +
                        "\tIf the key store entry identified by '"
                                + pname + "'\n" +
                        "\tis a key entry, then the principal name will be\n" +
                        "\tthe subject distinguished name from the first\n" +
                        "\tcertificate in the entry's certificate chain.\n" +
                        "\n" +
                        "\tIf the key store entry identified by '" +
                                pname + "'\n" +
                        "\tis a trusted certificate entry, then the\n" +
                        "\tprincipal name will be the subject distinguished\n" +
                        "\tname from the trusted public key certificate.");
            tw.displayStatusDialog(this,
                        "'" + pname + "' will be interpreted as a key " +
                        "store alias.  View Warning Log for details.");
        }
        return new PolicyParser.PrincipalEntry(pclass, pname);
    }


    /**
     * construct a Permission object from the Permission Info Dialog Box
     */
    PolicyParser.PermissionEntry getPermFromDialog() {

        TextField tf = (TextField)getComponent(PD_PERM_TEXTFIELD);
        String permission = new String(tf.getText().trim());
        tf = (TextField)getComponent(PD_NAME_TEXTFIELD);
        String name = null;
        if (tf.getText().trim().equals("") == false)
            name = new String(tf.getText().trim());
        if (permission.equals("") ||
            (!permission.equals(ALL_PERM_CLASS) && name == null)) {
            throw new InvalidParameterException(PolicyTool.rb.getString
2183
                ("Permission.and.Target.Name.must.have.a.value"));
D
duke 已提交
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
        }

        // When the permission is FilePermission, we need to check the name
        // to make sure it's not escaped. We believe --
        //
        // String             name.lastIndexOf("\\\\")
        // ----------------   ------------------------
        // c:\foo\bar         -1, legal
        // c:\\foo\\bar       2, illegal
        // \\server\share     0, legal
        // \\\\server\share   2, illegal

        if (permission.equals(FILE_PERM_CLASS) && name.lastIndexOf("\\\\") > 0) {
            char result = tw.displayYesNoDialog(this,
                    PolicyTool.rb.getString("Warning"),
                    PolicyTool.rb.getString(
2200
                        "Warning.File.name.may.include.escaped.backslash.characters.It.is.not.necessary.to.escape.backslash.characters.the.tool.escapes"),
D
duke 已提交
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
                    PolicyTool.rb.getString("Retain"),
                    PolicyTool.rb.getString("Edit")
                    );
            if (result != 'Y') {
                // an invisible exception
                throw new NoDisplayException();
            }
        }
        // get the Actions
        tf = (TextField)getComponent(PD_ACTIONS_TEXTFIELD);
        String actions = null;
        if (tf.getText().trim().equals("") == false)
            actions = new String(tf.getText().trim());

        // get the Signed By
        tf = (TextField)getComponent(PD_SIGNEDBY_TEXTFIELD);
        String signedBy = null;
        if (tf.getText().trim().equals("") == false)
            signedBy = new String(tf.getText().trim());

        PolicyParser.PermissionEntry pppe = new PolicyParser.PermissionEntry
                                (permission, name, actions);
        pppe.signedBy = signedBy;

        // see if the signers have public keys
        if (signedBy != null) {
                String signers[] = tool.parseSigners(pppe.signedBy);
                for (int i = 0; i < signers.length; i++) {
                try {
                    PublicKey pubKey = tool.getPublicKeyAlias(signers[i]);
                    if (pubKey == null) {
                        MessageFormat form = new MessageFormat
                            (PolicyTool.rb.getString
2234
                            ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));
D
duke 已提交
2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
                        Object[] source = {signers[i]};
                        tool.warnings.addElement(form.format(source));
                        tw.displayStatusDialog(this, form.format(source));
                    }
                } catch (Exception e) {
                    tw.displayErrorDialog(this, e);
                }
            }
        }
        return pppe;
    }

    /**
     * confirm that the user REALLY wants to remove the Policy Entry
     */
    void displayConfirmRemovePolicyEntry() {

        // find the entry to be removed
        List list = (List)tw.getComponent(tw.MW_POLICY_LIST);
        int index = list.getSelectedIndex();
        PolicyEntry entries[] = tool.getEntry();

        // find where the PolicyTool gui is
        Point location = tw.getLocationOnScreen();
        setBounds(location.x + 25, location.y + 100, 600, 400);
        setLayout(new GridBagLayout());

        // ask the user do they really want to do this?
        Label label = new Label
2264
                (PolicyTool.rb.getString("Remove.this.Policy.Entry."));
D
duke 已提交
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
        tw.addNewComponent(this, label, CRPE_LABEL1,
                           0, 0, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                           tw.BOTTOM_PADDING);

        // display the policy entry
        label = new Label(entries[index].codebaseToString());
        tw.addNewComponent(this, label, CRPE_LABEL2,
                        0, 1, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH);
        label = new Label(entries[index].principalsToString().trim());
        tw.addNewComponent(this, label, CRPE_LABEL2+1,
                        0, 2, 2, 1, 0.0, 0.0, GridBagConstraints.BOTH);
        Vector<PolicyParser.PermissionEntry> perms =
                        entries[index].getGrantEntry().permissionEntries;
        for (int i = 0; i < perms.size(); i++) {
            PolicyParser.PermissionEntry nextPerm = perms.elementAt(i);
            String permString = ToolDialog.PermissionEntryToUserFriendlyString(nextPerm);
            label = new Label("    " + permString);
            if (i == (perms.size()-1)) {
                tw.addNewComponent(this, label, CRPE_LABEL2 + 2 + i,
                                 1, 3 + i, 1, 1, 0.0, 0.0,
                                 GridBagConstraints.BOTH, tw.BOTTOM_PADDING);
            } else {
                tw.addNewComponent(this, label, CRPE_LABEL2 + 2 + i,
                                 1, 3 + i, 1, 1, 0.0, 0.0,
                                 GridBagConstraints.BOTH);
            }
        }


        // add OK/CANCEL buttons in a new panel
        Panel panel = new Panel();
        panel.setLayout(new GridBagLayout());

        // OK button
        Button okButton = new Button(PolicyTool.rb.getString("OK"));
        okButton.addActionListener
                (new ConfirmRemovePolicyEntryOKButtonListener(tool, tw, this));
        tw.addNewComponent(panel, okButton, CRPE_PANEL_OK,
                           0, 0, 1, 1, 0.0, 0.0,
                           GridBagConstraints.VERTICAL, tw.LR_PADDING);

        // cancel button
        Button cancelButton = new Button(PolicyTool.rb.getString("Cancel"));
        cancelButton.addActionListener(new CancelButtonListener(this));
        tw.addNewComponent(panel, cancelButton, CRPE_PANEL_CANCEL,
                           1, 0, 1, 1, 0.0, 0.0,
                           GridBagConstraints.VERTICAL, tw.LR_PADDING);

        tw.addNewComponent(this, panel, CRPE_LABEL2 + 2 + perms.size(),
                           0, 3 + perms.size(), 2, 1, 0.0, 0.0,
                           GridBagConstraints.VERTICAL, tw.TOP_BOTTOM_PADDING);

        pack();
        setVisible(true);
    }

    /**
     * perform SAVE AS
     */
    void displaySaveAsDialog(int nextEvent) {

        // pop up a dialog box for the user to enter a filename.
        FileDialog fd = new FileDialog
2328
                (tw, PolicyTool.rb.getString("Save.As"), FileDialog.SAVE);
D
duke 已提交
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
        fd.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                e.getWindow().setVisible(false);
            }
        });
        fd.setVisible(true);

        // see if the user hit cancel
        if (fd.getFile() == null ||
            fd.getFile().equals(""))
            return;

        // get the entered filename
        String filename = new String(fd.getDirectory() + fd.getFile());
        fd.dispose();

        // see if the file already exists
        File saveAsFile = new File(filename);
        if (saveAsFile.exists()) {
            // display a dialog box for the user to enter policy info
            ToolDialog td = new ToolDialog
2350
                (PolicyTool.rb.getString("Overwrite.File"), tool, tw, true);
D
duke 已提交
2351 2352 2353 2354 2355 2356 2357 2358
            td.displayOverWriteFileDialog(filename, nextEvent);
        } else {
            try {
                // save the policy entries to a file
                tool.savePolicy(filename);

                // display status
                MessageFormat form = new MessageFormat(PolicyTool.rb.getString
2359
                        ("Policy.successfully.written.to.filename"));
D
duke 已提交
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
                Object[] source = {filename};
                tw.displayStatusDialog(null, form.format(source));

                // display the new policy filename
                TextField newFilename = (TextField)tw.getComponent
                                (tw.MW_FILENAME_TEXTFIELD);
                newFilename.setText(filename);
                tw.setVisible(true);

                // now continue with the originally requested command
                // (QUIT, NEW, or OPEN)
                userSaveContinue(tool, tw, this, nextEvent);

            } catch (FileNotFoundException fnfe) {
                if (filename == null || filename.equals("")) {
                    tw.displayErrorDialog(null, new FileNotFoundException
2376
                                (PolicyTool.rb.getString("null.filename")));
D
duke 已提交
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
                } else {
                    tw.displayErrorDialog(null, fnfe);
                }
            } catch (Exception ee) {
                tw.displayErrorDialog(null, ee);
            }
        }
    }

    /**
     * ask user if they want to save changes
     */
    void displayUserSave(int select) {

        if (tool.modified == true) {

            // find where the PolicyTool gui is
            Point location = tw.getLocationOnScreen();
            setBounds(location.x + 75, location.y + 100, 400, 150);
            setLayout(new GridBagLayout());

            Label label = new Label
2399
                (PolicyTool.rb.getString("Save.changes."));
D
duke 已提交
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
            tw.addNewComponent(this, label, USC_LABEL,
                               0, 0, 3, 1, 0.0, 0.0, GridBagConstraints.BOTH,
                               tw.L_TOP_BOTTOM_PADDING);

            Panel panel = new Panel();
            panel.setLayout(new GridBagLayout());

            Button yesButton = new Button(PolicyTool.rb.getString("Yes"));
            yesButton.addActionListener
                        (new UserSaveYesButtonListener(this, tool, tw, select));
            tw.addNewComponent(panel, yesButton, USC_YES_BUTTON,
                               0, 0, 1, 1, 0.0, 0.0,
                               GridBagConstraints.VERTICAL,
                               tw.LR_BOTTOM_PADDING);
            Button noButton = new Button(PolicyTool.rb.getString("No"));
            noButton.addActionListener
                        (new UserSaveNoButtonListener(this, tool, tw, select));
            tw.addNewComponent(panel, noButton, USC_NO_BUTTON,
                               1, 0, 1, 1, 0.0, 0.0,
                               GridBagConstraints.VERTICAL,
                               tw.LR_BOTTOM_PADDING);
            Button cancelButton = new Button(PolicyTool.rb.getString("Cancel"));
            cancelButton.addActionListener
                        (new UserSaveCancelButtonListener(this));
            tw.addNewComponent(panel, cancelButton, USC_CANCEL_BUTTON,
                               2, 0, 1, 1, 0.0, 0.0,
                               GridBagConstraints.VERTICAL,
                               tw.LR_BOTTOM_PADDING);

            tw.addNewComponent(this, panel, USC_PANEL,
                               0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.BOTH);

            pack();
            setVisible(true);
        } else {
            // just do the original request (QUIT, NEW, or OPEN)
            userSaveContinue(tool, tw, this, select);
        }
    }

    /**
     * when the user sees the 'YES', 'NO', 'CANCEL' buttons on the
     * displayUserSave dialog, and the click on one of them,
     * we need to continue the originally requested action
     * (either QUITting, opening NEW policy file, or OPENing an existing
     * policy file.  do that now.
     */
    void userSaveContinue(PolicyTool tool, ToolWindow tw,
                        ToolDialog us, int select) {

        // now either QUIT, open a NEW policy file, or OPEN an existing policy
        switch(select) {
        case ToolDialog.QUIT:

            tw.setVisible(false);
            tw.dispose();
            System.exit(0);

        case ToolDialog.NEW:

            try {
                tool.openPolicy(null);
            } catch (Exception ee) {
                tool.modified = false;
                tw.displayErrorDialog(null, ee);
            }

            // display the policy entries via the policy list textarea
            List list = new List(40, false);
            list.addActionListener(new PolicyListListener(tool, tw));
            tw.replacePolicyList(list);

            // display null policy filename and keystore
            TextField newFilename = (TextField)
                                tw.getComponent(tw.MW_FILENAME_TEXTFIELD);
            newFilename.setText("");
            tw.setVisible(true);
            break;

        case ToolDialog.OPEN:

            // pop up a dialog box for the user to enter a filename.
            FileDialog fd = new FileDialog
                (tw, PolicyTool.rb.getString("Open"), FileDialog.LOAD);
            fd.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    e.getWindow().setVisible(false);
                }
            });
            fd.setVisible(true);

            // see if the user hit 'cancel'
            if (fd.getFile() == null ||
                fd.getFile().equals(""))
                return;

            // get the entered filename
            String policyFile = new String(fd.getDirectory() + fd.getFile());

            try {
                // open the policy file
                tool.openPolicy(policyFile);

                // display the policy entries via the policy list textarea
                list = new List(40, false);
                list.addActionListener(new PolicyListListener(tool, tw));
                PolicyEntry entries[] = tool.getEntry();
                if (entries != null) {
                    for (int i = 0; i < entries.length; i++)
                        list.add(entries[i].headerToString());
                }
                tw.replacePolicyList(list);
                tool.modified = false;

                // display the new policy filename
                newFilename = (TextField)
                                tw.getComponent(tw.MW_FILENAME_TEXTFIELD);
                newFilename.setText(policyFile);
                tw.setVisible(true);

                // inform user of warnings
                if (tool.newWarning == true) {
                    tw.displayStatusDialog(null, PolicyTool.rb.getString
2523
                        ("Errors.have.occurred.while.opening.the.policy.configuration.View.the.Warning.Log.for.more.information."));
D
duke 已提交
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
                }

            } catch (Exception e) {
                // add blank policy listing
                list = new List(40, false);
                list.addActionListener(new PolicyListListener(tool, tw));
                tw.replacePolicyList(list);
                tool.setPolicyFileName(null);
                tool.modified = false;

                // display a null policy filename
                newFilename = (TextField)
                                tw.getComponent(tw.MW_FILENAME_TEXTFIELD);
                newFilename.setText("");
                tw.setVisible(true);

                // display the error
                MessageFormat form = new MessageFormat(PolicyTool.rb.getString
2542
                    ("Could.not.open.policy.file.policyFile.e.toString."));
D
duke 已提交
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
                Object[] source = {policyFile, e.toString()};
                tw.displayErrorDialog(null, form.format(source));
            }
            break;
        }
    }

    /**
     * Return a Menu list of names for a given permission
     *
     * If inputPerm's TARGETS are null, then this means TARGETS are
     * not allowed to be entered (and the TextField is set to be
     * non-editable).
     *
     * If TARGETS are valid but there are no standard ones
     * (user must enter them by hand) then the TARGETS array may be empty
     * (and of course non-null).
     */
    void setPermissionNames(Perm inputPerm, Choice names, TextField field) {
        names.removeAll();
        names.add(PERM_NAME);

        if (inputPerm == null) {
            // custom permission
            field.setEditable(true);
        } else if (inputPerm.TARGETS == null) {
            // standard permission with no targets
            field.setEditable(false);
        } else {
            // standard permission with standard targets
            field.setEditable(true);
            for (int i = 0; i < inputPerm.TARGETS.length; i++) {
                names.add(inputPerm.TARGETS[i]);
            }
        }
    }

    /**
     * Return a Menu list of actions for a given permission
     *
     * If inputPerm's ACTIONS are null, then this means ACTIONS are
     * not allowed to be entered (and the TextField is set to be
     * non-editable).  This is typically true for BasicPermissions.
     *
     * If ACTIONS are valid but there are no standard ones
     * (user must enter them by hand) then the ACTIONS array may be empty
     * (and of course non-null).
     */
    void setPermissionActions(Perm inputPerm, Choice actions, TextField field) {
        actions.removeAll();
        actions.add(PERM_ACTIONS);

        if (inputPerm == null) {
            // custom permission
            field.setEditable(true);
        } else if (inputPerm.ACTIONS == null) {
            // standard permission with no actions
            field.setEditable(false);
        } else {
            // standard permission with standard actions
            field.setEditable(true);
            for (int i = 0; i < inputPerm.ACTIONS.length; i++) {
                actions.add(inputPerm.ACTIONS[i]);
            }
        }
    }

    static String PermissionEntryToUserFriendlyString(PolicyParser.PermissionEntry pppe) {
        String result = pppe.permission;
        if (pppe.name != null) {
            result += " " + pppe.name;
        }
        if (pppe.action != null) {
            result += ", \"" + pppe.action + "\"";
        }
        if (pppe.signedBy != null) {
            result += ", signedBy " + pppe.signedBy;
        }
        return result;
    }

    static String PrincipalEntryToUserFriendlyString(PolicyParser.PrincipalEntry pppe) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pppe.write(pw);
        return sw.toString();
    }
}

/**
 * Event handler for the PolicyTool window
 */
class ToolWindowListener implements WindowListener {

    private ToolWindow tw;

    ToolWindowListener(ToolWindow tw) {
        this.tw = tw;
    }

    public void windowOpened(WindowEvent we) {
    }

    public void windowClosing(WindowEvent we) {

        // XXX
        // should we ask user if they want to save changes?
        // (we do if they choose the Menu->Exit)
        // seems that if they kill the application by hand,
        // we don't have to ask.

        tw.setVisible(false);
        tw.dispose();
        System.exit(0);
    }

    public void windowClosed(WindowEvent we) {
        System.exit(0);
    }

    public void windowIconified(WindowEvent we) {
    }

    public void windowDeiconified(WindowEvent we) {
    }

    public void windowActivated(WindowEvent we) {
    }

    public void windowDeactivated(WindowEvent we) {
    }
}

/**
 * Event handler for the Policy List
 */
class PolicyListListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;

    PolicyListListener(PolicyTool tool, ToolWindow tw) {
        this.tool = tool;
        this.tw = tw;

    }

    public void actionPerformed(ActionEvent e) {

        // display the permission list for a policy entry
        ToolDialog td = new ToolDialog
2694
                (PolicyTool.rb.getString("Policy.Entry"), tool, tw, true);
D
duke 已提交
2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717
        td.displayPolicyEntryDialog(true);
    }
}

/**
 * Event handler for the File Menu
 */
class FileMenuListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;

    FileMenuListener(PolicyTool tool, ToolWindow tw) {
        this.tool = tool;
        this.tw = tw;
    }

    public void actionPerformed(ActionEvent e) {

        if (PolicyTool.collator.compare(e.getActionCommand(), tw.QUIT) == 0) {

            // ask user if they want to save changes
            ToolDialog td = new ToolDialog
2718
                (PolicyTool.rb.getString("Save.Changes"), tool, tw, true);
D
duke 已提交
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
            td.displayUserSave(td.QUIT);

            // the above method will perform the QUIT as long as the
            // user does not CANCEL the request

        } else if (PolicyTool.collator.compare(e.getActionCommand(),
                                        tw.NEW_POLICY_FILE) == 0) {

            // ask user if they want to save changes
            ToolDialog td = new ToolDialog
2729
                (PolicyTool.rb.getString("Save.Changes"), tool, tw, true);
D
duke 已提交
2730 2731 2732 2733 2734 2735 2736 2737 2738 2739
            td.displayUserSave(td.NEW);

            // the above method will perform the NEW as long as the
            // user does not CANCEL the request

        } else if (PolicyTool.collator.compare(e.getActionCommand(),
                                        tw.OPEN_POLICY_FILE) == 0) {

            // ask user if they want to save changes
            ToolDialog td = new ToolDialog
2740
                (PolicyTool.rb.getString("Save.Changes"), tool, tw, true);
D
duke 已提交
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
            td.displayUserSave(td.OPEN);

            // the above method will perform the OPEN as long as the
            // user does not CANCEL the request

        } else if (PolicyTool.collator.compare(e.getActionCommand(),
                                        tw.SAVE_POLICY_FILE) == 0) {

            // get the previously entered filename
            String filename = ((TextField)
                    tw.getComponent(tw.MW_FILENAME_TEXTFIELD)).getText();

            // if there is no filename, do a SAVE_AS
            if (filename == null || filename.length() == 0) {
                // user wants to SAVE AS
                ToolDialog td = new ToolDialog
2757
                        (PolicyTool.rb.getString("Save.As"), tool, tw, true);
D
duke 已提交
2758 2759 2760 2761 2762 2763 2764 2765 2766
                td.displaySaveAsDialog(td.NOACTION);
            } else {
                try {
                    // save the policy entries to a file
                    tool.savePolicy(filename);

                    // display status
                    MessageFormat form = new MessageFormat
                        (PolicyTool.rb.getString
2767
                        ("Policy.successfully.written.to.filename"));
D
duke 已提交
2768 2769 2770 2771 2772
                    Object[] source = {filename};
                    tw.displayStatusDialog(null, form.format(source));
                } catch (FileNotFoundException fnfe) {
                    if (filename == null || filename.equals("")) {
                        tw.displayErrorDialog(null, new FileNotFoundException
2773
                                (PolicyTool.rb.getString("null.filename")));
D
duke 已提交
2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
                    } else {
                        tw.displayErrorDialog(null, fnfe);
                    }
                } catch (Exception ee) {
                    tw.displayErrorDialog(null, ee);
                }
            }
        } else if (PolicyTool.collator.compare(e.getActionCommand(),
                                                tw.SAVE_AS_POLICY_FILE) == 0) {

            // user wants to SAVE AS
            ToolDialog td = new ToolDialog
2786
                (PolicyTool.rb.getString("Save.As"), tool, tw, true);
D
duke 已提交
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815
            td.displaySaveAsDialog(td.NOACTION);

        } else if (PolicyTool.collator.compare(e.getActionCommand(),
                                                tw.VIEW_WARNINGS) == 0) {
            tw.displayWarningLog(null);
        }
    }
}

/**
 * Event handler for the main window buttons and Edit Menu
 */
class MainWindowListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;

    MainWindowListener(PolicyTool tool, ToolWindow tw) {
        this.tool = tool;
        this.tw = tw;
    }

    public void actionPerformed(ActionEvent e) {

        if (PolicyTool.collator.compare(e.getActionCommand(),
                                        tw.ADD_POLICY_ENTRY) == 0) {

            // display a dialog box for the user to enter policy info
            ToolDialog td = new ToolDialog
2816
                (PolicyTool.rb.getString("Policy.Entry"), tool, tw, true);
D
duke 已提交
2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
            td.displayPolicyEntryDialog(false);

        } else if (PolicyTool.collator.compare(e.getActionCommand(),
                                        tw.REMOVE_POLICY_ENTRY) == 0) {

            // get the selected entry
            List list = (List)tw.getComponent(tw.MW_POLICY_LIST);
            int index = list.getSelectedIndex();
            if (index < 0) {
                tw.displayErrorDialog(null, new Exception
2827
                        (PolicyTool.rb.getString("No.Policy.Entry.selected")));
D
duke 已提交
2828 2829 2830 2831 2832
                return;
            }

            // ask the user if they really want to remove the policy entry
            ToolDialog td = new ToolDialog(PolicyTool.rb.getString
2833
                ("Remove.Policy.Entry"), tool, tw, true);
D
duke 已提交
2834 2835 2836 2837 2838 2839 2840 2841 2842 2843
            td.displayConfirmRemovePolicyEntry();

        } else if (PolicyTool.collator.compare(e.getActionCommand(),
                                        tw.EDIT_POLICY_ENTRY) == 0) {

            // get the selected entry
            List list = (List)tw.getComponent(tw.MW_POLICY_LIST);
            int index = list.getSelectedIndex();
            if (index < 0) {
                tw.displayErrorDialog(null, new Exception
2844
                        (PolicyTool.rb.getString("No.Policy.Entry.selected")));
D
duke 已提交
2845 2846 2847 2848 2849
                return;
            }

            // display the permission list for a policy entry
            ToolDialog td = new ToolDialog
2850
                (PolicyTool.rb.getString("Policy.Entry"), tool, tw, true);
D
duke 已提交
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
            td.displayPolicyEntryDialog(true);

        } else if (PolicyTool.collator.compare(e.getActionCommand(),
                                        tw.EDIT_KEYSTORE) == 0) {

            // display a dialog box for the user to enter keystore info
            ToolDialog td = new ToolDialog
                (PolicyTool.rb.getString("KeyStore"), tool, tw, true);
            td.keyStoreDialog(td.EDIT_KEYSTORE);
        }
    }
}

/**
 * Event handler for OverWriteFileOKButton button
 */
class OverWriteFileOKButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog td;
    private String filename;
    private int nextEvent;

    OverWriteFileOKButtonListener(PolicyTool tool, ToolWindow tw,
                                ToolDialog td, String filename, int nextEvent) {
        this.tool = tool;
        this.tw = tw;
        this.td = td;
        this.filename = filename;
        this.nextEvent = nextEvent;
    }

    public void actionPerformed(ActionEvent e) {
        try {
            // save the policy entries to a file
            tool.savePolicy(filename);

            // display status
            MessageFormat form = new MessageFormat
                (PolicyTool.rb.getString
2892
                ("Policy.successfully.written.to.filename"));
D
duke 已提交
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910
            Object[] source = {filename};
            tw.displayStatusDialog(null, form.format(source));

            // display the new policy filename
            TextField newFilename = (TextField)tw.getComponent
                                (tw.MW_FILENAME_TEXTFIELD);
            newFilename.setText(filename);
            tw.setVisible(true);

            // now continue with the originally requested command
            // (QUIT, NEW, or OPEN)
            td.setVisible(false);
            td.dispose();
            td.userSaveContinue(tool, tw, td, nextEvent);

        } catch (FileNotFoundException fnfe) {
            if (filename == null || filename.equals("")) {
                tw.displayErrorDialog(null, new FileNotFoundException
2911
                                (PolicyTool.rb.getString("null.filename")));
D
duke 已提交
2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962
            } else {
                tw.displayErrorDialog(null, fnfe);
            }
            td.setVisible(false);
            td.dispose();
        } catch (Exception ee) {
            tw.displayErrorDialog(null, ee);
            td.setVisible(false);
            td.dispose();
        }
    }
}

/**
 * Event handler for AddEntryDoneButton button
 *
 * -- if edit is TRUE, then we are EDITing an existing PolicyEntry
 *    and we need to update both the policy and the GUI listing.
 *    if edit is FALSE, then we are ADDing a new PolicyEntry,
 *    so we only need to update the GUI listing.
 */
class AddEntryDoneButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog td;
    private boolean edit;

    AddEntryDoneButtonListener(PolicyTool tool, ToolWindow tw,
                                ToolDialog td, boolean edit) {
        this.tool = tool;
        this.tw = tw;
        this.td = td;
        this.edit = edit;
    }

    public void actionPerformed(ActionEvent e) {

        try {
            // get a PolicyEntry object from the dialog policy info
            PolicyEntry newEntry = td.getPolicyEntryFromDialog();
            PolicyParser.GrantEntry newGe = newEntry.getGrantEntry();

            // see if all the signers have public keys
            if (newGe.signedBy != null) {
                String signers[] = tool.parseSigners(newGe.signedBy);
                for (int i = 0; i < signers.length; i++) {
                    PublicKey pubKey = tool.getPublicKeyAlias(signers[i]);
                    if (pubKey == null) {
                        MessageFormat form = new MessageFormat
                            (PolicyTool.rb.getString
2963
                            ("Warning.A.public.key.for.alias.signers.i.does.not.exist.Make.sure.a.KeyStore.is.properly.configured."));
D
duke 已提交
2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
                        Object[] source = {signers[i]};
                        tool.warnings.addElement(form.format(source));
                        tw.displayStatusDialog(td, form.format(source));
                    }
                }
            }

            // add the entry
            List policyList = (List)tw.getComponent(tw.MW_POLICY_LIST);
            if (edit) {
                int listIndex = policyList.getSelectedIndex();
                tool.addEntry(newEntry, listIndex);
                String newCodeBaseStr = newEntry.headerToString();
                if (PolicyTool.collator.compare
                        (newCodeBaseStr, policyList.getItem(listIndex)) != 0)
                    tool.modified = true;
                policyList.replaceItem(newCodeBaseStr, listIndex);
            } else {
                tool.addEntry(newEntry, -1);
                policyList.add(newEntry.headerToString());
                tool.modified = true;
            }
            td.setVisible(false);
            td.dispose();

        } catch (Exception eee) {
            tw.displayErrorDialog(td, eee);
        }
    }
}

/**
 * Event handler for ChangeKeyStoreOKButton button
 */
class ChangeKeyStoreOKButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog td;

    ChangeKeyStoreOKButtonListener(PolicyTool tool, ToolWindow tw,
                ToolDialog td) {
        this.tool = tool;
        this.tw = tw;
        this.td = td;
    }

    public void actionPerformed(ActionEvent e) {

        String URLString = ((TextField)
                td.getComponent(td.KSD_NAME_TEXTFIELD)).getText().trim();
        String type = ((TextField)
                td.getComponent(td.KSD_TYPE_TEXTFIELD)).getText().trim();
        String provider = ((TextField)
                td.getComponent(td.KSD_PROVIDER_TEXTFIELD)).getText().trim();
        String pwdURL = ((TextField)
                td.getComponent(td.KSD_PWD_URL_TEXTFIELD)).getText().trim();

        try {
            tool.openKeyStore
                        ((URLString.length() == 0 ? null : URLString),
                        (type.length() == 0 ? null : type),
                        (provider.length() == 0 ? null : provider),
                        (pwdURL.length() == 0 ? null : pwdURL));
            tool.modified = true;
        } catch (Exception ex) {
            MessageFormat form = new MessageFormat(PolicyTool.rb.getString
3031
                ("Unable.to.open.KeyStore.ex.toString."));
D
duke 已提交
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126
            Object[] source = {ex.toString()};
            tw.displayErrorDialog(td, form.format(source));
            return;
        }

        td.dispose();
    }
}

/**
 * Event handler for AddPrinButton button
 */
class AddPrinButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog td;
    private boolean editPolicyEntry;

    AddPrinButtonListener(PolicyTool tool, ToolWindow tw,
                                ToolDialog td, boolean editPolicyEntry) {
        this.tool = tool;
        this.tw = tw;
        this.td = td;
        this.editPolicyEntry = editPolicyEntry;
    }

    public void actionPerformed(ActionEvent e) {

        // display a dialog box for the user to enter principal info
        td.displayPrincipalDialog(editPolicyEntry, false);
    }
}

/**
 * Event handler for AddPermButton button
 */
class AddPermButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog td;
    private boolean editPolicyEntry;

    AddPermButtonListener(PolicyTool tool, ToolWindow tw,
                                ToolDialog td, boolean editPolicyEntry) {
        this.tool = tool;
        this.tw = tw;
        this.td = td;
        this.editPolicyEntry = editPolicyEntry;
    }

    public void actionPerformed(ActionEvent e) {

        // display a dialog box for the user to enter permission info
        td.displayPermissionDialog(editPolicyEntry, false);
    }
}

/**
 * Event handler for AddPrinOKButton button
 */
class NewPolicyPrinOKButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog listDialog;
    private ToolDialog infoDialog;
    private boolean edit;

    NewPolicyPrinOKButtonListener(PolicyTool tool,
                                ToolWindow tw,
                                ToolDialog listDialog,
                                ToolDialog infoDialog,
                                boolean edit) {
        this.tool = tool;
        this.tw = tw;
        this.listDialog = listDialog;
        this.infoDialog = infoDialog;
        this.edit = edit;
    }

    public void actionPerformed(ActionEvent e) {

        try {
            // read in the new principal info from Dialog Box
            PolicyParser.PrincipalEntry pppe =
                        infoDialog.getPrinFromDialog();
            if (pppe != null) {
                try {
                    tool.verifyPrincipal(pppe.getPrincipalClass(),
                                        pppe.getPrincipalName());
                } catch (ClassNotFoundException cnfe) {
                    MessageFormat form = new MessageFormat
                                (PolicyTool.rb.getString
3127
                                ("Warning.Class.not.found.class"));
D
duke 已提交
3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187
                    Object[] source = {pppe.getPrincipalClass()};
                    tool.warnings.addElement(form.format(source));
                    tw.displayStatusDialog(infoDialog, form.format(source));
                }

                // add the principal to the GUI principal list
                TaggedList prinList =
                    (TaggedList)listDialog.getComponent(listDialog.PE_PRIN_LIST);

                String prinString = ToolDialog.PrincipalEntryToUserFriendlyString(pppe);
                if (edit) {
                    // if editing, replace the original principal
                    int index = prinList.getSelectedIndex();
                    prinList.replaceTaggedItem(prinString, pppe, index);
                } else {
                    // if adding, just add it to the end
                    prinList.addTaggedItem(prinString, pppe);
                }
            }
            infoDialog.dispose();
        } catch (Exception ee) {
            tw.displayErrorDialog(infoDialog, ee);
        }
    }
}

/**
 * Event handler for AddPermOKButton button
 */
class NewPolicyPermOKButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog listDialog;
    private ToolDialog infoDialog;
    private boolean edit;

    NewPolicyPermOKButtonListener(PolicyTool tool,
                                ToolWindow tw,
                                ToolDialog listDialog,
                                ToolDialog infoDialog,
                                boolean edit) {
        this.tool = tool;
        this.tw = tw;
        this.listDialog = listDialog;
        this.infoDialog = infoDialog;
        this.edit = edit;
    }

    public void actionPerformed(ActionEvent e) {

        try {
            // read in the new permission info from Dialog Box
            PolicyParser.PermissionEntry pppe =
                        infoDialog.getPermFromDialog();

            try {
                tool.verifyPermission(pppe.permission, pppe.name, pppe.action);
            } catch (ClassNotFoundException cnfe) {
                MessageFormat form = new MessageFormat(PolicyTool.rb.getString
3188
                                ("Warning.Class.not.found.class"));
D
duke 已提交
3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
                Object[] source = {pppe.permission};
                tool.warnings.addElement(form.format(source));
                tw.displayStatusDialog(infoDialog, form.format(source));
            }

            // add the permission to the GUI permission list
            TaggedList permList =
                (TaggedList)listDialog.getComponent(listDialog.PE_PERM_LIST);

            String permString = ToolDialog.PermissionEntryToUserFriendlyString(pppe);
            if (edit) {
                // if editing, replace the original permission
                int which = permList.getSelectedIndex();
                permList.replaceTaggedItem(permString, pppe, which);
            } else {
                // if adding, just add it to the end
                permList.addTaggedItem(permString, pppe);
            }
            infoDialog.dispose();

        } catch (InvocationTargetException ite) {
            tw.displayErrorDialog(infoDialog, ite.getTargetException());
        } catch (Exception ee) {
            tw.displayErrorDialog(infoDialog, ee);
        }
    }
}

/**
 * Event handler for RemovePrinButton button
 */
class RemovePrinButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog td;
    private boolean edit;

    RemovePrinButtonListener(PolicyTool tool, ToolWindow tw,
                                ToolDialog td, boolean edit) {
        this.tool = tool;
        this.tw = tw;
        this.td = td;
        this.edit = edit;
    }

    public void actionPerformed(ActionEvent e) {

        // get the Principal selected from the Principal List
        TaggedList prinList = (TaggedList)td.getComponent(td.PE_PRIN_LIST);
        int prinIndex = prinList.getSelectedIndex();

        if (prinIndex < 0) {
            tw.displayErrorDialog(td, new Exception
3243
                (PolicyTool.rb.getString("No.principal.selected")));
D
duke 已提交
3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276
            return;
        }
        // remove the principal from the display
        prinList.removeTaggedItem(prinIndex);
    }
}

/**
 * Event handler for RemovePermButton button
 */
class RemovePermButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog td;
    private boolean edit;

    RemovePermButtonListener(PolicyTool tool, ToolWindow tw,
                                ToolDialog td, boolean edit) {
        this.tool = tool;
        this.tw = tw;
        this.td = td;
        this.edit = edit;
    }

    public void actionPerformed(ActionEvent e) {

        // get the Permission selected from the Permission List
        TaggedList permList = (TaggedList)td.getComponent(td.PE_PERM_LIST);
        int permIndex = permList.getSelectedIndex();

        if (permIndex < 0) {
            tw.displayErrorDialog(td, new Exception
3277
                (PolicyTool.rb.getString("No.permission.selected")));
D
duke 已提交
3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
            return;
        }
        // remove the permission from the display
        permList.removeTaggedItem(permIndex);

    }
}

/**
 * Event handler for Edit Principal button
 *
 * We need the editPolicyEntry boolean to tell us if the user is
 * adding a new PolicyEntry at this time, or editing an existing entry.
 * If the user is adding a new PolicyEntry, we ONLY update the
 * GUI listing.  If the user is editing an existing PolicyEntry, we
 * update both the GUI listing and the actual PolicyEntry.
 */
class EditPrinButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog td;
    private boolean editPolicyEntry;

    EditPrinButtonListener(PolicyTool tool, ToolWindow tw,
                                ToolDialog td, boolean editPolicyEntry) {
        this.tool = tool;
        this.tw = tw;
        this.td = td;
        this.editPolicyEntry = editPolicyEntry;
    }

    public void actionPerformed(ActionEvent e) {

        // get the Principal selected from the Principal List
        TaggedList list = (TaggedList)td.getComponent(td.PE_PRIN_LIST);
        int prinIndex = list.getSelectedIndex();

        if (prinIndex < 0) {
            tw.displayErrorDialog(td, new Exception
3318
                (PolicyTool.rb.getString("No.principal.selected")));
D
duke 已提交
3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356
            return;
        }
        td.displayPrincipalDialog(editPolicyEntry, true);
    }
}

/**
 * Event handler for Edit Permission button
 *
 * We need the editPolicyEntry boolean to tell us if the user is
 * adding a new PolicyEntry at this time, or editing an existing entry.
 * If the user is adding a new PolicyEntry, we ONLY update the
 * GUI listing.  If the user is editing an existing PolicyEntry, we
 * update both the GUI listing and the actual PolicyEntry.
 */
class EditPermButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog td;
    private boolean editPolicyEntry;

    EditPermButtonListener(PolicyTool tool, ToolWindow tw,
                                ToolDialog td, boolean editPolicyEntry) {
        this.tool = tool;
        this.tw = tw;
        this.td = td;
        this.editPolicyEntry = editPolicyEntry;
    }

    public void actionPerformed(ActionEvent e) {

        // get the Permission selected from the Permission List
        List list = (List)td.getComponent(td.PE_PERM_LIST);
        int permIndex = list.getSelectedIndex();

        if (permIndex < 0) {
            tw.displayErrorDialog(td, new Exception
3357
                (PolicyTool.rb.getString("No.permission.selected")));
D
duke 已提交
3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651
            return;
        }
        td.displayPermissionDialog(editPolicyEntry, true);
    }
}

/**
 * Event handler for Principal Popup Menu
 */
class PrincipalTypeMenuListener implements ItemListener {

    private ToolDialog td;

    PrincipalTypeMenuListener(ToolDialog td) {
        this.td = td;
    }

    public void itemStateChanged(ItemEvent e) {

        Choice prin = (Choice)td.getComponent(td.PRD_PRIN_CHOICE);
        TextField prinField =
                        (TextField)td.getComponent(td.PRD_PRIN_TEXTFIELD);
        TextField nameField =
                        (TextField)td.getComponent(td.PRD_NAME_TEXTFIELD);

        prin.getAccessibleContext().setAccessibleName(
            PolicyTool.splitToWords((String)e.getItem()));
        if (((String)e.getItem()).equals(td.PRIN_TYPE)) {
            // ignore if they choose "Principal Type:" item
            if (prinField.getText() != null &&
                prinField.getText().length() > 0) {
                Prin inputPrin = td.getPrin(prinField.getText(), true);
                prin.select(inputPrin.CLASS);
            }
            return;
        }

        // if you change the principal, clear the name
        if (prinField.getText().indexOf((String)e.getItem()) == -1) {
            nameField.setText("");
        }

        // set the text in the textfield and also modify the
        // pull-down choice menus to reflect the correct possible
        // set of names and actions
        Prin inputPrin = td.getPrin((String)e.getItem(), false);
        if (inputPrin != null) {
            prinField.setText(inputPrin.FULL_CLASS);
        }
    }
}

/**
 * Event handler for Permission Popup Menu
 */
class PermissionMenuListener implements ItemListener {

    private ToolDialog td;

    PermissionMenuListener(ToolDialog td) {
        this.td = td;
    }

    public void itemStateChanged(ItemEvent e) {

        Choice perms = (Choice)td.getComponent(td.PD_PERM_CHOICE);
        Choice names = (Choice)td.getComponent(td.PD_NAME_CHOICE);
        Choice actions = (Choice)td.getComponent(td.PD_ACTIONS_CHOICE);
        TextField nameField =
                        (TextField)td.getComponent(td.PD_NAME_TEXTFIELD);
        TextField actionsField =
                        (TextField)td.getComponent(td.PD_ACTIONS_TEXTFIELD);
        TextField permField = (TextField)td.getComponent(td.PD_PERM_TEXTFIELD);
        TextField signedbyField =
                        (TextField)td.getComponent(td.PD_SIGNEDBY_TEXTFIELD);

        perms.getAccessibleContext().setAccessibleName(
            PolicyTool.splitToWords((String)e.getItem()));

        // ignore if they choose the 'Permission:' item
        if (PolicyTool.collator.compare((String)e.getItem(), td.PERM) == 0) {
            if (permField.getText() != null &&
                permField.getText().length() > 0) {

                Perm inputPerm = td.getPerm(permField.getText(), true);
                if (inputPerm != null) {
                    perms.select(inputPerm.CLASS);
                }
            }
            return;
        }

        // if you change the permission, clear the name, actions, and signedBy
        if (permField.getText().indexOf((String)e.getItem()) == -1) {
            nameField.setText("");
            actionsField.setText("");
            signedbyField.setText("");
        }

        // set the text in the textfield and also modify the
        // pull-down choice menus to reflect the correct possible
        // set of names and actions

        Perm inputPerm = td.getPerm((String)e.getItem(), false);
        if (inputPerm == null) {
            permField.setText("");
        } else {
            permField.setText(inputPerm.FULL_CLASS);
        }
        td.setPermissionNames(inputPerm, names, nameField);
        td.setPermissionActions(inputPerm, actions, actionsField);
    }
}

/**
 * Event handler for Permission Name Popup Menu
 */
class PermissionNameMenuListener implements ItemListener {

    private ToolDialog td;

    PermissionNameMenuListener(ToolDialog td) {
        this.td = td;
    }

    public void itemStateChanged(ItemEvent e) {

        Choice names = (Choice)td.getComponent(td.PD_NAME_CHOICE);
        names.getAccessibleContext().setAccessibleName(
            PolicyTool.splitToWords((String)e.getItem()));

        if (((String)e.getItem()).indexOf(td.PERM_NAME) != -1)
            return;

        TextField tf = (TextField)td.getComponent(td.PD_NAME_TEXTFIELD);
        tf.setText((String)e.getItem());
    }
}

/**
 * Event handler for Permission Actions Popup Menu
 */
class PermissionActionsMenuListener implements ItemListener {

    private ToolDialog td;

    PermissionActionsMenuListener(ToolDialog td) {
        this.td = td;
    }

    public void itemStateChanged(ItemEvent e) {

        Choice actions = (Choice)td.getComponent(td.PD_ACTIONS_CHOICE);
        actions.getAccessibleContext().setAccessibleName((String)e.getItem());

        if (((String)e.getItem()).indexOf(td.PERM_ACTIONS) != -1)
            return;

        TextField tf = (TextField)td.getComponent(td.PD_ACTIONS_TEXTFIELD);
        if (tf.getText() == null || tf.getText().equals("")) {
            tf.setText((String)e.getItem());
        } else {
            if (tf.getText().indexOf((String)e.getItem()) == -1)
                tf.setText(tf.getText() + ", " + (String)e.getItem());
        }
    }
}

/**
 * Event handler for all the children dialogs/windows
 */
class ChildWindowListener implements WindowListener {

    private ToolDialog td;

    ChildWindowListener(ToolDialog td) {
        this.td = td;
    }

    public void windowOpened(WindowEvent we) {
    }

    public void windowClosing(WindowEvent we) {
        // same as pressing the "cancel" button
        td.setVisible(false);
        td.dispose();
    }

    public void windowClosed(WindowEvent we) {
    }

    public void windowIconified(WindowEvent we) {
    }

    public void windowDeiconified(WindowEvent we) {
    }

    public void windowActivated(WindowEvent we) {
    }

    public void windowDeactivated(WindowEvent we) {
    }
}

/**
 * Event handler for CancelButton button
 */
class CancelButtonListener implements ActionListener {

    private ToolDialog td;

    CancelButtonListener(ToolDialog td) {
        this.td = td;
    }

    public void actionPerformed(ActionEvent e) {
        td.setVisible(false);
        td.dispose();
    }
}

/**
 * Event handler for ErrorOKButton button
 */
class ErrorOKButtonListener implements ActionListener {

    private ToolDialog ed;

    ErrorOKButtonListener(ToolDialog ed) {
        this.ed = ed;
    }

    public void actionPerformed(ActionEvent e) {
        ed.setVisible(false);
        ed.dispose();
    }
}

/**
 * Event handler for StatusOKButton button
 */
class StatusOKButtonListener implements ActionListener {

    private ToolDialog sd;

    StatusOKButtonListener(ToolDialog sd) {
        this.sd = sd;
    }

    public void actionPerformed(ActionEvent e) {
        sd.setVisible(false);
        sd.dispose();
    }
}

/**
 * Event handler for UserSaveYes button
 */
class UserSaveYesButtonListener implements ActionListener {

    private ToolDialog us;
    private PolicyTool tool;
    private ToolWindow tw;
    private int select;

    UserSaveYesButtonListener(ToolDialog us, PolicyTool tool,
                        ToolWindow tw, int select) {
        this.us = us;
        this.tool = tool;
        this.tw = tw;
        this.select = select;
    }

    public void actionPerformed(ActionEvent e) {

        // first get rid of the window
        us.setVisible(false);
        us.dispose();

        try {
            String filename = ((TextField)
                    tw.getComponent(tw.MW_FILENAME_TEXTFIELD)).getText();
            if (filename == null || filename.equals("")) {
                us.displaySaveAsDialog(select);

                // the above dialog will continue with the originally
                // requested command if necessary
            } else {
                // save the policy entries to a file
                tool.savePolicy(filename);

                // display status
                MessageFormat form = new MessageFormat
                        (PolicyTool.rb.getString
3652
                        ("Policy.successfully.written.to.filename"));
D
duke 已提交
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883
                Object[] source = {filename};
                tw.displayStatusDialog(null, form.format(source));

                // now continue with the originally requested command
                // (QUIT, NEW, or OPEN)
                us.userSaveContinue(tool, tw, us, select);
            }
        } catch (Exception ee) {
            // error -- just report it and bail
            tw.displayErrorDialog(null, ee);
        }
    }
}

/**
 * Event handler for UserSaveNoButton
 */
class UserSaveNoButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog us;
    private int select;

    UserSaveNoButtonListener(ToolDialog us, PolicyTool tool,
                        ToolWindow tw, int select) {
        this.us = us;
        this.tool = tool;
        this.tw = tw;
        this.select = select;
    }

    public void actionPerformed(ActionEvent e) {
        us.setVisible(false);
        us.dispose();

        // now continue with the originally requested command
        // (QUIT, NEW, or OPEN)
        us.userSaveContinue(tool, tw, us, select);
    }
}

/**
 * Event handler for UserSaveCancelButton
 */
class UserSaveCancelButtonListener implements ActionListener {

    private ToolDialog us;

    UserSaveCancelButtonListener(ToolDialog us) {
        this.us = us;
    }

    public void actionPerformed(ActionEvent e) {
        us.setVisible(false);
        us.dispose();

        // do NOT continue with the originally requested command
        // (QUIT, NEW, or OPEN)
    }
}

/**
 * Event handler for ConfirmRemovePolicyEntryOKButtonListener
 */
class ConfirmRemovePolicyEntryOKButtonListener implements ActionListener {

    private PolicyTool tool;
    private ToolWindow tw;
    private ToolDialog us;

    ConfirmRemovePolicyEntryOKButtonListener(PolicyTool tool,
                                ToolWindow tw, ToolDialog us) {
        this.tool = tool;
        this.tw = tw;
        this.us = us;
    }

    public void actionPerformed(ActionEvent e) {
        // remove the entry
        List list = (List)tw.getComponent(tw.MW_POLICY_LIST);
        int index = list.getSelectedIndex();
        PolicyEntry entries[] = tool.getEntry();
        tool.removeEntry(entries[index]);

        // redraw the window listing
        list = new List(40, false);
        list.addActionListener(new PolicyListListener(tool, tw));
        entries = tool.getEntry();
        if (entries != null) {
                for (int i = 0; i < entries.length; i++)
                    list.add(entries[i].headerToString());
        }
        tw.replacePolicyList(list);
        us.setVisible(false);
        us.dispose();
    }
}

/**
 * Just a special name, so that the codes dealing with this exception knows
 * it's special, and does not pop out a warning box.
 */
class NoDisplayException extends RuntimeException {

}

/**
 * This is a java.awt.List that bind an Object to each String it holds.
 */
class TaggedList extends List {
    private java.util.List<Object> data = new LinkedList<Object>();
    public TaggedList(int i, boolean b) {
        super(i, b);
    }

    public Object getObject(int index) {
        return data.get(index);
    }

    @Override @Deprecated public void add(String string) {
        throw new AssertionError("should not call add in TaggedList");
    }
    public void addTaggedItem(String string, Object object) {
        super.add(string);
        data.add(object);
    }

    @Override @Deprecated public void replaceItem(String string, int index) {
        throw new AssertionError("should not call replaceItem in TaggedList");
    }
    public void replaceTaggedItem(String string, Object object, int index) {
        super.replaceItem(string, index);
        data.set(index, object);
    }

    @Override @Deprecated public void remove(int index) {
        // Cannot throw AssertionError, because replaceItem() call remove() internally
        super.remove(index);
    }
    public void removeTaggedItem(int index) {
        super.remove(index);
        data.remove(index);
    }
}

/**
 * Convenience Principal Classes
 */

class Prin {
    public final String CLASS;
    public final String FULL_CLASS;

    public Prin(String clazz, String fullClass) {
        this.CLASS = clazz;
        this.FULL_CLASS = fullClass;
    }
}

class KrbPrin extends Prin {
    public KrbPrin() {
        super("KerberosPrincipal",
                "javax.security.auth.kerberos.KerberosPrincipal");
    }
}

class X500Prin extends Prin {
    public X500Prin() {
        super("X500Principal",
                "javax.security.auth.x500.X500Principal");
    }
}

/**
 * Convenience Permission Classes
 */

class Perm {
    public final String CLASS;
    public final String FULL_CLASS;
    public final String[] TARGETS;
    public final String[] ACTIONS;

    public Perm(String clazz, String fullClass,
                String[] targets, String[] actions) {

        this.CLASS = clazz;
        this.FULL_CLASS = fullClass;
        this.TARGETS = targets;
        this.ACTIONS = actions;
    }
}

class AllPerm extends Perm {
    public AllPerm() {
        super("AllPermission", "java.security.AllPermission", null, null);
    }
}

class AudioPerm extends Perm {
    public AudioPerm() {
        super("AudioPermission",
        "javax.sound.sampled.AudioPermission",
        new String[]    {
                "play",
                "record"
                },
        null);
    }
}

class AuthPerm extends Perm {
    public AuthPerm() {
    super("AuthPermission",
        "javax.security.auth.AuthPermission",
        new String[]    {
                "doAs",
                "doAsPrivileged",
                "getSubject",
                "getSubjectFromDomainCombiner",
                "setReadOnly",
                "modifyPrincipals",
                "modifyPublicCredentials",
                "modifyPrivateCredentials",
                "refreshCredential",
                "destroyCredential",
                "createLoginContext.<" + PolicyTool.rb.getString("name") + ">",
                "getLoginConfiguration",
                "setLoginConfiguration",
                "createLoginConfiguration.<" +
3884
                        PolicyTool.rb.getString("configuration.type") + ">",
D
duke 已提交
3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940
                "refreshLoginConfiguration"
                },
        null);
    }
}

class AWTPerm extends Perm {
    public AWTPerm() {
    super("AWTPermission",
        "java.awt.AWTPermission",
        new String[]    {
                "accessClipboard",
                "accessEventQueue",
                "accessSystemTray",
                "createRobot",
                "fullScreenExclusive",
                "listenToAllAWTEvents",
                "readDisplayPixels",
                "replaceKeyboardFocusManager",
                "setAppletStub",
                "setWindowAlwaysOnTop",
                "showWindowWithoutWarningBanner",
                "toolkitModality",
                "watchMousePointer"
        },
        null);
    }
}

class DelegationPerm extends Perm {
    public DelegationPerm() {
    super("DelegationPermission",
        "javax.security.auth.kerberos.DelegationPermission",
        new String[]    {
                // allow user input
                },
        null);
    }
}

class FilePerm extends Perm {
    public FilePerm() {
    super("FilePermission",
        "java.io.FilePermission",
        new String[]    {
                "<<ALL FILES>>"
                },
        new String[]    {
                "read",
                "write",
                "delete",
                "execute"
                });
    }
}

3941 3942 3943 3944 3945
class InqSecContextPerm extends Perm {
    public InqSecContextPerm() {
    super("InquireSecContextPermission",
        "com.sun.security.jgss.InquireSecContextPermission",
        new String[]    {
3946 3947 3948 3949
                "KRB5_GET_SESSION_KEY",
                "KRB5_GET_TKT_FLAGS",
                "KRB5_GET_AUTHZ_DATA",
                "KRB5_GET_AUTHTIME"
3950 3951 3952 3953 3954
                },
        null);
    }
}

D
duke 已提交
3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
class LogPerm extends Perm {
    public LogPerm() {
    super("LoggingPermission",
        "java.util.logging.LoggingPermission",
        new String[]    {
                "control"
                },
        null);
    }
}

class MgmtPerm extends Perm {
    public MgmtPerm() {
    super("ManagementPermission",
        "java.lang.management.ManagementPermission",
        new String[]    {
                "control",
                "monitor"
                },
        null);
    }
}

class MBeanPerm extends Perm {
    public MBeanPerm() {
    super("MBeanPermission",
        "javax.management.MBeanPermission",
        new String[]    {
                // allow user input
                },
        new String[]    {
                "addNotificationListener",
                "getAttribute",
                "getClassLoader",
                "getClassLoaderFor",
                "getClassLoaderRepository",
                "getDomains",
                "getMBeanInfo",
                "getObjectInstance",
                "instantiate",
                "invoke",
                "isInstanceOf",
                "queryMBeans",
                "queryNames",
                "registerMBean",
                "removeNotificationListener",
                "setAttribute",
                "unregisterMBean"
                });
    }
}

class MBeanSvrPerm extends Perm {
    public MBeanSvrPerm() {
    super("MBeanServerPermission",
        "javax.management.MBeanServerPermission",
        new String[]    {
                "createMBeanServer",
                "findMBeanServer",
                "newMBeanServer",
                "releaseMBeanServer"
                },
        null);
    }
}

class MBeanTrustPerm extends Perm {
    public MBeanTrustPerm() {
    super("MBeanTrustPermission",
        "javax.management.MBeanTrustPermission",
        new String[]    {
                "register"
                },
        null);
    }
}

class NetPerm extends Perm {
    public NetPerm() {
    super("NetPermission",
        "java.net.NetPermission",
        new String[]    {
                "setDefaultAuthenticator",
                "requestPasswordAuthentication",
                "specifyStreamHandler",
                "setProxySelector",
                "getProxySelector",
                "setCookieHandler",
                "getCookieHandler",
                "setResponseCache",
                "getResponseCache"
                },
        null);
    }
}

class PrivCredPerm extends Perm {
    public PrivCredPerm() {
    super("PrivateCredentialPermission",
        "javax.security.auth.PrivateCredentialPermission",
        new String[]    {
                // allow user input
                },
        new String[]    {
                "read"
                });
    }
}

class PropPerm extends Perm {
    public PropPerm() {
    super("PropertyPermission",
        "java.util.PropertyPermission",
        new String[]    {
                // allow user input
                },
        new String[]    {
                "read",
                "write"
                });
    }
}

class ReflectPerm extends Perm {
    public ReflectPerm() {
    super("ReflectPermission",
        "java.lang.reflect.ReflectPermission",
        new String[]    {
                "suppressAccessChecks"
                },
        null);
    }
}

class RuntimePerm extends Perm {
    public RuntimePerm() {
    super("RuntimePermission",
        "java.lang.RuntimePermission",
        new String[]    {
                "createClassLoader",
                "getClassLoader",
                "setContextClassLoader",
                "enableContextClassLoaderOverride",
4098
                "setSecurityManager",
D
duke 已提交
4099 4100
                "createSecurityManager",
                "getenv.<" +
4101
                    PolicyTool.rb.getString("environment.variable.name") + ">",
D
duke 已提交
4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112
                "exitVM",
                "shutdownHooks",
                "setFactory",
                "setIO",
                "modifyThread",
                "stopThread",
                "modifyThreadGroup",
                "getProtectionDomain",
                "readFileDescriptor",
                "writeFileDescriptor",
                "loadLibrary.<" +
4113
                    PolicyTool.rb.getString("library.name") + ">",
D
duke 已提交
4114
                "accessClassInPackage.<" +
4115
                    PolicyTool.rb.getString("package.name")+">",
D
duke 已提交
4116
                "defineClassInPackage.<" +
4117
                    PolicyTool.rb.getString("package.name")+">",
D
duke 已提交
4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139
                "accessDeclaredMembers",
                "queuePrintJob",
                "getStackTrace",
                "setDefaultUncaughtExceptionHandler",
                "preferences",
                "usePolicy",
                // "inheritedChannel"
                },
        null);
    }
}

class SecurityPerm extends Perm {
    public SecurityPerm() {
    super("SecurityPermission",
        "java.security.SecurityPermission",
        new String[]    {
                "createAccessControlContext",
                "getDomainCombiner",
                "getPolicy",
                "setPolicy",
                "createPolicy.<" +
4140
                    PolicyTool.rb.getString("policy.type") + ">",
D
duke 已提交
4141
                "getProperty.<" +
4142
                    PolicyTool.rb.getString("property.name") + ">",
D
duke 已提交
4143
                "setProperty.<" +
4144
                    PolicyTool.rb.getString("property.name") + ">",
D
duke 已提交
4145
                "insertProvider.<" +
4146
                    PolicyTool.rb.getString("provider.name") + ">",
D
duke 已提交
4147
                "removeProvider.<" +
4148
                    PolicyTool.rb.getString("provider.name") + ">",
D
duke 已提交
4149 4150 4151 4152 4153 4154 4155
                //"setSystemScope",
                //"setIdentityPublicKey",
                //"setIdentityInfo",
                //"addIdentityCertificate",
                //"removeIdentityCertificate",
                //"printIdentity",
                "clearProviderProperties.<" +
4156
                    PolicyTool.rb.getString("provider.name") + ">",
D
duke 已提交
4157
                "putProviderProperty.<" +
4158
                    PolicyTool.rb.getString("provider.name") + ">",
D
duke 已提交
4159
                "removeProviderProperty.<" +
4160
                    PolicyTool.rb.getString("provider.name") + ">",
D
duke 已提交
4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214
                //"getSignerPrivateKey",
                //"setSignerKeyPair"
                },
        null);
    }
}

class SerialPerm extends Perm {
    public SerialPerm() {
    super("SerializablePermission",
        "java.io.SerializablePermission",
        new String[]    {
                "enableSubclassImplementation",
                "enableSubstitution"
                },
        null);
    }
}

class ServicePerm extends Perm {
    public ServicePerm() {
    super("ServicePermission",
        "javax.security.auth.kerberos.ServicePermission",
        new String[]    {
                // allow user input
                },
        new String[]    {
                "initiate",
                "accept"
                });
    }
}

class SocketPerm extends Perm {
    public SocketPerm() {
    super("SocketPermission",
        "java.net.SocketPermission",
        new String[]    {
                // allow user input
                },
        new String[]    {
                "accept",
                "connect",
                "listen",
                "resolve"
                });
    }
}

class SQLPerm extends Perm {
    public SQLPerm() {
    super("SQLPermission",
        "java.sql.SQLPermission",
        new String[]    {
4215 4216 4217 4218
                "setLog",
                "callAbort",
                "setSyncFactory",
                "setNetworkTimeout",
D
duke 已提交
4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245
                },
        null);
    }
}

class SSLPerm extends Perm {
    public SSLPerm() {
    super("SSLPermission",
        "javax.net.ssl.SSLPermission",
        new String[]    {
                "setHostnameVerifier",
                "getSSLSessionContext"
                },
        null);
    }
}

class SubjDelegPerm extends Perm {
    public SubjDelegPerm() {
    super("SubjectDelegationPermission",
        "javax.management.remote.SubjectDelegationPermission",
        new String[]    {
                // allow user input
                },
        null);
    }
}