/*
 * Written by Dawid Kurzyniec and released to the public domain, as explained
 * at http://creativecommons.org/licenses/publicdomain
 */

package edu.emory.mathcs.util.security.action;

import java.security.*;

/**
 * A convenience class for retrieving the integer value of a system property
 * as a privileged action.
 *
 * @see java.security.PrivilegedAction
 * @see java.security.AccessController
 */

public class GetIntegerAction implements PrivilegedAction {
    private String prop;
    private int defaultVal;
    private boolean defaultSet = false;

    /**
     * Constructor that takes the name of the system property whose integer
     * value needs to be determined.
     *
     * @param prop the name of the system property
     */
    public GetIntegerAction(String prop) {
        this.prop = prop;
    }

    /**
     * Constructor that takes the name of the system property and a default
     * value to use when property is not set.
     *
     * @param prop the name of the system property
     * @param defaultVal the default value
     */
    public GetIntegerAction(String prop, int defaultVal) {
        this.prop = prop;
        this.defaultVal = defaultVal;
        this.defaultSet = true;
    }

    /**
     * Determines the integer value of the system property whose name was
     * specified in the constructor.
     *
     * <p>If there is no property of the specified name, or if the property
     * does not have the correct numeric format, then an <code>Integer</code>
     * object representing the default value that was specified in the
     * constructor is returned, or <code>null</code> if no default value was
     * specified.
     *
     * @return the <code>Integer</code> value of the property
     */
    public Object run() {
        Integer value = Integer.getInteger(prop);
        if ((value == null) && defaultSet) return new Integer(defaultVal);
        return value;
    }
}
