org.apache.catalina.Realm

Here are the examples of the java api org.apache.catalina.Realm taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

87 Examples 7

19 Source : TesterHost.java
with Apache License 2.0
from wangyingjie

@Override
public void setRealm(Realm realm) {
// NO-OP
}

19 Source : Embedded.java
with Apache License 2.0
from wangyingjie

/**
 * Set the default Realm for our Containers.
 *
 * @param realm The new default realm
 */
public void setRealm(Realm realm) {
    Realm oldRealm = this.realm;
    this.realm = realm;
    support.firePropertyChange("realm", oldRealm, this.realm);
}

19 Source : CombinedRealm.java
with Apache License 2.0
from wangyingjie

/**
 * Gracefully terminate the active use of the public methods of this
 * component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that needs to be reported
 */
@Override
protected void stopInternal() throws LifecycleException {
    // Stop this realm, then the sub-realms (reverse order to start)
    super.stopInternal();
    for (Realm realm : realms) {
        if (realm instanceof Lifecycle) {
            ((Lifecycle) realm).stop();
        }
    }
}

19 Source : CombinedRealm.java
with Apache License 2.0
from wangyingjie

/**
 * Ensure child Realms are destroyed when this Realm is destroyed.
 */
@Override
protected void destroyInternal() throws LifecycleException {
    for (Realm realm : realms) {
        if (realm instanceof Lifecycle) {
            ((Lifecycle) realm).destroy();
        }
    }
    super.destroyInternal();
}

19 Source : SerializablePrincipal.java
with Apache License 2.0
from wangyingjie

public void setRealm(Realm realm) {
    this.realm = realm;
}

19 Source : StandardEngine.java
with Apache License 2.0
from wangyingjie

// ------------------------------------------------------------- Properties
/**
 * Obtain the configured Realm and provide a default Realm implementation
 * when no explicit configuration is set.
 *
 * @return configured realm, or a {@link NullRealm} by default
 */
@Override
public Realm getRealm() {
    Realm configured = super.getRealm();
    // If no set realm has been called - default to NullRealm
    // This can be overridden at engine, context and host level
    if (configured == null) {
        configured = new NullRealm();
        this.setRealm(configured);
    }
    return configured;
}

19 Source : 1650.java
with MIT License
from masud-technope

// ------------------------------------------------------------- Properties
/**
 * Obtain the configured Realm and provide a default Realm implementation
 * when no explicit configuration is set.
 *
 * @return configured realm, or a {@link NullRealm} by default
 */
@Override
public Realm getRealm() {
    Realm configured = super.getRealm();
    // This can be overridden at engine, context and host level
    if (configured == null) {
        configured = new NullRealm();
        this.setRealm(configured);
    }
    return configured;
}

19 Source : Embedded.java
with Apache License 2.0
from how2j

/**
 * Set the default Realm for our Containers.
 *
 * @param realm
 *            The new default realm
 */
public void setRealm(Realm realm) {
    Realm oldRealm = this.realm;
    this.realm = realm;
    support.firePropertyChange("realm", oldRealm, this.realm);
}

19 Source : CombinedRealm.java
with Apache License 2.0
from how2j

/**
 * Gracefully terminate the active use of the public methods of this
 * component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
 *
 * @exception LifecycleException
 *                if this component detects a fatal error that needs to be
 *                reported
 */
@Override
protected void stopInternal() throws LifecycleException {
    // Stop this realm, then the sub-realms (reverse order to start)
    super.stopInternal();
    for (Realm realm : realms) {
        if (realm instanceof Lifecycle) {
            ((Lifecycle) realm).stop();
        }
    }
}

18 Source : Tomcat.java
with Apache License 2.0
from wangyingjie

/**
 * Set a custom realm for auth. If not called, a simple
 * default will be used, using an internal map.
 *
 * Must be called before adding a context.
 *
 * @deprecated Will be removed in Tomcat 8.0.x.
 */
@Deprecated
public void setDefaultRealm(Realm realm) {
    defaultRealm = realm;
}

18 Source : FailedContext.java
with Apache License 2.0
from wangyingjie

@Override
public void setRealm(Realm realm) {
/* NO-OP */
}

18 Source : Embedded.java
with Apache License 2.0
from wangyingjie

/**
 * Convenience clreplaced to embed a Catalina servlet container environment
 * inside another application.  You must call the methods of this clreplaced in the
 * following order to ensure correct operation.
 *
 * <ul>
 * <li>Instantiate a new instance of this clreplaced.</li>
 * <li>Set the relevant properties of this object itself.  In particular,
 *     you will want to establish the default Logger to be used, as well
 *     as the default Realm if you are using container-managed security.</li>
 * <li>Call <code>createEngine()</code> to create an Engine object, and then
 *     call its property setters as desired.</li>
 * <li>Call <code>createHost()</code> to create at least one virtual Host
 *     replacedociated with the newly created Engine, and then call its property
 *     setters as desired.  After you customize this Host, add it to the
 *     corresponding Engine with <code>engine.addChild(host)</code>.</li>
 * <li>Call <code>createContext()</code> to create at least one Context
 *     replacedociated with each newly created Host, and then call its property
 *     setters as desired.  You <strong>SHOULD</strong> create a Context with
 *     a pathname equal to a zero-length string, which will be used to process
 *     all requests not mapped to some other Context.  After you customize
 *     this Context, add it to the corresponding Host with
 *     <code>host.addChild(context)</code>.</li>
 * <li>Call <code>addEngine()</code> to attach this Engine to the set of
 *     defined Engines for this object.</li>
 * <li>Call <code>createConnector()</code> to create at least one TCP/IP
 *     connector, and then call its property setters as desired.</li>
 * <li>Call <code>addConnector()</code> to attach this Connector to the set
 *     of defined Connectors for this object.  The added Connector will use
 *     the most recently added Engine to process its received requests.</li>
 * <li>Repeat the above series of steps as often as required (although there
 *     will typically be only one Engine instance created).</li>
 * <li>Call <code>start()</code> to initiate normal operations of all the
 *     attached components.</li>
 * </ul>
 *
 * After normal operations have begun, you can add and remove Connectors,
 * Engines, Hosts, and Contexts on the fly.  However, once you have removed
 * a particular component, it must be thrown away -- you can create a new one
 * with the same characteristics if you merely want to do a restart.
 * <p>
 * To initiate a normal shutdown, call the <code>stop()</code> method of
 * this object.
 * <p>
 * @see org.apache.catalina.startup.Bootstrap#main For a complete example
 * of how Tomcat is set up and launched as an Embedded application.
 *
 * @author Craig R. McClanahan
 *
 * @deprecated Use {@link Tomcat} instead.
 */
@Deprecated
public clreplaced Embedded extends StandardService {

    private static final Log log = LogFactory.getLog(Embedded.clreplaced);

    // ----------------------------------------------------------- Constructors
    /**
     * Construct a new instance of this clreplaced with default properties.
     */
    public Embedded() {
        this(null);
    }

    /**
     * Construct a new instance of this clreplaced with specified properties.
     *
     * @param realm Realm implementation to be inherited by all components
     *  (unless overridden further down the container hierarchy)
     */
    public Embedded(Realm realm) {
        super();
        setRealm(realm);
        setSecurityProtection();
    }

    // ----------------------------------------------------- Instance Variables
    /**
     * Is naming enabled ?
     */
    protected boolean useNaming = true;

    /**
     * Is standard streams redirection enabled ?
     */
    protected boolean redirectStreams = true;

    /**
     * The set of Engines that have been deployed in this server.  Normally
     * there will only be one.
     */
    protected Engine[] engines = new Engine[0];

    /**
     * Custom mappings of login methods to authenticators
     */
    protected volatile HashMap<String, Authenticator> authenticators;

    /**
     * Descriptive information about this server implementation.
     */
    protected static final String info = "org.apache.catalina.startup.Embedded/1.0";

    /**
     * The default realm to be used by all containers replacedociated with
     * this component.
     */
    protected Realm realm = null;

    /**
     * The string manager for this package.
     */
    protected static final StringManager sm = StringManager.getManager(Constants.Package);

    /**
     * Use await.
     */
    protected boolean await = false;

    // ------------------------------------------------------------- Properties
    /**
     * Return true if naming is enabled.
     */
    public boolean isUseNaming() {
        return (this.useNaming);
    }

    /**
     * Enables or disables naming support.
     *
     * @param useNaming The new use naming value
     */
    public void setUseNaming(boolean useNaming) {
        boolean oldUseNaming = this.useNaming;
        this.useNaming = useNaming;
        support.firePropertyChange("useNaming", Boolean.valueOf(oldUseNaming), Boolean.valueOf(this.useNaming));
    }

    /**
     * Return true if redirection of standard streams is enabled.
     */
    public boolean isRedirectStreams() {
        return (this.redirectStreams);
    }

    /**
     * Enables or disables redirection.
     *
     * @param redirectStreams The new redirection value
     */
    public void setRedirectStreams(boolean redirectStreams) {
        boolean oldRedirectStreams = this.redirectStreams;
        this.redirectStreams = redirectStreams;
        support.firePropertyChange("redirectStreams", Boolean.valueOf(oldRedirectStreams), Boolean.valueOf(this.redirectStreams));
    }

    /**
     * Return the default Realm for our Containers.
     */
    public Realm getRealm() {
        return (this.realm);
    }

    /**
     * Set the default Realm for our Containers.
     *
     * @param realm The new default realm
     */
    public void setRealm(Realm realm) {
        Realm oldRealm = this.realm;
        this.realm = realm;
        support.firePropertyChange("realm", oldRealm, this.realm);
    }

    public void setAwait(boolean b) {
        await = b;
    }

    public boolean isAwait() {
        return await;
    }

    public void setCatalinaHome(String s) {
        System.setProperty(Globals.CATALINA_HOME_PROP, s);
    }

    public void setCatalinaBase(String s) {
        System.setProperty(Globals.CATALINA_BASE_PROP, s);
    }

    public String getCatalinaHome() {
        return System.getProperty(Globals.CATALINA_HOME_PROP);
    }

    public String getCatalinaBase() {
        return System.getProperty(Globals.CATALINA_BASE_PROP);
    }

    // --------------------------------------------------------- Public Methods
    /**
     * Add a new Connector to the set of defined Connectors.  The newly
     * added Connector will be replacedociated with the most recently added Engine.
     *
     * @param connector The connector to be added
     *
     * @exception IllegalStateException if no engines have been added yet
     */
    @Override
    public synchronized void addConnector(Connector connector) {
        if (log.isDebugEnabled()) {
            log.debug("Adding connector (" + connector.getInfo() + ")");
        }
        // Make sure we have a Container to send requests to
        if (engines.length < 1)
            throw new IllegalStateException(sm.getString("embedded.noEngines"));
        /*
         * Add the connector. This will set the connector's container to the
         * most recently added Engine
         */
        super.addConnector(connector);
    }

    /**
     * Add a new Engine to the set of defined Engines.
     *
     * @param engine The engine to be added
     */
    public synchronized void addEngine(Engine engine) {
        if (log.isDebugEnabled())
            log.debug("Adding engine (" + engine.getInfo() + ")");
        // Add this Engine to our set of defined Engines
        Engine[] results = new Engine[engines.length + 1];
        for (int i = 0; i < engines.length; i++) results[i] = engines[i];
        results[engines.length] = engine;
        engines = results;
        // Start this Engine if necessary
        if (getState().isAvailable()) {
            try {
                engine.start();
            } catch (LifecycleException e) {
                log.error("Engine.start", e);
            }
        }
        this.container = engine;
    }

    /**
     * Create, configure, and return a new TCP/IP socket connector
     * based on the specified properties.
     *
     * @param address InetAddress to bind to, or <code>null</code> if the
     * connector is supposed to bind to all addresses on this server
     * @param port Port number to listen to
     * @param secure true if the generated connector is supposed to be
     * SSL-enabled, and false otherwise
     */
    public Connector createConnector(InetAddress address, int port, boolean secure) {
        return createConnector(address != null ? address.toString() : null, port, secure);
    }

    public Connector createConnector(String address, int port, boolean secure) {
        String protocol = "http";
        if (secure) {
            protocol = "https";
        }
        return createConnector(address, port, protocol);
    }

    public Connector createConnector(InetAddress address, int port, String protocol) {
        return createConnector(address != null ? address.toString() : null, port, protocol);
    }

    public Connector createConnector(String address, int port, String protocol) {
        Connector connector = null;
        if (address != null) {
            /*
             * InetAddress.toString() returns a string of the form
             * "<hostname>/<literal_IP>". Get the latter part, so that the
             * address can be parsed (back) into an InetAddress using
             * InetAddress.getByName().
             */
            int index = address.indexOf('/');
            if (index != -1) {
                address = address.substring(index + 1);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Creating connector for address='" + ((address == null) ? "ALL" : address) + "' port='" + port + "' protocol='" + protocol + "'");
        }
        try {
            if (protocol.equals("ajp")) {
                connector = new Connector("org.apache.coyote.ajp.AjpProtocol");
            } else if (protocol.equals("memory")) {
                connector = new Connector("org.apache.coyote.memory.MemoryProtocolHandler");
            } else if (protocol.equals("http")) {
                connector = new Connector();
            } else if (protocol.equals("https")) {
                connector = new Connector();
                connector.setScheme("https");
                connector.setSecure(true);
                connector.setProperty("SSLEnabled", "true");
            // FIXME !!!! SET SSL PROPERTIES
            } else {
                connector = new Connector(protocol);
            }
            if (address != null) {
                IntrospectionUtils.setProperty(connector, "address", "" + address);
            }
            IntrospectionUtils.setProperty(connector, "port", "" + port);
        } catch (Exception e) {
            log.error("Couldn't create connector.");
        }
        return (connector);
    }

    /**
     * Create, configure, and return a Context that will process all
     * HTTP requests received from one of the replacedociated Connectors,
     * and directed to the specified context path on the virtual host
     * to which this Context is connected.
     * <p>
     * After you have customized the properties, listeners, and Valves
     * for this Context, you must attach it to the corresponding Host
     * by calling:
     * <pre>
     *   host.addChild(context);
     * </pre>
     * which will also cause the Context to be started if the Host has
     * already been started.
     *
     * @param path Context path of this application ("" for the default
     *  application for this host, must start with a slash otherwise)
     * @param docBase Absolute pathname to the doreplacedent base directory
     *  for this web application
     *
     * @exception IllegalArgumentException if an invalid parameter
     *  is specified
     */
    public Context createContext(String path, String docBase) {
        if (log.isDebugEnabled())
            log.debug("Creating context '" + path + "' with docBase '" + docBase + "'");
        StandardContext context = new StandardContext();
        context.setDocBase(docBase);
        context.setPath(path);
        ContextConfig config = new ContextConfig();
        config.setCustomAuthenticators(authenticators);
        context.addLifecycleListener(config);
        return (context);
    }

    /**
     * Create, configure, and return an Engine that will process all
     * HTTP requests received from one of the replacedociated Connectors,
     * based on the specified properties.
     */
    public Engine createEngine() {
        if (log.isDebugEnabled())
            log.debug("Creating engine");
        StandardEngine engine = new StandardEngine();
        // Default host will be set to the first host added
        // Inherited by all children
        engine.setRealm(realm);
        return (engine);
    }

    /**
     * Create, configure, and return a Host that will process all
     * HTTP requests received from one of the replacedociated Connectors,
     * and directed to the specified virtual host.
     * <p>
     * After you have customized the properties, listeners, and Valves
     * for this Host, you must attach it to the corresponding Engine
     * by calling:
     * <pre>
     *   engine.addChild(host);
     * </pre>
     * which will also cause the Host to be started if the Engine has
     * already been started.  If this is the default (or only) Host you
     * will be defining, you may also tell the Engine to preplaced all requests
     * not replacedigned to another virtual host to this one:
     * <pre>
     *   engine.setDefaultHost(host.getName());
     * </pre>
     *
     * @param name Canonical name of this virtual host
     * @param appBase Absolute pathname to the application base directory
     *  for this virtual host
     *
     * @exception IllegalArgumentException if an invalid parameter
     *  is specified
     */
    public Host createHost(String name, String appBase) {
        if (log.isDebugEnabled())
            log.debug("Creating host '" + name + "' with appBase '" + appBase + "'");
        StandardHost host = new StandardHost();
        host.setAppBase(appBase);
        host.setName(name);
        return (host);
    }

    /**
     * Create and return a clreplaced loader manager that can be customized, and
     * then attached to a Context, before it is started.
     *
     * @param parent ClreplacedLoader that will be the parent of the one
     *  created by this Loader
     */
    public Loader createLoader(ClreplacedLoader parent) {
        if (log.isDebugEnabled())
            log.debug("Creating Loader with parent clreplaced loader '" + parent + "'");
        WebappLoader loader = new WebappLoader(parent);
        return (loader);
    }

    /**
     * Return descriptive information about this Server implementation and
     * the corresponding version number, in the format
     * <code><description>/<version></code>.
     */
    @Override
    public String getInfo() {
        return (info);
    }

    /**
     * Remove the specified Context from the set of defined Contexts for its
     * replacedociated Host.  If this is the last Context for this Host, the Host
     * will also be removed.
     *
     * @param context The Context to be removed
     */
    public synchronized void removeContext(Context context) {
        if (log.isDebugEnabled())
            log.debug("Removing context[" + context.getName() + "]");
        // Is this Context actually among those that are defined?
        boolean found = false;
        for (int i = 0; i < engines.length; i++) {
            Container[] hosts = engines[i].findChildren();
            for (int j = 0; j < hosts.length; j++) {
                Container[] contexts = hosts[j].findChildren();
                for (int k = 0; k < contexts.length; k++) {
                    if (context == (Context) contexts[k]) {
                        found = true;
                        break;
                    }
                }
                if (found)
                    break;
            }
            if (found)
                break;
        }
        if (!found)
            return;
        // Remove this Context from the replacedociated Host
        if (log.isDebugEnabled())
            log.debug(" Removing this Context");
        context.getParent().removeChild(context);
    }

    /**
     * Remove the specified Engine from the set of defined Engines, along with
     * all of its related Hosts and Contexts.  All replacedociated Connectors are
     * also removed.
     *
     * @param engine The Engine to be removed
     */
    public synchronized void removeEngine(Engine engine) {
        if (log.isDebugEnabled())
            log.debug("Removing engine (" + engine.getInfo() + ")");
        // Is the specified Engine actually defined?
        int j = -1;
        for (int i = 0; i < engines.length; i++) {
            if (engine == engines[i]) {
                j = i;
                break;
            }
        }
        if (j < 0)
            return;
        // Remove any Connector that is using this Engine
        if (log.isDebugEnabled())
            log.debug(" Removing related Containers");
        while (true) {
            int n = -1;
            for (int i = 0; i < connectors.length; i++) {
                if (connectors[i].getService().getContainer() == engine) {
                    n = i;
                    break;
                }
            }
            if (n < 0)
                break;
            removeConnector(connectors[n]);
        }
        // Stop this Engine if necessary
        if (log.isDebugEnabled())
            log.debug(" Stopping this Engine");
        try {
            engine.stop();
        } catch (LifecycleException e) {
            log.error("Engine.stop", e);
        }
        // Remove this Engine from our set of defined Engines
        if (log.isDebugEnabled())
            log.debug(" Removing this Engine");
        int k = 0;
        Engine[] results = new Engine[engines.length - 1];
        for (int i = 0; i < engines.length; i++) {
            if (i != j)
                results[k++] = engines[i];
        }
        engines = results;
    }

    /**
     * Remove the specified Host, along with all of its related Contexts,
     * from the set of defined Hosts for its replacedociated Engine.  If this is
     * the last Host for this Engine, the Engine will also be removed.
     *
     * @param host The Host to be removed
     */
    public synchronized void removeHost(Host host) {
        if (log.isDebugEnabled())
            log.debug("Removing host[" + host.getName() + "]");
        // Is this Host actually among those that are defined?
        boolean found = false;
        for (int i = 0; i < engines.length; i++) {
            Container[] hosts = engines[i].findChildren();
            for (int j = 0; j < hosts.length; j++) {
                if (host == (Host) hosts[j]) {
                    found = true;
                    break;
                }
            }
            if (found)
                break;
        }
        if (!found)
            return;
        // Remove this Host from the replacedociated Engine
        if (log.isDebugEnabled())
            log.debug(" Removing this Host");
        host.getParent().removeChild(host);
    }

    /*
     * Maps the specified login method to the specified authenticator, allowing
     * the mappings in org/apache/catalina/startup/Authenticators.properties
     * to be overridden.
     *
     * @param authenticator Authenticator to handle authentication for the
     * specified login method
     * @param loginMethod Login method that maps to the specified authenticator
     *
     * @throws IllegalArgumentException if the specified authenticator does not
     * implement the org.apache.catalina.Valve interface
     */
    public void addAuthenticator(Authenticator authenticator, String loginMethod) {
        if (!(authenticator instanceof Valve)) {
            throw new IllegalArgumentException(sm.getString("embedded.authenticatorNotInstanceOfValve"));
        }
        if (authenticators == null) {
            synchronized (this) {
                if (authenticators == null) {
                    authenticators = new HashMap<String, Authenticator>();
                }
            }
        }
        authenticators.put(loginMethod, authenticator);
    }

    // ------------------------------------------------------ Lifecycle Methods
    /**
     * Start nested components ({@link Connector}s and {@link Engine}s) and
     * implement the requirements of
     * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    @Override
    protected void startInternal() throws LifecycleException {
        if (log.isInfoEnabled())
            log.info("Starting tomcat server");
        // Validate the setup of our required system properties
        initDirs();
        // Initialize some naming specific properties
        initNaming();
        setState(LifecycleState.STARTING);
        // Start our defined Engines first
        for (int i = 0; i < engines.length; i++) {
            engines[i].start();
        }
        // Start our defined Connectors second
        for (int i = 0; i < connectors.length; i++) {
            ((Lifecycle) connectors[i]).start();
        }
    }

    /**
     * Stop nested components ({@link Connector}s and {@link Engine}s) and
     * implement the requirements of
     * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that needs to be reported
     */
    @Override
    protected void stopInternal() throws LifecycleException {
        if (log.isDebugEnabled())
            log.debug("Stopping embedded server");
        setState(LifecycleState.STOPPING);
        // Stop our defined Connectors first
        for (int i = 0; i < connectors.length; i++) {
            ((Lifecycle) connectors[i]).stop();
        }
        // Stop our defined Engines second
        for (int i = 0; i < engines.length; i++) {
            engines[i].stop();
        }
    }

    // ------------------------------------------------------ Protected Methods
    /**
     * Initialize naming - this should only enable java:env and root naming.
     * If tomcat is embedded in an application that already defines those -
     * it shouldn't do it.
     *
     * XXX The 2 should be separated, you may want to enable java: but not
     * the initial context and the reverse
     * XXX Can we "guess" - i.e. lookup java: and if something is returned replacedume
     * false ?
     * XXX We have a major problem with the current setting for java: url
     */
    protected void initNaming() {
        // Setting additional variables
        if (!useNaming) {
            log.info("Catalina naming disabled");
            System.setProperty("catalina.useNaming", "false");
        } else {
            System.setProperty("catalina.useNaming", "true");
            String value = "org.apache.naming";
            String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
            if (oldValue != null) {
                value = value + ":" + oldValue;
            }
            System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
            if (log.isDebugEnabled())
                log.debug("Setting naming prefix=" + value);
            value = System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
            if (value == null) {
                System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
            } else {
                log.debug("INITIAL_CONTEXT_FACTORY already set " + value);
            }
        }
    }

    protected void initDirs() {
        String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP);
        if (catalinaHome == null) {
            // Backwards compatibility patch for J2EE RI 1.3
            String j2eeHome = System.getProperty("com.sun.enterprise.home");
            if (j2eeHome != null) {
                catalinaHome = System.getProperty("com.sun.enterprise.home");
            } else if (System.getProperty(Globals.CATALINA_BASE_PROP) != null) {
                catalinaHome = System.getProperty(Globals.CATALINA_BASE_PROP);
            } else {
                // Use IntrospectionUtils and guess the dir
                catalinaHome = IntrospectionUtils.guessInstall(Globals.CATALINA_HOME_PROP, Globals.CATALINA_BASE_PROP, "catalina.jar");
                if (catalinaHome == null) {
                    catalinaHome = IntrospectionUtils.guessInstall("tomcat.install", Globals.CATALINA_HOME_PROP, "tomcat.jar");
                }
            }
        }
        // last resort - for minimal/embedded cases.
        if (catalinaHome == null) {
            catalinaHome = System.getProperty("user.dir");
        }
        if (catalinaHome != null) {
            File home = new File(catalinaHome);
            if (!home.isAbsolute()) {
                try {
                    catalinaHome = home.getCanonicalPath();
                } catch (IOException e) {
                    catalinaHome = home.getAbsolutePath();
                }
            }
            System.setProperty(Globals.CATALINA_HOME_PROP, catalinaHome);
        }
        if (System.getProperty(Globals.CATALINA_BASE_PROP) == null) {
            System.setProperty(Globals.CATALINA_BASE_PROP, catalinaHome);
        } else {
            String catalinaBase = System.getProperty(Globals.CATALINA_BASE_PROP);
            File base = new File(catalinaBase);
            if (!base.isAbsolute()) {
                try {
                    catalinaBase = base.getCanonicalPath();
                } catch (IOException e) {
                    catalinaBase = base.getAbsolutePath();
                }
            }
            System.setProperty(Globals.CATALINA_BASE_PROP, catalinaBase);
        }
        String temp = System.getProperty("java.io.tmpdir");
        if (temp == null || (!(new File(temp)).exists()) || (!(new File(temp)).isDirectory())) {
            log.error(sm.getString("embedded.notmp", temp));
        }
    }

    protected void initStreams() {
        if (redirectStreams) {
            // Replace System.out and System.err with a custom PrintStream
            System.setOut(new SystemLogHandler(System.out));
            System.setErr(new SystemLogHandler(System.err));
        }
    }

    // -------------------------------------------------------- Private Methods
    /**
     * Set the security package access/protection.
     */
    protected void setSecurityProtection() {
        SecurityConfig securityConfig = SecurityConfig.newInstance();
        securityConfig.setPackageDefinition();
        securityConfig.setPackageAccess();
    }
}

18 Source : CombinedRealm.java
with Apache License 2.0
from wangyingjie

/**
 * Delegate the backgroundProcess call to all sub-realms.
 */
@Override
public void backgroundProcess() {
    super.backgroundProcess();
    for (Realm r : realms) {
        r.backgroundProcess();
    }
}

18 Source : CombinedRealm.java
with Apache License 2.0
from wangyingjie

/**
 * Add a realm to the list of realms that will be used to authenticate
 * users.
 */
public void addRealm(Realm theRealm) {
    realms.add(theRealm);
    if (log.isDebugEnabled()) {
        sm.getString("combinedRealm.addRealm", theRealm.getInfo(), Integer.toString(realms.size()));
    }
}

18 Source : CombinedRealm.java
with Apache License 2.0
from wangyingjie

/**
 * Return the set of Realms that this Realm is wrapping
 */
public ObjectName[] getRealms() {
    ObjectName[] result = new ObjectName[realms.size()];
    for (Realm realm : realms) {
        if (realm instanceof RealmBase) {
            result[realms.indexOf(realm)] = ((RealmBase) realm).getObjectName();
        }
    }
    return result;
}

18 Source : SerializablePrincipal.java
with Apache License 2.0
from wangyingjie

/**
 * Generic implementation of <strong>java.security.Principal</strong> that
 * is available for use by <code>Realm</code> implementations.
 * The GenericPrincipal does NOT implement serializable and I didn't want to
 * change that implementation hence I implemented this one instead.
 * @author Filip Hanik
 */
public clreplaced SerializablePrincipal implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(SerializablePrincipal.clreplaced);

    /**
     * The string manager for this package.
     */
    protected static final StringManager sm = StringManager.getManager(Constants.Package);

    // ----------------------------------------------------------- Constructors
    public SerializablePrincipal() {
        super();
    }

    /**
     * Construct a new Principal, replacedociated with the specified Realm, for the
     * specified username and preplacedword.
     *
     * @param name The username of the user represented by this Principal
     * @param preplacedword Credentials used to authenticate this user
     */
    public SerializablePrincipal(String name, String preplacedword) {
        this(name, preplacedword, null);
    }

    /**
     * Construct a new Principal, replacedociated with the specified Realm, for the
     * specified username and preplacedword, with the specified role names
     * (as Strings).
     *
     * @param name The username of the user represented by this Principal
     * @param preplacedword Credentials used to authenticate this user
     * @param roles List of roles (must be Strings) possessed by this user
     */
    public SerializablePrincipal(String name, String preplacedword, List<String> roles) {
        this(name, preplacedword, roles, null);
    }

    /**
     * Construct a new Principal, replacedociated with the specified Realm, for the
     * specified username and preplacedword, with the specified role names
     * (as Strings).
     *
     * @param name The username of the user represented by this Principal
     * @param preplacedword Credentials used to authenticate this user
     * @param roles List of roles (must be Strings) possessed by this user
     * @param userPrincipal The user principal to be exposed to applications
     */
    public SerializablePrincipal(String name, String preplacedword, List<String> roles, Principal userPrincipal) {
        super();
        this.name = name;
        this.preplacedword = preplacedword;
        if (roles != null) {
            this.roles = new String[roles.size()];
            this.roles = roles.toArray(this.roles);
            if (this.roles.length > 1)
                Arrays.sort(this.roles);
        }
        if (userPrincipal instanceof Serializable) {
            this.userPrincipal = userPrincipal;
        }
    }

    // ------------------------------------------------------------- Properties
    /**
     * The username of the user represented by this Principal.
     */
    protected String name = null;

    public String getName() {
        return (this.name);
    }

    /**
     * The authentication credentials for the user represented by
     * this Principal.
     */
    protected String preplacedword = null;

    public String getPreplacedword() {
        return (this.preplacedword);
    }

    /**
     * The Realm with which this Principal is replacedociated.
     */
    protected transient Realm realm = null;

    public Realm getRealm() {
        return (this.realm);
    }

    public void setRealm(Realm realm) {
        this.realm = realm;
    }

    /**
     * The set of roles replacedociated with this user.
     */
    protected String[] roles = new String[0];

    public String[] getRoles() {
        return (this.roles);
    }

    /**
     * The user principal, if present.
     */
    protected Principal userPrincipal = null;

    // --------------------------------------------------------- Public Methods
    /**
     * Return a String representation of this object, which exposes only
     * information that should be public.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("SerializablePrincipal[");
        sb.append(this.name);
        sb.append("]");
        return (sb.toString());
    }

    public static SerializablePrincipal createPrincipal(GenericPrincipal principal) {
        if (principal == null)
            return null;
        return new SerializablePrincipal(principal.getName(), principal.getPreplacedword(), principal.getRoles() != null ? Arrays.asList(principal.getRoles()) : null, principal.getUserPrincipal() != principal ? principal.getUserPrincipal() : null);
    }

    public GenericPrincipal getPrincipal() {
        return new GenericPrincipal(name, preplacedword, getRoles() != null ? Arrays.asList(getRoles()) : null, userPrincipal);
    }

    public static GenericPrincipal readPrincipal(ObjectInput in) throws IOException, ClreplacedNotFoundException {
        String name = in.readUTF();
        boolean hasPwd = in.readBoolean();
        String pwd = null;
        if (hasPwd)
            pwd = in.readUTF();
        int size = in.readInt();
        String[] roles = new String[size];
        for (int i = 0; i < size; i++) roles[i] = in.readUTF();
        Principal userPrincipal = null;
        boolean hasUserPrincipal = in.readBoolean();
        if (hasUserPrincipal) {
            try {
                userPrincipal = (Principal) in.readObject();
            } catch (ClreplacedNotFoundException e) {
                log.error(sm.getString("serializablePrincipal.readPrincipal.cnfe"), e);
                throw e;
            }
        }
        return new GenericPrincipal(name, pwd, Arrays.asList(roles), userPrincipal);
    }

    public static void writePrincipal(GenericPrincipal p, ObjectOutput out) throws IOException {
        out.writeUTF(p.getName());
        out.writeBoolean(p.getPreplacedword() != null);
        if (p.getPreplacedword() != null)
            out.writeUTF(p.getPreplacedword());
        String[] roles = p.getRoles();
        if (roles == null)
            roles = new String[0];
        out.writeInt(roles.length);
        for (int i = 0; i < roles.length; i++) out.writeUTF(roles[i]);
        boolean hasUserPrincipal = (p != p.getUserPrincipal() && p.getUserPrincipal() instanceof Serializable);
        out.writeBoolean(hasUserPrincipal);
        if (hasUserPrincipal)
            out.writeObject(p.getUserPrincipal());
    }
}

18 Source : 830.java
with MIT License
from masud-technope

@Deprecated
public clreplaced Embedded extends StandardService {

    private static final Log log = LogFactory.getLog(Embedded.clreplaced);

    /**
     * Construct a new instance of this clreplaced with default properties.
     */
    public Embedded() {
        this(null);
    }

    /**
     * Construct a new instance of this clreplaced with specified properties.
     *
     * @param realm Realm implementation to be inherited by all components
     *  (unless overridden further down the container hierarchy)
     */
    public Embedded(Realm realm) {
        super();
        setRealm(realm);
        setSecurityProtection();
    }

    // ----------------------------------------------------- Instance Variables
    /**
     * Is naming enabled ?
     */
    protected boolean useNaming = true;

    /**
     * Is standard streams redirection enabled ?
     */
    protected boolean redirectStreams = true;

    /**
     * The set of Engines that have been deployed in this server.  Normally
     * there will only be one.
     */
    protected Engine[] engines = new Engine[0];

    /**
     * Custom mappings of login methods to authenticators
     */
    protected volatile HashMap<String, Authenticator> authenticators;

    /**
     * Descriptive information about this server implementation.
     */
    protected static final String info = "org.apache.catalina.startup.Embedded/1.0";

    /**
     * The default realm to be used by all containers replacedociated with
     * this component.
     */
    protected Realm realm = null;

    /**
     * The string manager for this package.
     */
    protected static final StringManager sm = StringManager.getManager(Constants.Package);

    /**
     * Use await.
     */
    protected boolean await = false;

    // ------------------------------------------------------------- Properties
    /**
     * Return true if naming is enabled.
     */
    public boolean isUseNaming() {
        return (this.useNaming);
    }

    /**
     * Enables or disables naming support.
     *
     * @param useNaming The new use naming value
     */
    public void setUseNaming(boolean useNaming) {
        boolean oldUseNaming = this.useNaming;
        this.useNaming = useNaming;
        support.firePropertyChange("useNaming", Boolean.valueOf(oldUseNaming), Boolean.valueOf(this.useNaming));
    }

    /**
     * Return true if redirection of standard streams is enabled.
     */
    public boolean isRedirectStreams() {
        return (this.redirectStreams);
    }

    /**
     * Enables or disables redirection.
     *
     * @param redirectStreams The new redirection value
     */
    public void setRedirectStreams(boolean redirectStreams) {
        boolean oldRedirectStreams = this.redirectStreams;
        this.redirectStreams = redirectStreams;
        support.firePropertyChange("redirectStreams", Boolean.valueOf(oldRedirectStreams), Boolean.valueOf(this.redirectStreams));
    }

    /**
     * Return the default Realm for our Containers.
     */
    public Realm getRealm() {
        return (this.realm);
    }

    /**
     * Set the default Realm for our Containers.
     *
     * @param realm The new default realm
     */
    public void setRealm(Realm realm) {
        Realm oldRealm = this.realm;
        this.realm = realm;
        support.firePropertyChange("realm", oldRealm, this.realm);
    }

    public void setAwait(boolean b) {
        await = b;
    }

    public boolean isAwait() {
        return await;
    }

    public void setCatalinaHome(String s) {
        System.setProperty(Globals.CATALINA_HOME_PROP, s);
    }

    public void setCatalinaBase(String s) {
        System.setProperty(Globals.CATALINA_BASE_PROP, s);
    }

    public String getCatalinaHome() {
        return System.getProperty(Globals.CATALINA_HOME_PROP);
    }

    public String getCatalinaBase() {
        return System.getProperty(Globals.CATALINA_BASE_PROP);
    }

    // --------------------------------------------------------- Public Methods
    /**
     * Add a new Connector to the set of defined Connectors.  The newly
     * added Connector will be replacedociated with the most recently added Engine.
     *
     * @param connector The connector to be added
     *
     * @exception IllegalStateException if no engines have been added yet
     */
    @Override
    public synchronized void addConnector(Connector connector) {
        if (log.isDebugEnabled()) {
            log.debug("Adding connector (" + connector.getInfo() + ")");
        }
        // Make sure we have a Container to send requests to
        if (engines.length < 1)
            throw new IllegalStateException(sm.getString("embedded.noEngines"));
        /*
         * Add the connector. This will set the connector's container to the
         * most recently added Engine
         */
        super.addConnector(connector);
    }

    /**
     * Add a new Engine to the set of defined Engines.
     *
     * @param engine The engine to be added
     */
    public synchronized void addEngine(Engine engine) {
        if (log.isDebugEnabled())
            log.debug("Adding engine (" + engine.getInfo() + ")");
        // Add this Engine to our set of defined Engines
        Engine[] results = new Engine[engines.length + 1];
        for (int i = 0; i < engines.length; i++) results[i] = engines[i];
        results[engines.length] = engine;
        engines = results;
        // Start this Engine if necessary
        if (getState().isAvailable()) {
            try {
                engine.start();
            } catch (LifecycleException e) {
                log.error("Engine.start", e);
            }
        }
        this.container = engine;
    }

    /**
     * Create, configure, and return a new TCP/IP socket connector
     * based on the specified properties.
     *
     * @param address InetAddress to bind to, or <code>null</code> if the
     * connector is supposed to bind to all addresses on this server
     * @param port Port number to listen to
     * @param secure true if the generated connector is supposed to be
     * SSL-enabled, and false otherwise
     */
    public Connector createConnector(InetAddress address, int port, boolean secure) {
        return createConnector(address != null ? address.toString() : null, port, secure);
    }

    public Connector createConnector(String address, int port, boolean secure) {
        String protocol = "http";
        if (secure) {
            protocol = "https";
        }
        return createConnector(address, port, protocol);
    }

    public Connector createConnector(InetAddress address, int port, String protocol) {
        return createConnector(address != null ? address.toString() : null, port, protocol);
    }

    public Connector createConnector(String address, int port, String protocol) {
        Connector connector = null;
        if (address != null) {
            /*
             * InetAddress.toString() returns a string of the form
             * "<hostname>/<literal_IP>". Get the latter part, so that the
             * address can be parsed (back) into an InetAddress using
             * InetAddress.getByName().
             */
            int index = address.indexOf('/');
            if (index != -1) {
                address = address.substring(index + 1);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Creating connector for address='" + ((address == null) ? "ALL" : address) + "' port='" + port + "' protocol='" + protocol + "'");
        }
        try {
            if (protocol.equals("ajp")) {
                connector = new Connector("org.apache.coyote.ajp.AjpProtocol");
            } else if (protocol.equals("memory")) {
                connector = new Connector("org.apache.coyote.memory.MemoryProtocolHandler");
            } else if (protocol.equals("http")) {
                connector = new Connector();
            } else if (protocol.equals("https")) {
                connector = new Connector();
                connector.setScheme("https");
                connector.setSecure(true);
                connector.setProperty("SSLEnabled", "true");
            // FIXME !!!! SET SSL PROPERTIES
            } else {
                connector = new Connector(protocol);
            }
            if (address != null) {
                IntrospectionUtils.setProperty(connector, "address", "" + address);
            }
            IntrospectionUtils.setProperty(connector, "port", "" + port);
        } catch (Exception e) {
            log.error("Couldn't create connector.");
        }
        return (connector);
    }

    /**
     * Create, configure, and return a Context that will process all
     * HTTP requests received from one of the replacedociated Connectors,
     * and directed to the specified context path on the virtual host
     * to which this Context is connected.
     * <p>
     * After you have customized the properties, listeners, and Valves
     * for this Context, you must attach it to the corresponding Host
     * by calling:
     * <pre>
     *   host.addChild(context);
     * </pre>
     * which will also cause the Context to be started if the Host has
     * already been started.
     *
     * @param path Context path of this application ("" for the default
     *  application for this host, must start with a slash otherwise)
     * @param docBase Absolute pathname to the doreplacedent base directory
     *  for this web application
     *
     * @exception IllegalArgumentException if an invalid parameter
     *  is specified
     */
    public Context createContext(String path, String docBase) {
        if (log.isDebugEnabled())
            log.debug("Creating context '" + path + "' with docBase '" + docBase + "'");
        StandardContext context = new StandardContext();
        context.setDocBase(docBase);
        context.setPath(path);
        ContextConfig config = new ContextConfig();
        config.setCustomAuthenticators(authenticators);
        context.addLifecycleListener(config);
        return (context);
    }

    /**
     * Create, configure, and return an Engine that will process all
     * HTTP requests received from one of the replacedociated Connectors,
     * based on the specified properties.
     */
    public Engine createEngine() {
        if (log.isDebugEnabled())
            log.debug("Creating engine");
        StandardEngine engine = new StandardEngine();
        // Default host will be set to the first host added
        // Inherited by all children
        engine.setRealm(realm);
        return (engine);
    }

    /**
     * Create, configure, and return a Host that will process all
     * HTTP requests received from one of the replacedociated Connectors,
     * and directed to the specified virtual host.
     * <p>
     * After you have customized the properties, listeners, and Valves
     * for this Host, you must attach it to the corresponding Engine
     * by calling:
     * <pre>
     *   engine.addChild(host);
     * </pre>
     * which will also cause the Host to be started if the Engine has
     * already been started.  If this is the default (or only) Host you
     * will be defining, you may also tell the Engine to preplaced all requests
     * not replacedigned to another virtual host to this one:
     * <pre>
     *   engine.setDefaultHost(host.getName());
     * </pre>
     *
     * @param name Canonical name of this virtual host
     * @param appBase Absolute pathname to the application base directory
     *  for this virtual host
     *
     * @exception IllegalArgumentException if an invalid parameter
     *  is specified
     */
    public Host createHost(String name, String appBase) {
        if (log.isDebugEnabled())
            log.debug("Creating host '" + name + "' with appBase '" + appBase + "'");
        StandardHost host = new StandardHost();
        host.setAppBase(appBase);
        host.setName(name);
        return (host);
    }

    /**
     * Create and return a clreplaced loader manager that can be customized, and
     * then attached to a Context, before it is started.
     *
     * @param parent ClreplacedLoader that will be the parent of the one
     *  created by this Loader
     */
    public Loader createLoader(ClreplacedLoader parent) {
        if (log.isDebugEnabled())
            log.debug("Creating Loader with parent clreplaced loader '" + parent + "'");
        WebappLoader loader = new WebappLoader(parent);
        return (loader);
    }

    /**
     * Return descriptive information about this Server implementation and
     * the corresponding version number, in the format
     * <code><description>/<version></code>.
     */
    @Override
    public String getInfo() {
        return (info);
    }

    /**
     * Remove the specified Context from the set of defined Contexts for its
     * replacedociated Host.  If this is the last Context for this Host, the Host
     * will also be removed.
     *
     * @param context The Context to be removed
     */
    public synchronized void removeContext(Context context) {
        if (log.isDebugEnabled())
            log.debug("Removing context[" + context.getName() + "]");
        // Is this Context actually among those that are defined?
        boolean found = false;
        for (int i = 0; i < engines.length; i++) {
            Container[] hosts = engines[i].findChildren();
            for (int j = 0; j < hosts.length; j++) {
                Container[] contexts = hosts[j].findChildren();
                for (int k = 0; k < contexts.length; k++) {
                    if (context == (Context) contexts[k]) {
                        found = true;
                        break;
                    }
                }
                if (found)
                    break;
            }
            if (found)
                break;
        }
        if (!found)
            return;
        // Remove this Context from the replacedociated Host
        if (log.isDebugEnabled())
            log.debug(" Removing this Context");
        context.getParent().removeChild(context);
    }

    /**
     * Remove the specified Engine from the set of defined Engines, along with
     * all of its related Hosts and Contexts.  All replacedociated Connectors are
     * also removed.
     *
     * @param engine The Engine to be removed
     */
    public synchronized void removeEngine(Engine engine) {
        if (log.isDebugEnabled())
            log.debug("Removing engine (" + engine.getInfo() + ")");
        // Is the specified Engine actually defined?
        int j = -1;
        for (int i = 0; i < engines.length; i++) {
            if (engine == engines[i]) {
                j = i;
                break;
            }
        }
        if (j < 0)
            return;
        // Remove any Connector that is using this Engine
        if (log.isDebugEnabled())
            log.debug(" Removing related Containers");
        while (true) {
            int n = -1;
            for (int i = 0; i < connectors.length; i++) {
                if (connectors[i].getService().getContainer() == engine) {
                    n = i;
                    break;
                }
            }
            if (n < 0)
                break;
            removeConnector(connectors[n]);
        }
        // Stop this Engine if necessary
        if (log.isDebugEnabled())
            log.debug(" Stopping this Engine");
        try {
            engine.stop();
        } catch (LifecycleException e) {
            log.error("Engine.stop", e);
        }
        // Remove this Engine from our set of defined Engines
        if (log.isDebugEnabled())
            log.debug(" Removing this Engine");
        int k = 0;
        Engine[] results = new Engine[engines.length - 1];
        for (int i = 0; i < engines.length; i++) {
            if (i != j)
                results[k++] = engines[i];
        }
        engines = results;
    }

    /**
     * Remove the specified Host, along with all of its related Contexts,
     * from the set of defined Hosts for its replacedociated Engine.  If this is
     * the last Host for this Engine, the Engine will also be removed.
     *
     * @param host The Host to be removed
     */
    public synchronized void removeHost(Host host) {
        if (log.isDebugEnabled())
            log.debug("Removing host[" + host.getName() + "]");
        // Is this Host actually among those that are defined?
        boolean found = false;
        for (int i = 0; i < engines.length; i++) {
            Container[] hosts = engines[i].findChildren();
            for (int j = 0; j < hosts.length; j++) {
                if (host == (Host) hosts[j]) {
                    found = true;
                    break;
                }
            }
            if (found)
                break;
        }
        if (!found)
            return;
        // Remove this Host from the replacedociated Engine
        if (log.isDebugEnabled())
            log.debug(" Removing this Host");
        host.getParent().removeChild(host);
    }

    /*
     * Maps the specified login method to the specified authenticator, allowing
     * the mappings in org/apache/catalina/startup/Authenticators.properties
     * to be overridden.
     *
     * @param authenticator Authenticator to handle authentication for the
     * specified login method
     * @param loginMethod Login method that maps to the specified authenticator
     *
     * @throws IllegalArgumentException if the specified authenticator does not
     * implement the org.apache.catalina.Valve interface
     */
    public void addAuthenticator(Authenticator authenticator, String loginMethod) {
        if (!(authenticator instanceof Valve)) {
            throw new IllegalArgumentException(sm.getString("embedded.authenticatorNotInstanceOfValve"));
        }
        if (authenticators == null) {
            synchronized (this) {
                if (authenticators == null) {
                    authenticators = new HashMap<String, Authenticator>();
                }
            }
        }
        authenticators.put(loginMethod, authenticator);
    }

    // ------------------------------------------------------ Lifecycle Methods
    /**
     * Start nested components ({@link Connector}s and {@link Engine}s) and
     * implement the requirements of
     * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    @Override
    protected void startInternal() throws LifecycleException {
        if (log.isInfoEnabled())
            log.info("Starting tomcat server");
        // Validate the setup of our required system properties
        initDirs();
        // Initialize some naming specific properties
        initNaming();
        setState(LifecycleState.STARTING);
        // Start our defined Engines first
        for (int i = 0; i < engines.length; i++) {
            engines[i].start();
        }
        // Start our defined Connectors second
        for (int i = 0; i < connectors.length; i++) {
            ((Lifecycle) connectors[i]).start();
        }
    }

    /**
     * Stop nested components ({@link Connector}s and {@link Engine}s) and
     * implement the requirements of
     * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that needs to be reported
     */
    @Override
    protected void stopInternal() throws LifecycleException {
        if (log.isDebugEnabled())
            log.debug("Stopping embedded server");
        setState(LifecycleState.STOPPING);
        // Stop our defined Connectors first
        for (int i = 0; i < connectors.length; i++) {
            ((Lifecycle) connectors[i]).stop();
        }
        // Stop our defined Engines second
        for (int i = 0; i < engines.length; i++) {
            engines[i].stop();
        }
    }

    // ------------------------------------------------------ Protected Methods
    /**
     * Initialize naming - this should only enable java:env and root naming.
     * If tomcat is embedded in an application that already defines those -
     * it shouldn't do it.
     *
     * XXX The 2 should be separated, you may want to enable java: but not
     * the initial context and the reverse
     * XXX Can we "guess" - i.e. lookup java: and if something is returned replacedume
     * false ?
     * XXX We have a major problem with the current setting for java: url
     */
    protected void initNaming() {
        // Setting additional variables
        if (!useNaming) {
            log.info("Catalina naming disabled");
            System.setProperty("catalina.useNaming", "false");
        } else {
            System.setProperty("catalina.useNaming", "true");
            String value = "org.apache.naming";
            String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
            if (oldValue != null) {
                value = value + ":" + oldValue;
            }
            System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
            if (log.isDebugEnabled())
                log.debug("Setting naming prefix=" + value);
            value = System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
            if (value == null) {
                System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
            } else {
                log.debug("INITIAL_CONTEXT_FACTORY already set " + value);
            }
        }
    }

    protected void initDirs() {
        String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP);
        if (catalinaHome == null) {
            // Backwards compatibility patch for J2EE RI 1.3
            String j2eeHome = System.getProperty("com.sun.enterprise.home");
            if (j2eeHome != null) {
                catalinaHome = System.getProperty("com.sun.enterprise.home");
            } else if (System.getProperty(Globals.CATALINA_BASE_PROP) != null) {
                catalinaHome = System.getProperty(Globals.CATALINA_BASE_PROP);
            } else {
                // Use IntrospectionUtils and guess the dir
                catalinaHome = IntrospectionUtils.guessInstall(Globals.CATALINA_HOME_PROP, Globals.CATALINA_BASE_PROP, "catalina.jar");
                if (catalinaHome == null) {
                    catalinaHome = IntrospectionUtils.guessInstall("tomcat.install", Globals.CATALINA_HOME_PROP, "tomcat.jar");
                }
            }
        }
        // last resort - for minimal/embedded cases.
        if (catalinaHome == null) {
            catalinaHome = System.getProperty("user.dir");
        }
        if (catalinaHome != null) {
            File home = new File(catalinaHome);
            if (!home.isAbsolute()) {
                try {
                    catalinaHome = home.getCanonicalPath();
                } catch (IOException e) {
                    catalinaHome = home.getAbsolutePath();
                }
            }
            System.setProperty(Globals.CATALINA_HOME_PROP, catalinaHome);
        }
        if (System.getProperty(Globals.CATALINA_BASE_PROP) == null) {
            System.setProperty(Globals.CATALINA_BASE_PROP, catalinaHome);
        } else {
            String catalinaBase = System.getProperty(Globals.CATALINA_BASE_PROP);
            File base = new File(catalinaBase);
            if (!base.isAbsolute()) {
                try {
                    catalinaBase = base.getCanonicalPath();
                } catch (IOException e) {
                    catalinaBase = base.getAbsolutePath();
                }
            }
            System.setProperty(Globals.CATALINA_BASE_PROP, catalinaBase);
        }
        String temp = System.getProperty("java.io.tmpdir");
        if (temp == null || (!(new File(temp)).exists()) || (!(new File(temp)).isDirectory())) {
            log.error(sm.getString("embedded.notmp", temp));
        }
    }

    protected void initStreams() {
        if (redirectStreams) {
            // Replace System.out and System.err with a custom PrintStream
            System.setOut(new SystemLogHandler(System.out));
            System.setErr(new SystemLogHandler(System.err));
        }
    }

    // -------------------------------------------------------- Private Methods
    /**
     * Set the security package access/protection.
     */
    protected void setSecurityProtection() {
        SecurityConfig securityConfig = SecurityConfig.newInstance();
        securityConfig.setPackageDefinition();
        securityConfig.setPackageAccess();
    }
}

18 Source : 134.java
with MIT License
from masud-technope

/**
 * Generic implementation of <strong>java.security.Principal</strong> that
 * is available for use by <code>Realm</code> implementations.
 * The GenericPrincipal does NOT implement serializable and I didn't want to
 * change that implementation hence I implemented this one instead.
 * @author Filip Hanik
 */
public clreplaced SerializablePrincipal implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(SerializablePrincipal.clreplaced);

    /**
     * The string manager for this package.
     */
    protected static final StringManager sm = StringManager.getManager(Constants.Package);

    public SerializablePrincipal() {
        super();
    }

    /**
     * Construct a new Principal, replacedociated with the specified Realm, for the
     * specified username and preplacedword.
     *
     * @param name The username of the user represented by this Principal
     * @param preplacedword Credentials used to authenticate this user
     */
    public SerializablePrincipal(String name, String preplacedword) {
        this(name, preplacedword, null);
    }

    /**
     * Construct a new Principal, replacedociated with the specified Realm, for the
     * specified username and preplacedword, with the specified role names
     * (as Strings).
     *
     * @param name The username of the user represented by this Principal
     * @param preplacedword Credentials used to authenticate this user
     * @param roles List of roles (must be Strings) possessed by this user
     */
    public SerializablePrincipal(String name, String preplacedword, List<String> roles) {
        this(name, preplacedword, roles, null);
    }

    /**
     * Construct a new Principal, replacedociated with the specified Realm, for the
     * specified username and preplacedword, with the specified role names
     * (as Strings).
     *
     * @param name The username of the user represented by this Principal
     * @param preplacedword Credentials used to authenticate this user
     * @param roles List of roles (must be Strings) possessed by this user
     * @param userPrincipal The user principal to be exposed to applications
     */
    public SerializablePrincipal(String name, String preplacedword, List<String> roles, Principal userPrincipal) {
        super();
        this.name = name;
        this.preplacedword = preplacedword;
        if (roles != null) {
            this.roles = new String[roles.size()];
            this.roles = roles.toArray(this.roles);
            if (this.roles.length > 1)
                Arrays.sort(this.roles);
        }
        if (userPrincipal instanceof Serializable) {
            this.userPrincipal = userPrincipal;
        }
    }

    // ------------------------------------------------------------- Properties
    /**
     * The username of the user represented by this Principal.
     */
    protected String name = null;

    public String getName() {
        return (this.name);
    }

    /**
     * The authentication credentials for the user represented by
     * this Principal.
     */
    protected String preplacedword = null;

    public String getPreplacedword() {
        return (this.preplacedword);
    }

    /**
     * The Realm with which this Principal is replacedociated.
     */
    protected transient Realm realm = null;

    public Realm getRealm() {
        return (this.realm);
    }

    public void setRealm(Realm realm) {
        this.realm = realm;
    }

    /**
     * The set of roles replacedociated with this user.
     */
    protected String[] roles = new String[0];

    public String[] getRoles() {
        return (this.roles);
    }

    /**
     * The user principal, if present.
     */
    protected Principal userPrincipal = null;

    // --------------------------------------------------------- Public Methods
    /**
     * Return a String representation of this object, which exposes only
     * information that should be public.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("SerializablePrincipal[");
        sb.append(this.name);
        sb.append("]");
        return (sb.toString());
    }

    public static SerializablePrincipal createPrincipal(GenericPrincipal principal) {
        if (principal == null)
            return null;
        return new SerializablePrincipal(principal.getName(), principal.getPreplacedword(), principal.getRoles() != null ? Arrays.asList(principal.getRoles()) : null, principal.getUserPrincipal() != principal ? principal.getUserPrincipal() : null);
    }

    public GenericPrincipal getPrincipal() {
        return new GenericPrincipal(name, preplacedword, getRoles() != null ? Arrays.asList(getRoles()) : null, userPrincipal);
    }

    public static GenericPrincipal readPrincipal(ObjectInput in) throws IOException, ClreplacedNotFoundException {
        String name = in.readUTF();
        boolean hasPwd = in.readBoolean();
        String pwd = null;
        if (hasPwd)
            pwd = in.readUTF();
        int size = in.readInt();
        String[] roles = new String[size];
        for (int i = 0; i < size; i++) roles[i] = in.readUTF();
        Principal userPrincipal = null;
        boolean hasUserPrincipal = in.readBoolean();
        if (hasUserPrincipal) {
            try {
                userPrincipal = (Principal) in.readObject();
            } catch (ClreplacedNotFoundException e) {
                log.error(sm.getString("serializablePrincipal.readPrincipal.cnfe"), e);
                throw e;
            }
        }
        return new GenericPrincipal(name, pwd, Arrays.asList(roles), userPrincipal);
    }

    public static void writePrincipal(GenericPrincipal p, ObjectOutput out) throws IOException {
        out.writeUTF(p.getName());
        out.writeBoolean(p.getPreplacedword() != null);
        if (p.getPreplacedword() != null)
            out.writeUTF(p.getPreplacedword());
        String[] roles = p.getRoles();
        if (roles == null)
            roles = new String[0];
        out.writeInt(roles.length);
        for (int i = 0; i < roles.length; i++) out.writeUTF(roles[i]);
        boolean hasUserPrincipal = (p != p.getUserPrincipal() && p.getUserPrincipal() instanceof Serializable);
        out.writeBoolean(hasUserPrincipal);
        if (hasUserPrincipal)
            out.writeObject(p.getUserPrincipal());
    }
}

18 Source : Embedded.java
with Apache License 2.0
from how2j

/**
 * Convenience clreplaced to embed a Catalina servlet container environment inside
 * another application. You must call the methods of this clreplaced in the following
 * order to ensure correct operation.
 *
 * <ul>
 * <li>Instantiate a new instance of this clreplaced.</li>
 * <li>Set the relevant properties of this object itself. In particular, you
 * will want to establish the default Logger to be used, as well as the default
 * Realm if you are using container-managed security.</li>
 * <li>Call <code>createEngine()</code> to create an Engine object, and then
 * call its property setters as desired.</li>
 * <li>Call <code>createHost()</code> to create at least one virtual Host
 * replacedociated with the newly created Engine, and then call its property setters
 * as desired. After you customize this Host, add it to the corresponding Engine
 * with <code>engine.addChild(host)</code>.</li>
 * <li>Call <code>createContext()</code> to create at least one Context
 * replacedociated with each newly created Host, and then call its property setters
 * as desired. You <strong>SHOULD</strong> create a Context with a pathname
 * equal to a zero-length string, which will be used to process all requests not
 * mapped to some other Context. After you customize this Context, add it to the
 * corresponding Host with <code>host.addChild(context)</code>.</li>
 * <li>Call <code>addEngine()</code> to attach this Engine to the set of defined
 * Engines for this object.</li>
 * <li>Call <code>createConnector()</code> to create at least one TCP/IP
 * connector, and then call its property setters as desired.</li>
 * <li>Call <code>addConnector()</code> to attach this Connector to the set of
 * defined Connectors for this object. The added Connector will use the most
 * recently added Engine to process its received requests.</li>
 * <li>Repeat the above series of steps as often as required (although there
 * will typically be only one Engine instance created).</li>
 * <li>Call <code>start()</code> to initiate normal operations of all the
 * attached components.</li>
 * </ul>
 *
 * After normal operations have begun, you can add and remove Connectors,
 * Engines, Hosts, and Contexts on the fly. However, once you have removed a
 * particular component, it must be thrown away -- you can create a new one with
 * the same characteristics if you merely want to do a restart.
 * <p>
 * To initiate a normal shutdown, call the <code>stop()</code> method of this
 * object.
 * <p>
 *
 * @see org.apache.catalina.startup.Bootstrap#main For a complete example of how
 *      Tomcat is set up and launched as an Embedded application.
 *
 * @author Craig R. McClanahan
 *
 * @deprecated Use {@link Tomcat} instead.
 */
@Deprecated
public clreplaced Embedded extends StandardService {

    private static final Log log = LogFactory.getLog(Embedded.clreplaced);

    // ----------------------------------------------------------- Constructors
    /**
     * Construct a new instance of this clreplaced with default properties.
     */
    public Embedded() {
        this(null);
    }

    /**
     * Construct a new instance of this clreplaced with specified properties.
     *
     * @param realm
     *            Realm implementation to be inherited by all components (unless
     *            overridden further down the container hierarchy)
     */
    public Embedded(Realm realm) {
        super();
        setRealm(realm);
        setSecurityProtection();
    }

    // ----------------------------------------------------- Instance Variables
    /**
     * Is naming enabled ?
     */
    protected boolean useNaming = true;

    /**
     * Is standard streams redirection enabled ?
     */
    protected boolean redirectStreams = true;

    /**
     * The set of Engines that have been deployed in this server. Normally there
     * will only be one.
     */
    protected Engine[] engines = new Engine[0];

    /**
     * Custom mappings of login methods to authenticators
     */
    protected volatile HashMap<String, Authenticator> authenticators;

    /**
     * Descriptive information about this server implementation.
     */
    protected static final String info = "org.apache.catalina.startup.Embedded/1.0";

    /**
     * The default realm to be used by all containers replacedociated with this
     * component.
     */
    protected Realm realm = null;

    /**
     * The string manager for this package.
     */
    protected static final StringManager sm = StringManager.getManager(Constants.Package);

    /**
     * Use await.
     */
    protected boolean await = false;

    // ------------------------------------------------------------- Properties
    /**
     * Return true if naming is enabled.
     */
    public boolean isUseNaming() {
        return (this.useNaming);
    }

    /**
     * Enables or disables naming support.
     *
     * @param useNaming
     *            The new use naming value
     */
    public void setUseNaming(boolean useNaming) {
        boolean oldUseNaming = this.useNaming;
        this.useNaming = useNaming;
        support.firePropertyChange("useNaming", Boolean.valueOf(oldUseNaming), Boolean.valueOf(this.useNaming));
    }

    /**
     * Return true if redirection of standard streams is enabled.
     */
    public boolean isRedirectStreams() {
        return (this.redirectStreams);
    }

    /**
     * Enables or disables redirection.
     *
     * @param redirectStreams
     *            The new redirection value
     */
    public void setRedirectStreams(boolean redirectStreams) {
        boolean oldRedirectStreams = this.redirectStreams;
        this.redirectStreams = redirectStreams;
        support.firePropertyChange("redirectStreams", Boolean.valueOf(oldRedirectStreams), Boolean.valueOf(this.redirectStreams));
    }

    /**
     * Return the default Realm for our Containers.
     */
    public Realm getRealm() {
        return (this.realm);
    }

    /**
     * Set the default Realm for our Containers.
     *
     * @param realm
     *            The new default realm
     */
    public void setRealm(Realm realm) {
        Realm oldRealm = this.realm;
        this.realm = realm;
        support.firePropertyChange("realm", oldRealm, this.realm);
    }

    public void setAwait(boolean b) {
        await = b;
    }

    public boolean isAwait() {
        return await;
    }

    public void setCatalinaHome(String s) {
        System.setProperty(Globals.CATALINA_HOME_PROP, s);
    }

    public void setCatalinaBase(String s) {
        System.setProperty(Globals.CATALINA_BASE_PROP, s);
    }

    public String getCatalinaHome() {
        return System.getProperty(Globals.CATALINA_HOME_PROP);
    }

    public String getCatalinaBase() {
        return System.getProperty(Globals.CATALINA_BASE_PROP);
    }

    // --------------------------------------------------------- Public Methods
    /**
     * Add a new Connector to the set of defined Connectors. The newly added
     * Connector will be replacedociated with the most recently added Engine.
     *
     * @param connector
     *            The connector to be added
     *
     * @exception IllegalStateException
     *                if no engines have been added yet
     */
    @Override
    public synchronized void addConnector(Connector connector) {
        if (log.isDebugEnabled()) {
            log.debug("Adding connector (" + connector.getInfo() + ")");
        }
        // Make sure we have a Container to send requests to
        if (engines.length < 1)
            throw new IllegalStateException(sm.getString("embedded.noEngines"));
        /*
		 * Add the connector. This will set the connector's container to the
		 * most recently added Engine
		 */
        super.addConnector(connector);
    }

    /**
     * Add a new Engine to the set of defined Engines.
     *
     * @param engine
     *            The engine to be added
     */
    public synchronized void addEngine(Engine engine) {
        if (log.isDebugEnabled())
            log.debug("Adding engine (" + engine.getInfo() + ")");
        // Add this Engine to our set of defined Engines
        Engine[] results = new Engine[engines.length + 1];
        for (int i = 0; i < engines.length; i++) results[i] = engines[i];
        results[engines.length] = engine;
        engines = results;
        // Start this Engine if necessary
        if (getState().isAvailable()) {
            try {
                engine.start();
            } catch (LifecycleException e) {
                log.error("Engine.start", e);
            }
        }
        this.container = engine;
    }

    /**
     * Create, configure, and return a new TCP/IP socket connector based on the
     * specified properties.
     *
     * @param address
     *            InetAddress to bind to, or <code>null</code> if the connector
     *            is supposed to bind to all addresses on this server
     * @param port
     *            Port number to listen to
     * @param secure
     *            true if the generated connector is supposed to be SSL-enabled,
     *            and false otherwise
     */
    public Connector createConnector(InetAddress address, int port, boolean secure) {
        return createConnector(address != null ? address.toString() : null, port, secure);
    }

    public Connector createConnector(String address, int port, boolean secure) {
        String protocol = "http";
        if (secure) {
            protocol = "https";
        }
        return createConnector(address, port, protocol);
    }

    public Connector createConnector(InetAddress address, int port, String protocol) {
        return createConnector(address != null ? address.toString() : null, port, protocol);
    }

    public Connector createConnector(String address, int port, String protocol) {
        Connector connector = null;
        if (address != null) {
            /*
			 * InetAddress.toString() returns a string of the form
			 * "<hostname>/<literal_IP>". Get the latter part, so that the
			 * address can be parsed (back) into an InetAddress using
			 * InetAddress.getByName().
			 */
            int index = address.indexOf('/');
            if (index != -1) {
                address = address.substring(index + 1);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Creating connector for address='" + ((address == null) ? "ALL" : address) + "' port='" + port + "' protocol='" + protocol + "'");
        }
        try {
            if (protocol.equals("ajp")) {
                connector = new Connector("org.apache.coyote.ajp.AjpProtocol");
            } else if (protocol.equals("memory")) {
                connector = new Connector("org.apache.coyote.memory.MemoryProtocolHandler");
            } else if (protocol.equals("http")) {
                connector = new Connector();
            } else if (protocol.equals("https")) {
                connector = new Connector();
                connector.setScheme("https");
                connector.setSecure(true);
                connector.setProperty("SSLEnabled", "true");
            // FIXME !!!! SET SSL PROPERTIES
            } else {
                connector = new Connector(protocol);
            }
            if (address != null) {
                IntrospectionUtils.setProperty(connector, "address", "" + address);
            }
            IntrospectionUtils.setProperty(connector, "port", "" + port);
        } catch (Exception e) {
            log.error("Couldn't create connector.");
        }
        return (connector);
    }

    /**
     * Create, configure, and return a Context that will process all HTTP
     * requests received from one of the replacedociated Connectors, and directed to
     * the specified context path on the virtual host to which this Context is
     * connected.
     * <p>
     * After you have customized the properties, listeners, and Valves for this
     * Context, you must attach it to the corresponding Host by calling:
     *
     * <pre>
     * host.addChild(context);
     * </pre>
     *
     * which will also cause the Context to be started if the Host has already
     * been started.
     *
     * @param path
     *            Context path of this application ("" for the default
     *            application for this host, must start with a slash otherwise)
     * @param docBase
     *            Absolute pathname to the doreplacedent base directory for this web
     *            application
     *
     * @exception IllegalArgumentException
     *                if an invalid parameter is specified
     */
    public Context createContext(String path, String docBase) {
        if (log.isDebugEnabled())
            log.debug("Creating context '" + path + "' with docBase '" + docBase + "'");
        StandardContext context = new StandardContext();
        context.setDocBase(docBase);
        context.setPath(path);
        ContextConfig config = new ContextConfig();
        config.setCustomAuthenticators(authenticators);
        context.addLifecycleListener(config);
        return (context);
    }

    /**
     * Create, configure, and return an Engine that will process all HTTP
     * requests received from one of the replacedociated Connectors, based on the
     * specified properties.
     */
    public Engine createEngine() {
        if (log.isDebugEnabled())
            log.debug("Creating engine");
        StandardEngine engine = new StandardEngine();
        // Default host will be set to the first host added
        // Inherited by all children
        engine.setRealm(realm);
        return (engine);
    }

    /**
     * Create, configure, and return a Host that will process all HTTP requests
     * received from one of the replacedociated Connectors, and directed to the
     * specified virtual host.
     * <p>
     * After you have customized the properties, listeners, and Valves for this
     * Host, you must attach it to the corresponding Engine by calling:
     *
     * <pre>
     * engine.addChild(host);
     * </pre>
     *
     * which will also cause the Host to be started if the Engine has already
     * been started. If this is the default (or only) Host you will be defining,
     * you may also tell the Engine to preplaced all requests not replacedigned to another
     * virtual host to this one:
     *
     * <pre>
     * engine.setDefaultHost(host.getName());
     * </pre>
     *
     * @param name
     *            Canonical name of this virtual host
     * @param appBase
     *            Absolute pathname to the application base directory for this
     *            virtual host
     *
     * @exception IllegalArgumentException
     *                if an invalid parameter is specified
     */
    public Host createHost(String name, String appBase) {
        if (log.isDebugEnabled())
            log.debug("Creating host '" + name + "' with appBase '" + appBase + "'");
        StandardHost host = new StandardHost();
        host.setAppBase(appBase);
        host.setName(name);
        return (host);
    }

    /**
     * Create and return a clreplaced loader manager that can be customized, and then
     * attached to a Context, before it is started.
     *
     * @param parent
     *            ClreplacedLoader that will be the parent of the one created by this
     *            Loader
     */
    public Loader createLoader(ClreplacedLoader parent) {
        if (log.isDebugEnabled())
            log.debug("Creating Loader with parent clreplaced loader '" + parent + "'");
        WebappLoader loader = new WebappLoader(parent);
        return (loader);
    }

    /**
     * Return descriptive information about this Server implementation and the
     * corresponding version number, in the format
     * <code><description>/<version></code>.
     */
    @Override
    public String getInfo() {
        return (info);
    }

    /**
     * Remove the specified Context from the set of defined Contexts for its
     * replacedociated Host. If this is the last Context for this Host, the Host will
     * also be removed.
     *
     * @param context
     *            The Context to be removed
     */
    public synchronized void removeContext(Context context) {
        if (log.isDebugEnabled())
            log.debug("Removing context[" + context.getName() + "]");
        // Is this Context actually among those that are defined?
        boolean found = false;
        for (int i = 0; i < engines.length; i++) {
            Container[] hosts = engines[i].findChildren();
            for (int j = 0; j < hosts.length; j++) {
                Container[] contexts = hosts[j].findChildren();
                for (int k = 0; k < contexts.length; k++) {
                    if (context == (Context) contexts[k]) {
                        found = true;
                        break;
                    }
                }
                if (found)
                    break;
            }
            if (found)
                break;
        }
        if (!found)
            return;
        // Remove this Context from the replacedociated Host
        if (log.isDebugEnabled())
            log.debug(" Removing this Context");
        context.getParent().removeChild(context);
    }

    /**
     * Remove the specified Engine from the set of defined Engines, along with
     * all of its related Hosts and Contexts. All replacedociated Connectors are also
     * removed.
     *
     * @param engine
     *            The Engine to be removed
     */
    public synchronized void removeEngine(Engine engine) {
        if (log.isDebugEnabled())
            log.debug("Removing engine (" + engine.getInfo() + ")");
        // Is the specified Engine actually defined?
        int j = -1;
        for (int i = 0; i < engines.length; i++) {
            if (engine == engines[i]) {
                j = i;
                break;
            }
        }
        if (j < 0)
            return;
        // Remove any Connector that is using this Engine
        if (log.isDebugEnabled())
            log.debug(" Removing related Containers");
        while (true) {
            int n = -1;
            for (int i = 0; i < connectors.length; i++) {
                if (connectors[i].getService().getContainer() == engine) {
                    n = i;
                    break;
                }
            }
            if (n < 0)
                break;
            removeConnector(connectors[n]);
        }
        // Stop this Engine if necessary
        if (log.isDebugEnabled())
            log.debug(" Stopping this Engine");
        try {
            engine.stop();
        } catch (LifecycleException e) {
            log.error("Engine.stop", e);
        }
        // Remove this Engine from our set of defined Engines
        if (log.isDebugEnabled())
            log.debug(" Removing this Engine");
        int k = 0;
        Engine[] results = new Engine[engines.length - 1];
        for (int i = 0; i < engines.length; i++) {
            if (i != j)
                results[k++] = engines[i];
        }
        engines = results;
    }

    /**
     * Remove the specified Host, along with all of its related Contexts, from
     * the set of defined Hosts for its replacedociated Engine. If this is the last
     * Host for this Engine, the Engine will also be removed.
     *
     * @param host
     *            The Host to be removed
     */
    public synchronized void removeHost(Host host) {
        if (log.isDebugEnabled())
            log.debug("Removing host[" + host.getName() + "]");
        // Is this Host actually among those that are defined?
        boolean found = false;
        for (int i = 0; i < engines.length; i++) {
            Container[] hosts = engines[i].findChildren();
            for (int j = 0; j < hosts.length; j++) {
                if (host == (Host) hosts[j]) {
                    found = true;
                    break;
                }
            }
            if (found)
                break;
        }
        if (!found)
            return;
        // Remove this Host from the replacedociated Engine
        if (log.isDebugEnabled())
            log.debug(" Removing this Host");
        host.getParent().removeChild(host);
    }

    /*
	 * Maps the specified login method to the specified authenticator, allowing
	 * the mappings in org/apache/catalina/startup/Authenticators.properties to
	 * be overridden.
	 *
	 * @param authenticator Authenticator to handle authentication for the
	 * specified login method
	 * 
	 * @param loginMethod Login method that maps to the specified authenticator
	 *
	 * @throws IllegalArgumentException if the specified authenticator does not
	 * implement the org.apache.catalina.Valve interface
	 */
    public void addAuthenticator(Authenticator authenticator, String loginMethod) {
        if (!(authenticator instanceof Valve)) {
            throw new IllegalArgumentException(sm.getString("embedded.authenticatorNotInstanceOfValve"));
        }
        if (authenticators == null) {
            synchronized (this) {
                if (authenticators == null) {
                    authenticators = new HashMap<String, Authenticator>();
                }
            }
        }
        authenticators.put(loginMethod, authenticator);
    }

    // ------------------------------------------------------ Lifecycle Methods
    /**
     * Start nested components ({@link Connector}s and {@link Engine}s) and
     * implement the requirements of
     * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException
     *                if this component detects a fatal error that prevents this
     *                component from being used
     */
    @Override
    protected void startInternal() throws LifecycleException {
        if (log.isInfoEnabled())
            log.info("Starting tomcat server");
        // Validate the setup of our required system properties
        initDirs();
        // Initialize some naming specific properties
        initNaming();
        setState(LifecycleState.STARTING);
        // Start our defined Engines first
        for (int i = 0; i < engines.length; i++) {
            engines[i].start();
        }
        // Start our defined Connectors second
        for (int i = 0; i < connectors.length; i++) {
            ((Lifecycle) connectors[i]).start();
        }
    }

    /**
     * Stop nested components ({@link Connector}s and {@link Engine}s) and
     * implement the requirements of
     * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
     *
     * @exception LifecycleException
     *                if this component detects a fatal error that needs to be
     *                reported
     */
    @Override
    protected void stopInternal() throws LifecycleException {
        if (log.isDebugEnabled())
            log.debug("Stopping embedded server");
        setState(LifecycleState.STOPPING);
        // Stop our defined Connectors first
        for (int i = 0; i < connectors.length; i++) {
            ((Lifecycle) connectors[i]).stop();
        }
        // Stop our defined Engines second
        for (int i = 0; i < engines.length; i++) {
            engines[i].stop();
        }
    }

    // ------------------------------------------------------ Protected Methods
    /**
     * Initialize naming - this should only enable java:env and root naming. If
     * tomcat is embedded in an application that already defines those - it
     * shouldn't do it.
     *
     * XXX The 2 should be separated, you may want to enable java: but not the
     * initial context and the reverse XXX Can we "guess" - i.e. lookup java:
     * and if something is returned replacedume false ? XXX We have a major problem
     * with the current setting for java: url
     */
    protected void initNaming() {
        // Setting additional variables
        if (!useNaming) {
            log.info("Catalina naming disabled");
            System.setProperty("catalina.useNaming", "false");
        } else {
            System.setProperty("catalina.useNaming", "true");
            String value = "org.apache.naming";
            String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
            if (oldValue != null) {
                value = value + ":" + oldValue;
            }
            System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
            if (log.isDebugEnabled())
                log.debug("Setting naming prefix=" + value);
            value = System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
            if (value == null) {
                System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
            } else {
                log.debug("INITIAL_CONTEXT_FACTORY already set " + value);
            }
        }
    }

    protected void initDirs() {
        String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP);
        if (catalinaHome == null) {
            // Backwards compatibility patch for J2EE RI 1.3
            String j2eeHome = System.getProperty("com.sun.enterprise.home");
            if (j2eeHome != null) {
                catalinaHome = System.getProperty("com.sun.enterprise.home");
            } else if (System.getProperty(Globals.CATALINA_BASE_PROP) != null) {
                catalinaHome = System.getProperty(Globals.CATALINA_BASE_PROP);
            } else {
                // Use IntrospectionUtils and guess the dir
                catalinaHome = IntrospectionUtils.guessInstall(Globals.CATALINA_HOME_PROP, Globals.CATALINA_BASE_PROP, "catalina.jar");
                if (catalinaHome == null) {
                    catalinaHome = IntrospectionUtils.guessInstall("tomcat.install", Globals.CATALINA_HOME_PROP, "tomcat.jar");
                }
            }
        }
        // last resort - for minimal/embedded cases.
        if (catalinaHome == null) {
            catalinaHome = System.getProperty("user.dir");
        }
        if (catalinaHome != null) {
            File home = new File(catalinaHome);
            if (!home.isAbsolute()) {
                try {
                    catalinaHome = home.getCanonicalPath();
                } catch (IOException e) {
                    catalinaHome = home.getAbsolutePath();
                }
            }
            System.setProperty(Globals.CATALINA_HOME_PROP, catalinaHome);
        }
        if (System.getProperty(Globals.CATALINA_BASE_PROP) == null) {
            System.setProperty(Globals.CATALINA_BASE_PROP, catalinaHome);
        } else {
            String catalinaBase = System.getProperty(Globals.CATALINA_BASE_PROP);
            File base = new File(catalinaBase);
            if (!base.isAbsolute()) {
                try {
                    catalinaBase = base.getCanonicalPath();
                } catch (IOException e) {
                    catalinaBase = base.getAbsolutePath();
                }
            }
            System.setProperty(Globals.CATALINA_BASE_PROP, catalinaBase);
        }
        String temp = System.getProperty("java.io.tmpdir");
        if (temp == null || (!(new File(temp)).exists()) || (!(new File(temp)).isDirectory())) {
            log.error(sm.getString("embedded.notmp", temp));
        }
    }

    protected void initStreams() {
        if (redirectStreams) {
            // Replace System.out and System.err with a custom PrintStream
            Where.amI();
            System.setOut(new SystemLogHandler(System.out));
            System.setErr(new SystemLogHandler(System.err));
        }
    }

    // -------------------------------------------------------- Private Methods
    /**
     * Set the security package access/protection.
     */
    protected void setSecurityProtection() {
        SecurityConfig securityConfig = SecurityConfig.newInstance();
        securityConfig.setPackageDefinition();
        securityConfig.setPackageAccess();
    }
}

18 Source : SerializablePrincipal.java
with Apache License 2.0
from how2j

/**
 * Generic implementation of <strong>java.security.Principal</strong> that is
 * available for use by <code>Realm</code> implementations. The GenericPrincipal
 * does NOT implement serializable and I didn't want to change that
 * implementation hence I implemented this one instead.
 *
 * @author Filip Hanik
 */
public clreplaced SerializablePrincipal implements java.io.Serializable {

    private static final long serialVersionUID = 1L;

    private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(SerializablePrincipal.clreplaced);

    /**
     * The string manager for this package.
     */
    protected static final StringManager sm = StringManager.getManager(Constants.Package);

    // ----------------------------------------------------------- Constructors
    public SerializablePrincipal() {
        super();
    }

    /**
     * Construct a new Principal, replacedociated with the specified Realm, for the
     * specified username and preplacedword.
     *
     * @param name
     *            The username of the user represented by this Principal
     * @param preplacedword
     *            Credentials used to authenticate this user
     */
    public SerializablePrincipal(String name, String preplacedword) {
        this(name, preplacedword, null);
    }

    /**
     * Construct a new Principal, replacedociated with the specified Realm, for the
     * specified username and preplacedword, with the specified role names (as
     * Strings).
     *
     * @param name
     *            The username of the user represented by this Principal
     * @param preplacedword
     *            Credentials used to authenticate this user
     * @param roles
     *            List of roles (must be Strings) possessed by this user
     */
    public SerializablePrincipal(String name, String preplacedword, List<String> roles) {
        this(name, preplacedword, roles, null);
    }

    /**
     * Construct a new Principal, replacedociated with the specified Realm, for the
     * specified username and preplacedword, with the specified role names (as
     * Strings).
     *
     * @param name
     *            The username of the user represented by this Principal
     * @param preplacedword
     *            Credentials used to authenticate this user
     * @param roles
     *            List of roles (must be Strings) possessed by this user
     * @param userPrincipal
     *            The user principal to be exposed to applications
     */
    public SerializablePrincipal(String name, String preplacedword, List<String> roles, Principal userPrincipal) {
        super();
        this.name = name;
        this.preplacedword = preplacedword;
        if (roles != null) {
            this.roles = new String[roles.size()];
            this.roles = roles.toArray(this.roles);
            if (this.roles.length > 1)
                Arrays.sort(this.roles);
        }
        if (userPrincipal instanceof Serializable) {
            this.userPrincipal = userPrincipal;
        }
    }

    // ------------------------------------------------------------- Properties
    /**
     * The username of the user represented by this Principal.
     */
    protected String name = null;

    public String getName() {
        return (this.name);
    }

    /**
     * The authentication credentials for the user represented by this
     * Principal.
     */
    protected String preplacedword = null;

    public String getPreplacedword() {
        return (this.preplacedword);
    }

    /**
     * The Realm with which this Principal is replacedociated.
     */
    protected transient Realm realm = null;

    public Realm getRealm() {
        return (this.realm);
    }

    public void setRealm(Realm realm) {
        this.realm = realm;
    }

    /**
     * The set of roles replacedociated with this user.
     */
    protected String[] roles = new String[0];

    public String[] getRoles() {
        return (this.roles);
    }

    /**
     * The user principal, if present.
     */
    protected Principal userPrincipal = null;

    // --------------------------------------------------------- Public Methods
    /**
     * Return a String representation of this object, which exposes only
     * information that should be public.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("SerializablePrincipal[");
        sb.append(this.name);
        sb.append("]");
        return (sb.toString());
    }

    public static SerializablePrincipal createPrincipal(GenericPrincipal principal) {
        if (principal == null)
            return null;
        return new SerializablePrincipal(principal.getName(), principal.getPreplacedword(), principal.getRoles() != null ? Arrays.asList(principal.getRoles()) : null, principal.getUserPrincipal() != principal ? principal.getUserPrincipal() : null);
    }

    public GenericPrincipal getPrincipal() {
        return new GenericPrincipal(name, preplacedword, getRoles() != null ? Arrays.asList(getRoles()) : null, userPrincipal);
    }

    public static GenericPrincipal readPrincipal(ObjectInput in) throws IOException, ClreplacedNotFoundException {
        String name = in.readUTF();
        boolean hasPwd = in.readBoolean();
        String pwd = null;
        if (hasPwd)
            pwd = in.readUTF();
        int size = in.readInt();
        String[] roles = new String[size];
        for (int i = 0; i < size; i++) roles[i] = in.readUTF();
        Principal userPrincipal = null;
        boolean hasUserPrincipal = in.readBoolean();
        if (hasUserPrincipal) {
            try {
                userPrincipal = (Principal) in.readObject();
            } catch (ClreplacedNotFoundException e) {
                log.error(sm.getString("serializablePrincipal.readPrincipal.cnfe"), e);
                throw e;
            }
        }
        return new GenericPrincipal(name, pwd, Arrays.asList(roles), userPrincipal);
    }

    public static void writePrincipal(GenericPrincipal p, ObjectOutput out) throws IOException {
        out.writeUTF(p.getName());
        out.writeBoolean(p.getPreplacedword() != null);
        if (p.getPreplacedword() != null)
            out.writeUTF(p.getPreplacedword());
        String[] roles = p.getRoles();
        if (roles == null)
            roles = new String[0];
        out.writeInt(roles.length);
        for (int i = 0; i < roles.length; i++) out.writeUTF(roles[i]);
        boolean hasUserPrincipal = (p != p.getUserPrincipal() && p.getUserPrincipal() instanceof Serializable);
        out.writeBoolean(hasUserPrincipal);
        if (hasUserPrincipal)
            out.writeObject(p.getUserPrincipal());
    }
}

18 Source : CombinedRealm.java
with GNU General Public License v3.0
from guang19

@Override
public boolean isAvailable() {
    for (Realm realm : realms) {
        if (!realm.isAvailable()) {
            return false;
        }
    }
    return true;
}

18 Source : CombinedRealm.java
with GNU General Public License v3.0
from guang19

/**
 * @return the set of Realms that this Realm is wrapping
 */
public ObjectName[] getRealms() {
    ObjectName[] result = new ObjectName[realms.size()];
    for (Realm realm : realms) {
        if (realm instanceof RealmBase) {
            result[realms.indexOf(realm)] = ((RealmBase) realm).getObjectName();
        }
    }
    return result;
}

18 Source : ContainerBase.java
with GNU General Public License v3.0
from guang19

@Override
protected void destroyInternal() throws LifecycleException {
    Realm realm = getRealmInternal();
    if (realm instanceof Lifecycle) {
        ((Lifecycle) realm).destroy();
    }
    Cluster cluster = getClusterInternal();
    if (cluster instanceof Lifecycle) {
        ((Lifecycle) cluster).destroy();
    }
    // Stop the Valves in our pipeline (including the basic), if any
    if (pipeline instanceof Lifecycle) {
        ((Lifecycle) pipeline).destroy();
    }
    // Remove children now this container is being destroyed
    for (Container child : findChildren()) {
        removeChild(child);
    }
    // Required if the child is destroyed directly.
    if (parent != null) {
        parent.removeChild(this);
    }
    // If init fails, this may be null
    if (startStopExecutor != null) {
        startStopExecutor.shutdownNow();
    }
    super.destroyInternal();
}

17 Source : Tomcat.java
with Apache License 2.0
from wangyingjie

// TODO: lazy init for the temp dir - only when a JSP is compiled or
// get temp dir is called we need to create it. This will avoid the
// need for the baseDir
// TODO: allow contexts without a base dir - i.e.
// only programmatic. This would disable the default servlet.
/**
 * Minimal tomcat starter for embedding/unit tests.
 *
 * Tomcat supports multiple styles of configuration and
 * startup - the most common and stable is server.xml-based,
 * implemented in org.apache.catalina.startup.Bootstrap.
 *
 * This clreplaced is for use in apps that embed tomcat.
 * Requirements:
 *
 * - all tomcat clreplacedes and possibly servlets are in the clreplacedpath.
 * ( for example all is in one big jar, or in eclipse CP, or in any other
 * combination )
 *
 * - we need one temporary directory for work files
 *
 * - no config file is required. This clreplaced provides methods to
 * use if you have a webapp with a web.xml file, but it is
 * optional - you can use your own servlets.
 *
 * There are a variety of 'add' methods to configure servlets and webapps. These
 * methods, by default, create a simple in-memory security realm and apply it.
 * If you need more complex security processing, you can define a subclreplaced of
 * this clreplaced.
 *
 * This clreplaced provides a set of convenience methods for configuring webapp
 * contexts, all overloads of the method <pre>addWebapp</pre>. These methods
 * create a webapp context, configure it, and then add it to a {@link Host}.
 * They do not use a global default web.xml; rather, they add a lifecycle
 * listener that adds the standard DefaultServlet, JSP processing, and welcome
 * files.
 *
 * In complex cases, you may prefer to use the ordinary Tomcat API to create
 * webapp contexts; for example, you might need to install a custom Loader
 * before the call to {@link Host#addChild(Container)}. To replicate the basic
 * behavior of the <pre>addWebapp</pre> methods, you may want to call two
 * methods of this clreplaced: {@link #noDefaultWebXmlPath()} and
 * {@link #getDefaultWebXmlListener()}.
 *
 * {@link #getDefaultRealm()} returns the simple security realm.
 *
 * {@link #getDefaultWebXmlListener()} returns a {@link LifecycleListener} that
 * adds the standard DefaultServlet, JSP processing, and welcome files. If you
 * add this listener, you must prevent Tomcat from applying any standard global
 * web.xml with ...
 *
 * {@link #noDefaultWebXmlPath()} returns a dummy pathname to configure to
 * prevent {@link ContextConfig} from trying to apply a global web.xml file.
 *
 * This clreplaced provides a main() and few simple CLI arguments,
 * see setters for doc. It can be used for simple tests and
 * demo.
 *
 * @see <a href="http://svn.apache.org/repos/asf/tomcat/trunk/test/org/apache/catalina/startup/TestTomcat.java">TestTomcat</a>
 * @author Costin Manolache
 */
public clreplaced Tomcat {

    // Some logging implementations use weak references for loggers so there is
    // the possibility that logging configuration could be lost if GC runs just
    // after Loggers are configured but before they are used. The purpose of
    // this Map is to retain strong references to explicitly configured loggers
    // so that configuration is not lost.
    private final Map<String, Logger> pinnedLoggers = new HashMap<String, Logger>();

    // Single engine, service, server, connector - few cases need more,
    // they can use server.xml
    protected Server server;

    protected Service service;

    protected Engine engine;

    // for more - customize the clreplacedes
    protected Connector connector;

    // To make it a bit easier to config for the common case
    // ( one host, one context ).
    protected Host host;

    // TODO: it's easy to add support for more hosts - but is it
    // really needed ?
    // TODO: allow use of in-memory connector
    protected int port = 8080;

    protected String hostname = "localhost";

    protected String basedir;

    // Default in-memory realm, will be set by default on the Engine. Can be
    // replaced at engine level or over-ridden at Host or Context level
    // Will be removed in Tomcat 8.0.x.
    @Deprecated
    protected Realm defaultRealm;

    private final Map<String, String> userPreplaced = new HashMap<String, String>();

    private final Map<String, List<String>> userRoles = new HashMap<String, List<String>>();

    private final Map<String, Principal> userPrincipals = new HashMap<String, Principal>();

    public Tomcat() {
    // NOOP
    }

    /**
     * Tomcat needs a directory for temp files. This should be the
     * first method called.
     *
     * By default, if this method is not called, we use:
     *  - system properties - catalina.base, catalina.home
     *  - $HOME/tomcat.$PORT
     * ( /tmp doesn't seem a good choice for security ).
     *
     * TODO: better default ? Maybe current dir ?
     * TODO: disable work dir if not needed ( no jsp, etc ).
     */
    public void setBaseDir(String basedir) {
        this.basedir = basedir;
    }

    /**
     * Set the port for the default connector. Must
     * be called before start().
     */
    public void setPort(int port) {
        this.port = port;
    }

    /**
     * The the hostname of the default host, default is
     * 'localhost'.
     */
    public void setHostname(String s) {
        hostname = s;
    }

    /**
     * This is equivalent to adding a web application to Tomcat's webapps
     * directory. The equivalent of the default web.xml will be applied  to the
     * web application and any WEB-INF/web.xml and META-INF/context.xml packaged
     * with the application will be processed normally. Normal web fragment and
     * {@link javax.servlet.ServletContainerInitializer} processing will be
     * applied.
     *
     * @throws ServletException
     */
    public Context addWebapp(String contextPath, String docBase) throws ServletException {
        return addWebapp(getHost(), contextPath, docBase);
    }

    /**
     * Add a context - programmatic mode, no web.xml used.
     *
     * API calls equivalent with web.xml:
     *
     * context-param
     *  ctx.addParameter("name", "value");
     *
     * error-page
     *    ErrorPage ep = new ErrorPage();
     *    ep.setErrorCode(500);
     *    ep.setLocation("/error.html");
     *    ctx.addErrorPage(ep);
     *
     * ctx.addMimeMapping("ext", "type");
     *
     * Note: If you reload the Context, all your configuration will be lost. If
     * you need reload support, consider using a LifecycleListener to provide
     * your configuration.
     *
     * TODO: add the rest
     *
     *  @param contextPath "" for root context.
     *  @param docBase base dir for the context, for static files. Must exist,
     *  relative to the server home
     */
    public Context addContext(String contextPath, String docBase) {
        return addContext(getHost(), contextPath, docBase);
    }

    /**
     * Equivalent with
     *  <servlet><servlet-name><servlet-clreplaced>.
     *
     * In general it is better/faster to use the method that takes a
     * Servlet as param - this one can be used if the servlet is not
     * commonly used, and want to avoid loading all deps.
     * ( for example: jsp servlet )
     *
     * You can customize the returned servlet, ex:
     *
     *    wrapper.addInitParameter("name", "value");
     *
     * @param contextPath   Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servletClreplaced  The clreplaced to be used for the Servlet
     * @return The wrapper for the servlet
     */
    public Wrapper addServlet(String contextPath, String servletName, String servletClreplaced) {
        Container ctx = getHost().findChild(contextPath);
        return addServlet((Context) ctx, servletName, servletClreplaced);
    }

    /**
     * Static version of {@link #addServlet(String, String, String)}
     * @param ctx           Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servletClreplaced  The clreplaced to be used for the Servlet
     * @return The wrapper for the servlet
     */
    public static Wrapper addServlet(Context ctx, String servletName, String servletClreplaced) {
        // will do clreplaced for name and set init params
        Wrapper sw = ctx.createWrapper();
        sw.setServletClreplaced(servletClreplaced);
        sw.setName(servletName);
        ctx.addChild(sw);
        return sw;
    }

    /**
     * Add an existing Servlet to the context with no clreplaced.forName or
     * initialisation.
     * @param contextPath   Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servlet       The Servlet to add
     * @return The wrapper for the servlet
     */
    public Wrapper addServlet(String contextPath, String servletName, Servlet servlet) {
        Container ctx = getHost().findChild(contextPath);
        return addServlet((Context) ctx, servletName, servlet);
    }

    /**
     * Static version of {@link #addServlet(String, String, Servlet)}.
     * @param ctx           Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servlet       The Servlet to add
     * @return The wrapper for the servlet
     */
    public static Wrapper addServlet(Context ctx, String servletName, Servlet servlet) {
        // will do clreplaced for name and set init params
        Wrapper sw = new ExistingStandardWrapper(servlet);
        sw.setName(servletName);
        ctx.addChild(sw);
        return sw;
    }

    /**
     * Initialise the server.
     *
     * @throws LifecycleException
     */
    public void init() throws LifecycleException {
        getServer();
        getConnector();
        server.init();
    }

    /**
     * Start the server.
     *
     * @throws LifecycleException
     */
    public void start() throws LifecycleException {
        getServer();
        getConnector();
        server.start();
    }

    /**
     * Stop the server.
     *
     * @throws LifecycleException
     */
    public void stop() throws LifecycleException {
        getServer();
        server.stop();
    }

    /**
     * Destroy the server. This object cannot be used once this method has been
     * called.
     */
    public void destroy() throws LifecycleException {
        getServer();
        server.destroy();
    // Could null out objects here
    }

    /**
     * Add a user for the in-memory realm. All created apps use this
     * by default, can be replaced using setRealm().
     */
    public void addUser(String user, String preplaced) {
        userPreplaced.put(user, preplaced);
    }

    /**
     * @see #addUser(String, String)
     */
    public void addRole(String user, String role) {
        List<String> roles = userRoles.get(user);
        if (roles == null) {
            roles = new ArrayList<String>();
            userRoles.put(user, roles);
        }
        roles.add(role);
    }

    // ------- Extra customization -------
    // You can tune individual tomcat objects, using internal APIs
    /**
     * Get the default http connector. You can set more
     * parameters - the port is already initialized.
     *
     * Alternatively, you can construct a Connector and set any params,
     * then call addConnector(Connector)
     *
     * @return A connector object that can be customized
     */
    public Connector getConnector() {
        getServer();
        if (connector != null) {
            return connector;
        }
        // The same as in standard Tomcat configuration.
        // This creates an APR HTTP connector if AprLifecycleListener has been
        // configured (created) and Tomcat Native library is available.
        // Otherwise it creates a BIO HTTP connector (Http11Protocol).
        connector = new Connector("HTTP/1.1");
        connector.setPort(port);
        service.addConnector(connector);
        return connector;
    }

    public void setConnector(Connector connector) {
        this.connector = connector;
    }

    /**
     * Get the service object. Can be used to add more
     * connectors and few other global settings.
     */
    public Service getService() {
        getServer();
        return service;
    }

    /**
     * Sets the current host - all future webapps will
     * be added to this host. When tomcat starts, the
     * host will be the default host.
     *
     * @param host
     */
    public void setHost(Host host) {
        this.host = host;
    }

    public Host getHost() {
        if (host == null) {
            host = new StandardHost();
            host.setName(hostname);
            getEngine().addChild(host);
        }
        return host;
    }

    /**
     * Set a custom realm for auth. If not called, a simple
     * default will be used, using an internal map.
     *
     * Must be called before adding a context.
     *
     * @deprecated Will be removed in Tomcat 8.0.x.
     */
    @Deprecated
    public void setDefaultRealm(Realm realm) {
        defaultRealm = realm;
    }

    /**
     * Access to the engine, for further customization.
     */
    public Engine getEngine() {
        if (engine == null) {
            getServer();
            engine = new StandardEngine();
            engine.setName("Tomcat");
            engine.setDefaultHost(hostname);
            if (defaultRealm == null) {
                initSimpleAuth();
            }
            engine.setRealm(defaultRealm);
            service.setContainer(engine);
        }
        return engine;
    }

    /**
     * Get the server object. You can add listeners and few more
     * customizations. JNDI is disabled by default.
     */
    public Server getServer() {
        if (server != null) {
            return server;
        }
        initBaseDir();
        System.setProperty("catalina.useNaming", "false");
        server = new StandardServer();
        server.setPort(-1);
        service = new StandardService();
        service.setName("Tomcat");
        server.addService(service);
        return server;
    }

    public Context addContext(Host host, String contextPath, String dir) {
        return addContext(host, contextPath, contextPath, dir);
    }

    public Context addContext(Host host, String contextPath, String contextName, String dir) {
        silence(host, contextName);
        Context ctx = createContext(host, contextPath);
        ctx.setName(contextName);
        ctx.setPath(contextPath);
        ctx.setDocBase(dir);
        ctx.addLifecycleListener(new FixContextListener());
        if (host == null) {
            getHost().addChild(ctx);
        } else {
            host.addChild(ctx);
        }
        return ctx;
    }

    public Context addWebapp(Host host, String contextPath, String docBase) {
        return addWebapp(host, contextPath, contextPath, docBase);
    }

    /**
     * @see #addWebapp(String, String)
     *
     * @param name Ignored. The contextPath will be used
     *
     * @deprecated Use {@link #addWebapp(Host, String, String)}
     */
    @Deprecated
    public Context addWebapp(Host host, String contextPath, String name, String docBase) {
        silence(host, contextPath);
        Context ctx = createContext(host, contextPath);
        ctx.setPath(contextPath);
        ctx.setDocBase(docBase);
        ctx.addLifecycleListener(new DefaultWebXmlListener());
        ctx.setConfigFile(getWebappConfigFile(docBase, contextPath));
        ContextConfig ctxCfg = new ContextConfig();
        ctx.addLifecycleListener(ctxCfg);
        // prevent it from looking ( if it finds one - it'll have dup error )
        ctxCfg.setDefaultWebXml(noDefaultWebXmlPath());
        if (host == null) {
            getHost().addChild(ctx);
        } else {
            host.addChild(ctx);
        }
        return ctx;
    }

    /**
     * Return a listener that provides the required configuration items for JSP
     * processing. From the standard Tomcat global web.xml. Preplaced this to
     * {@link Context#addLifecycleListener(LifecycleListener)} and then preplaced the
     * result of {@link #noDefaultWebXmlPath()} to
     * {@link ContextConfig#setDefaultWebXml(String)}.
     * @return a listener object that configures default JSP processing.
     */
    public LifecycleListener getDefaultWebXmlListener() {
        return new DefaultWebXmlListener();
    }

    /**
     * @return a pathname to preplaced to
     * {@link ContextConfig#setDefaultWebXml(String)} when using
     * {@link #getDefaultWebXmlListener()}.
     */
    public String noDefaultWebXmlPath() {
        return Constants.NoDefaultWebXml;
    }

    /**
     * For complex configurations, this accessor allows callers of this clreplaced
     * to obtain the simple realm created by default.
     * @return the simple in-memory realm created by default.
     * @deprecated Will be removed in Tomcat 8.0.x
     */
    @Deprecated
    public Realm getDefaultRealm() {
        if (defaultRealm == null) {
            initSimpleAuth();
        }
        return defaultRealm;
    }

    // ---------- Helper methods and clreplacedes -------------------
    /**
     * Create an in-memory realm. You can replace it for contexts with a real
     * one. The Realm created here will be added to the Engine by default and
     * may be replaced at the Engine level or over-ridden (as per normal Tomcat
     * behaviour) at the Host or Context level.
     * @deprecated Will be removed in Tomcat 8.0.x
     */
    @Deprecated
    protected void initSimpleAuth() {
        defaultRealm = new RealmBase() {

            @Override
            protected String getName() {
                return "Simple";
            }

            @Override
            protected String getPreplacedword(String username) {
                return userPreplaced.get(username);
            }

            @Override
            protected Principal getPrincipal(String username) {
                Principal p = userPrincipals.get(username);
                if (p == null) {
                    String preplaced = userPreplaced.get(username);
                    if (preplaced != null) {
                        p = new GenericPrincipal(username, preplaced, userRoles.get(username));
                        userPrincipals.put(username, p);
                    }
                }
                return p;
            }
        };
    }

    protected void initBaseDir() {
        String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP);
        if (basedir == null) {
            basedir = System.getProperty(Globals.CATALINA_BASE_PROP);
        }
        if (basedir == null) {
            basedir = catalinaHome;
        }
        if (basedir == null) {
            // Create a temp dir.
            basedir = System.getProperty("user.dir") + "/tomcat." + port;
            File home = new File(basedir);
            home.mkdir();
            if (!home.isAbsolute()) {
                try {
                    basedir = home.getCanonicalPath();
                } catch (IOException e) {
                    basedir = home.getAbsolutePath();
                }
            }
        }
        if (catalinaHome == null) {
            System.setProperty(Globals.CATALINA_HOME_PROP, basedir);
        }
        System.setProperty(Globals.CATALINA_BASE_PROP, basedir);
    }

    static final String[] silences = new String[] { "org.apache.coyote.http11.Http11Protocol", "org.apache.catalina.core.StandardService", "org.apache.catalina.core.StandardEngine", "org.apache.catalina.startup.ContextConfig", "org.apache.catalina.core.ApplicationContext", "org.apache.catalina.core.AprLifecycleListener" };

    private boolean silent = false;

    /**
     * Controls if the loggers will be silenced or not.
     * @param silent    <code>true</code> sets the log level to WARN for the
     *                  loggers that log information on Tomcat start up. This
     *                  prevents the usual startup information being logged.
     *                  <code>false</code> sets the log level to the default
     *                  level of INFO.
     */
    public void setSilent(boolean silent) {
        this.silent = silent;
        for (String s : silences) {
            Logger logger = Logger.getLogger(s);
            pinnedLoggers.put(s, logger);
            if (silent) {
                logger.setLevel(Level.WARNING);
            } else {
                logger.setLevel(Level.INFO);
            }
        }
    }

    private void silence(Host host, String contextPath) {
        String loggerName = getLoggerName(host, contextPath);
        Logger logger = Logger.getLogger(loggerName);
        pinnedLoggers.put(loggerName, logger);
        if (silent) {
            logger.setLevel(Level.WARNING);
        } else {
            logger.setLevel(Level.INFO);
        }
    }

    /*
     * Uses essentially the same logic as {@link ContainerBase#logName()}.
     */
    private String getLoggerName(Host host, String contextName) {
        if (host == null) {
            host = getHost();
        }
        StringBuilder loggerName = new StringBuilder();
        loggerName.append(ContainerBase.clreplaced.getName());
        loggerName.append(".[");
        // Engine name
        loggerName.append(host.getParent().getName());
        loggerName.append("].[");
        // Host name
        loggerName.append(host.getName());
        loggerName.append("].[");
        // Context name
        if (contextName == null || contextName.equals("")) {
            loggerName.append("/");
        } else if (contextName.startsWith("##")) {
            loggerName.append("/");
            loggerName.append(contextName);
        }
        loggerName.append(']');
        return loggerName.toString();
    }

    /**
     * Create the configured {@link Context} for the given <code>host</code>.
     * The default constructor of the clreplaced that was configured with
     * {@link StandardHost#setContextClreplaced(String)} will be used
     *
     * @param host
     *            host for which the {@link Context} should be created, or
     *            <code>null</code> if default host should be used
     * @param url
     *            path of the webapp which should get the {@link Context}
     * @return newly created {@link Context}
     */
    private Context createContext(Host host, String url) {
        String contextClreplaced = StandardContext.clreplaced.getName();
        if (host == null) {
            host = this.getHost();
        }
        if (host instanceof StandardHost) {
            contextClreplaced = ((StandardHost) host).getContextClreplaced();
        }
        try {
            return (Context) Clreplaced.forName(contextClreplaced).getConstructor().newInstance();
        } catch (InstantiationException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (InvocationTargetException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (SecurityException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (ClreplacedNotFoundException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        }
    }

    /**
     * Enables JNDI naming which is disabled by default. Server must implement
     * {@link Lifecycle} in order for the {@link NamingContextListener} to be
     * used.
     */
    public void enableNaming() {
        // Make sure getServer() has been called as that is where naming is
        // disabled
        getServer();
        server.addLifecycleListener(new NamingContextListener());
        System.setProperty("catalina.useNaming", "true");
        String value = "org.apache.naming";
        String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
        if (oldValue != null) {
            if (oldValue.contains(value)) {
                value = oldValue;
            } else {
                value = value + ":" + oldValue;
            }
        }
        System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
        value = System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
        if (value == null) {
            System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        }
    }

    /**
     * Provide default configuration for a context. This is the programmatic
     * equivalent of the default web.xml.
     *
     *  TODO: in normal Tomcat, if default-web.xml is not found, use this
     *  method
     *
     * @param contextPath   The context to set the defaults for
     */
    public void initWebappDefaults(String contextPath) {
        Container ctx = getHost().findChild(contextPath);
        initWebappDefaults((Context) ctx);
    }

    /**
     * Static version of {@link #initWebappDefaults(String)}
     * @param ctx   The context to set the defaults for
     */
    public static void initWebappDefaults(Context ctx) {
        // Default servlet
        Wrapper servlet = addServlet(ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
        servlet.setLoadOnStartup(1);
        servlet.setOverridable(true);
        // JSP servlet (by clreplaced name - to avoid loading all deps)
        servlet = addServlet(ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
        servlet.addInitParameter("fork", "false");
        servlet.setLoadOnStartup(3);
        servlet.setOverridable(true);
        // Servlet mappings
        ctx.addServletMapping("/", "default");
        ctx.addServletMapping("*.jsp", "jsp");
        ctx.addServletMapping("*.jspx", "jsp");
        // Sessions
        ctx.setSessionTimeout(30);
        // MIME mappings
        for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length; ) {
            ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++], DEFAULT_MIME_MAPPINGS[i++]);
        }
        // Welcome files
        ctx.addWelcomeFile("index.html");
        ctx.addWelcomeFile("index.htm");
        ctx.addWelcomeFile("index.jsp");
    }

    /**
     * Fix startup sequence - required if you don't use web.xml.
     *
     * The start() method in context will set 'configured' to false - and
     * expects a listener to set it back to true.
     */
    public static clreplaced FixContextListener implements LifecycleListener {

        @Override
        public void lifecycleEvent(LifecycleEvent event) {
            try {
                Context context = (Context) event.getLifecycle();
                if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
                    context.setConfigured(true);
                }
                // LoginConfig is required to process @ServletSecurity
                // annotations
                if (context.getLoginConfig() == null) {
                    context.setLoginConfig(new LoginConfig("NONE", null, null, null));
                    context.getPipeline().addValve(new NonLoginAuthenticator());
                }
            } catch (ClreplacedCastException e) {
                return;
            }
        }
    }

    /**
     * Fix reload - required if reloading and using programmatic configuration.
     * When a context is reloaded, any programmatic configuration is lost. This
     * listener sets the equivalent of conf/web.xml when the context starts.
     */
    public static clreplaced DefaultWebXmlListener implements LifecycleListener {

        @Override
        public void lifecycleEvent(LifecycleEvent event) {
            if (Lifecycle.BEFORE_START_EVENT.equals(event.getType())) {
                initWebappDefaults((Context) event.getLifecycle());
            }
        }
    }

    /**
     * Helper clreplaced for wrapping existing servlets. This disables servlet
     * lifecycle and normal reloading, but also reduces overhead and provide
     * more direct control over the servlet.
     */
    public static clreplaced ExistingStandardWrapper extends StandardWrapper {

        private final Servlet existing;

        @SuppressWarnings("deprecation")
        public ExistingStandardWrapper(Servlet existing) {
            this.existing = existing;
            if (existing instanceof javax.servlet.SingleThreadModel) {
                singleThreadModel = true;
                instancePool = new Stack<Servlet>();
            }
        }

        @Override
        public synchronized Servlet loadServlet() throws ServletException {
            if (singleThreadModel) {
                Servlet instance;
                try {
                    instance = existing.getClreplaced().newInstance();
                } catch (InstantiationException e) {
                    throw new ServletException(e);
                } catch (IllegalAccessException e) {
                    throw new ServletException(e);
                }
                instance.init(facade);
                return instance;
            } else {
                if (!instanceInitialized) {
                    existing.init(facade);
                    instanceInitialized = true;
                }
                return existing;
            }
        }

        @Override
        public long getAvailable() {
            return 0;
        }

        @Override
        public boolean isUnavailable() {
            return false;
        }

        @Override
        public Servlet getServlet() {
            return existing;
        }

        @Override
        public String getServletClreplaced() {
            return existing.getClreplaced().getName();
        }
    }

    /**
     * TODO: would a properties resource be better ? Or just parsing
     * /etc/mime.types ?
     * This is needed because we don't use the default web.xml, where this
     * is encoded.
     */
    private static final String[] DEFAULT_MIME_MAPPINGS = { "abs", "audio/x-mpeg", "ai", "application/postscript", "aif", "audio/x-aiff", "aifc", "audio/x-aiff", "aiff", "audio/x-aiff", "aim", "application/x-aim", "art", "image/x-jg", "asf", "video/x-ms-asf", "asx", "video/x-ms-asf", "au", "audio/basic", "avi", "video/x-msvideo", "avx", "video/x-rad-screenplay", "bcpio", "application/x-bcpio", "bin", "application/octet-stream", "bmp", "image/bmp", "body", "text/html", "cdf", "application/x-cdf", "cer", "application/pkix-cert", "clreplaced", "application/java", "cpio", "application/x-cpio", "csh", "application/x-csh", "css", "text/css", "dib", "image/bmp", "doc", "application/msword", "dtd", "application/xml-dtd", "dv", "video/x-dv", "dvi", "application/x-dvi", "eps", "application/postscript", "etx", "text/x-setext", "exe", "application/octet-stream", "gif", "image/gif", "gtar", "application/x-gtar", "gz", "application/x-gzip", "hdf", "application/x-hdf", "hqx", "application/mac-binhex40", "htc", "text/x-component", "htm", "text/html", "html", "text/html", "ief", "image/ief", "jad", "text/vnd.sun.j2me.app-descriptor", "jar", "application/java-archive", "java", "text/x-java-source", "jnlp", "application/x-java-jnlp-file", "jpe", "image/jpeg", "jpeg", "image/jpeg", "jpg", "image/jpeg", "js", "application/javascript", "jsf", "text/plain", "jspf", "text/plain", "kar", "audio/midi", "latex", "application/x-latex", "m3u", "audio/x-mpegurl", "mac", "image/x-macpaint", "man", "text/troff", "mathml", "application/mathml+xml", "me", "text/troff", "mid", "audio/midi", "midi", "audio/midi", "mif", "application/x-mif", "mov", "video/quicktime", "movie", "video/x-sgi-movie", "mp1", "audio/mpeg", "mp2", "audio/mpeg", "mp3", "audio/mpeg", "mp4", "video/mp4", "mpa", "audio/mpeg", "mpe", "video/mpeg", "mpeg", "video/mpeg", "mpega", "audio/x-mpeg", "mpg", "video/mpeg", "mpv2", "video/mpeg2", "nc", "application/x-netcdf", "oda", "application/oda", "odb", "application/vnd.oasis.opendoreplacedent.database", "odc", "application/vnd.oasis.opendoreplacedent.chart", "odf", "application/vnd.oasis.opendoreplacedent.formula", "odg", "application/vnd.oasis.opendoreplacedent.graphics", "odi", "application/vnd.oasis.opendoreplacedent.image", "odm", "application/vnd.oasis.opendoreplacedent.text-master", "odp", "application/vnd.oasis.opendoreplacedent.presentation", "ods", "application/vnd.oasis.opendoreplacedent.spreadsheet", "odt", "application/vnd.oasis.opendoreplacedent.text", "otg", "application/vnd.oasis.opendoreplacedent.graphics-template", "oth", "application/vnd.oasis.opendoreplacedent.text-web", "otp", "application/vnd.oasis.opendoreplacedent.presentation-template", "ots", "application/vnd.oasis.opendoreplacedent.spreadsheet-template ", "ott", "application/vnd.oasis.opendoreplacedent.text-template", "ogx", "application/ogg", "ogv", "video/ogg", "oga", "audio/ogg", "ogg", "audio/ogg", "spx", "audio/ogg", "flac", "audio/flac", "anx", "application/annodex", "axa", "audio/annodex", "axv", "video/annodex", "xspf", "application/xspf+xml", "pbm", "image/x-portable-bitmap", "pct", "image/pict", "pdf", "application/pdf", "pgm", "image/x-portable-graymap", "pic", "image/pict", "pict", "image/pict", "pls", "audio/x-scpls", "png", "image/png", "pnm", "image/x-portable-anymap", "pnt", "image/x-macpaint", "ppm", "image/x-portable-pixmap", "ppt", "application/vnd.ms-powerpoint", "pps", "application/vnd.ms-powerpoint", "ps", "application/postscript", "psd", "image/vnd.adobe.photoshop", "qt", "video/quicktime", "qti", "image/x-quicktime", "qtif", "image/x-quicktime", "ras", "image/x-cmu-raster", "rdf", "application/rdf+xml", "rgb", "image/x-rgb", "rm", "application/vnd.rn-realmedia", "roff", "text/troff", "rtf", "application/rtf", "rtx", "text/richtext", "sh", "application/x-sh", "shar", "application/x-shar", /*"shtml", "text/x-server-parsed-html",*/
    "sit", "application/x-stuffit", "snd", "audio/basic", "src", "application/x-wais-source", "sv4cpio", "application/x-sv4cpio", "sv4crc", "application/x-sv4crc", "svg", "image/svg+xml", "svgz", "image/svg+xml", "swf", "application/x-shockwave-flash", "t", "text/troff", "tar", "application/x-tar", "tcl", "application/x-tcl", "tex", "application/x-tex", "texi", "application/x-texinfo", "texinfo", "application/x-texinfo", "tif", "image/tiff", "tiff", "image/tiff", "tr", "text/troff", "tsv", "text/tab-separated-values", "txt", "text/plain", "ulw", "audio/basic", "ustar", "application/x-ustar", "vxml", "application/voicexml+xml", "xbm", "image/x-xbitmap", "xht", "application/xhtml+xml", "xhtml", "application/xhtml+xml", "xls", "application/vnd.ms-excel", "xml", "application/xml", "xpm", "image/x-xpixmap", "xsl", "application/xml", "xslt", "application/xslt+xml", "xul", "application/vnd.mozilla.xul+xml", "xwd", "image/x-xwindowdump", "vsd", "application/vnd.visio", "wav", "audio/x-wav", "wbmp", "image/vnd.wap.wbmp", "wml", "text/vnd.wap.wml", "wmlc", "application/vnd.wap.wmlc", "wmls", "text/vnd.wap.wmlsc", "wmlscriptc", "application/vnd.wap.wmlscriptc", "wmv", "video/x-ms-wmv", "wrl", "model/vrml", "wspolicy", "application/wspolicy+xml", "Z", "application/x-compress", "z", "application/x-compress", "zip", "application/zip" };

    protected URL getWebappConfigFile(String path, String contextName) {
        File docBase = new File(path);
        if (docBase.isDirectory()) {
            return getWebappConfigFileFromDirectory(docBase, contextName);
        } else {
            return getWebappConfigFileFromJar(docBase, contextName);
        }
    }

    private URL getWebappConfigFileFromDirectory(File docBase, String contextName) {
        URL result = null;
        File webAppContextXml = new File(docBase, Constants.ApplicationContextXml);
        if (webAppContextXml.exists()) {
            try {
                result = webAppContextXml.toURI().toURL();
            } catch (MalformedURLException e) {
                Logger.getLogger(getLoggerName(getHost(), contextName)).log(Level.WARNING, "Unable to determine web application context.xml " + docBase, e);
            }
        }
        return result;
    }

    private URL getWebappConfigFileFromJar(File docBase, String contextName) {
        URL result = null;
        JarFile jar = null;
        try {
            jar = new JarFile(docBase);
            JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
            if (entry != null) {
                result = UriUtil.buildJarUrl(docBase, Constants.ApplicationContextXml);
            }
        } catch (IOException e) {
            Logger.getLogger(getLoggerName(getHost(), contextName)).log(Level.WARNING, "Unable to determine web application context.xml " + docBase, e);
        } finally {
            if (jar != null) {
                try {
                    jar.close();
                } catch (IOException e) {
                // ignore
                }
            }
        }
        return result;
    }
}

17 Source : CombinedRealm.java
with Apache License 2.0
from wangyingjie

/**
 * Return the Principal replacedociated with the specified username, which
 * matches the digest calculated using the given parameters using the
 * method described in RFC 2069; otherwise return <code>null</code>.
 *
 * @param username Username of the Principal to look up
 * @param clientDigest Digest which has been submitted by the client
 * @param nonce Unique (or supposedly unique) token which has been used
 * for this request
 * @param realmName Realm name
 * @param md5a2 Second MD5 digest used to calculate the digest :
 * MD5(Method + ":" + uri)
 */
@Override
public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce, String qop, String realmName, String md5a2) {
    Principal authenticatedUser = null;
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
        }
        authenticatedUser = realm.authenticate(username, clientDigest, nonce, nc, cnonce, qop, realmName, md5a2);
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getInfo()));
            }
            break;
        }
    }
    return authenticatedUser;
}

17 Source : CombinedRealm.java
with Apache License 2.0
from wangyingjie

/**
 * Return the Principal replacedociated with the specified username and
 * credentials, if there is one; otherwise return <code>null</code>.
 *
 * @param username Username of the Principal to look up
 * @param credentials Preplacedword or other credentials to use in
 *  authenticating this username
 */
@Override
public Principal authenticate(String username, String credentials) {
    Principal authenticatedUser = null;
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
        }
        authenticatedUser = realm.authenticate(username, credentials);
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getInfo()));
            }
            break;
        }
    }
    return authenticatedUser;
}

17 Source : CombinedRealm.java
with Apache License 2.0
from wangyingjie

/**
 * Return the Principal replacedociated with the specified user name otherwise
 * return <code>null</code>.
 *
 * @param username User name of the Principal to look up
 */
@Override
public Principal authenticate(String username) {
    Principal authenticatedUser = null;
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getClreplaced().getName()));
        }
        authenticatedUser = realm.authenticate(username);
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getClreplaced().getName()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClreplaced().getName()));
            }
            break;
        }
    }
    return authenticatedUser;
}

17 Source : CombinedRealm.java
with Apache License 2.0
from wangyingjie

/**
 * Set the Container with which this Realm has been replacedociated.
 *
 * @param container The replacedociated Container
 */
@Override
public void setContainer(Container container) {
    for (Realm realm : realms) {
        // Set the realmPath for JMX naming
        if (realm instanceof RealmBase) {
            ((RealmBase) realm).setRealmPath(getRealmPath() + "/realm" + realms.indexOf(realm));
        }
        // Set the container for sub-realms. Mainly so logging works.
        realm.setContainer(container);
    }
    super.setContainer(container);
}

17 Source : AuthenticatorBase.java
with Apache License 2.0
from wangyingjie

/**
 * Attempts reauthentication to the <code>Realm</code> using
 * the credentials included in argument <code>entry</code>.
 *
 * @param ssoId identifier of SingleSignOn session with which the
 *              caller is replacedociated
 * @param request   the request that needs to be authenticated
 */
protected boolean reauthenticateFromSSO(String ssoId, Request request) {
    if (sso == null || ssoId == null)
        return false;
    boolean reauthenticated = false;
    Container parent = getContainer();
    if (parent != null) {
        Realm realm = parent.getRealm();
        if (realm != null) {
            reauthenticated = sso.reauthenticate(ssoId, realm, request);
        }
    }
    if (reauthenticated) {
        replacedociate(ssoId, request.getSessionInternal(true));
        if (log.isDebugEnabled()) {
            log.debug(" Reauthenticated cached principal '" + request.getUserPrincipal().getName() + "' with auth type '" + request.getAuthType() + "'");
        }
    }
    return reauthenticated;
}

17 Source : Tomcat.java
with Apache License 2.0
from tryandcatch

// TODO: lazy init for the temp dir - only when a JSP is compiled or
// get temp dir is called we need to create it. This will avoid the
// need for the baseDir
// TODO: allow contexts without a base dir - i.e.
// only programmatic. This would disable the default servlet.
/**
 * Minimal tomcat starter for embedding/unit tests.
 *
 * Tomcat supports multiple styles of configuration and
 * startup - the most common and stable is server.xml-based,
 * implemented in org.apache.catalina.startup.Bootstrap.
 *
 * This clreplaced is for use in apps that embed tomcat.
 * Requirements:
 *
 * - all tomcat clreplacedes and possibly servlets are in the clreplacedpath.
 * ( for example all is in one big jar, or in eclipse CP, or in any other
 * combination )
 *
 * - we need one temporary directory for work files
 *
 * - no config file is required. This clreplaced provides methods to
 * use if you have a webapp with a web.xml file, but it is
 * optional - you can use your own servlets.
 *
 * There are a variety of 'add' methods to configure servlets and webapps. These
 * methods, by default, create a simple in-memory security realm and apply it.
 * If you need more complex security processing, you can define a subclreplaced of
 * this clreplaced.
 *
 * This clreplaced provides a set of convenience methods for configuring webapp
 * contexts, all overloads of the method <pre>addWebapp</pre>. These methods
 * create a webapp context, configure it, and then add it to a {@link Host}.
 * They do not use a global default web.xml; rather, they add a lifecycle
 * listener that adds the standard DefaultServlet, JSP processing, and welcome
 * files.
 *
 * In complex cases, you may prefer to use the ordinary Tomcat API to create
 * webapp contexts; for example, you might need to install a custom Loader
 * before the call to {@link Host#addChild(Container)}. To replicate the basic
 * behavior of the <pre>addWebapp</pre> methods, you may want to call two
 * methods of this clreplaced: {@link #noDefaultWebXmlPath()} and
 * {@link #getDefaultWebXmlListener()}.
 *
 * {@link #getDefaultRealm()} returns the simple security realm.
 *
 * {@link #getDefaultWebXmlListener()} returns a {@link LifecycleListener} that
 * adds the standard DefaultServlet, JSP processing, and welcome files. If you
 * add this listener, you must prevent Tomcat from applying any standard global
 * web.xml with ...
 *
 * {@link #noDefaultWebXmlPath()} returns a dummy pathname to configure to
 * prevent {@link ContextConfig} from trying to apply a global web.xml file.
 *
 * This clreplaced provides a main() and few simple CLI arguments,
 * see setters for doc. It can be used for simple tests and
 * demo.
 *
 * @see <a href="http://svn.apache.org/repos/asf/tomcat/trunk/test/org/apache/catalina/startup/TestTomcat.java">TestTomcat</a>
 * @author Costin Manolache
 */
public clreplaced Tomcat {

    // Some logging implementations use weak references for loggers so there is
    // the possibility that logging configuration could be lost if GC runs just
    // after Loggers are configured but before they are used. The purpose of
    // this Map is to retain strong references to explicitly configured loggers
    // so that configuration is not lost.
    private final Map<String, Logger> pinnedLoggers = new HashMap<String, Logger>();

    // Single engine, service, server, connector - few cases need more,
    // they can use server.xml
    protected Server server;

    protected Service service;

    protected Engine engine;

    // for more - customize the clreplacedes
    protected Connector connector;

    // To make it a bit easier to config for the common case
    // ( one host, one context ).
    protected Host host;

    // TODO: it's easy to add support for more hosts - but is it
    // really needed ?
    // TODO: allow use of in-memory connector
    protected int port = 8080;

    protected String hostname = "localhost";

    protected String basedir;

    // Default in-memory realm, will be set by default on the Engine. Can be
    // replaced at engine level or over-ridden at Host or Context level
    // Will be removed in Tomcat 8.0.x.
    @Deprecated
    protected Realm defaultRealm;

    private final Map<String, String> userPreplaced = new HashMap<String, String>();

    private final Map<String, List<String>> userRoles = new HashMap<String, List<String>>();

    private final Map<String, Principal> userPrincipals = new HashMap<String, Principal>();

    public Tomcat() {
    // NOOP
    }

    /**
     * Tomcat needs a directory for temp files. This should be the
     * first method called.
     *
     * By default, if this method is not called, we use:
     *  - system properties - catalina.base, catalina.home
     *  - $HOME/tomcat.$PORT
     * ( /tmp doesn't seem a good choice for security ).
     *
     * TODO: better default ? Maybe current dir ?
     * TODO: disable work dir if not needed ( no jsp, etc ).
     */
    public void setBaseDir(String basedir) {
        this.basedir = basedir;
    }

    /**
     * Set the port for the default connector. Must
     * be called before start().
     */
    public void setPort(int port) {
        this.port = port;
    }

    /**
     * The the hostname of the default host, default is
     * 'localhost'.
     */
    public void setHostname(String s) {
        hostname = s;
    }

    /**
     * This is equivalent to adding a web application to Tomcat's webapps
     * directory. The equivalent of the default web.xml will be applied  to the
     * web application and any WEB-INF/web.xml and META-INF/context.xml packaged
     * with the application will be processed normally. Normal web fragment and
     * {@link javax.servlet.ServletContainerInitializer} processing will be
     * applied.
     *
     * @throws ServletException
     */
    public Context addWebapp(String contextPath, String docBase) throws ServletException {
        return addWebapp(getHost(), contextPath, docBase);
    }

    /**
     * Add a context - programmatic mode, no web.xml used.
     *
     * API calls equivalent with web.xml:
     *
     * context-param
     *  ctx.addParameter("name", "value");
     *
     * error-page
     *    ErrorPage ep = new ErrorPage();
     *    ep.setErrorCode(500);
     *    ep.setLocation("/error.html");
     *    ctx.addErrorPage(ep);
     *
     * ctx.addMimeMapping("ext", "type");
     *
     * Note: If you reload the Context, all your configuration will be lost. If
     * you need reload support, consider using a LifecycleListener to provide
     * your configuration.
     *
     * TODO: add the rest
     *
     *  @param contextPath "" for root context.
     *  @param docBase base dir for the context, for static files. Must exist,
     *  relative to the server home
     */
    public Context addContext(String contextPath, String docBase) {
        return addContext(getHost(), contextPath, docBase);
    }

    /**
     * Equivalent with
     *  <servlet><servlet-name><servlet-clreplaced>.
     *
     * In general it is better/faster to use the method that takes a
     * Servlet as param - this one can be used if the servlet is not
     * commonly used, and want to avoid loading all deps.
     * ( for example: jsp servlet )
     *
     * You can customize the returned servlet, ex:
     *
     *    wrapper.addInitParameter("name", "value");
     *
     * @param contextPath   Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servletClreplaced  The clreplaced to be used for the Servlet
     * @return The wrapper for the servlet
     */
    public Wrapper addServlet(String contextPath, String servletName, String servletClreplaced) {
        Container ctx = getHost().findChild(contextPath);
        return addServlet((Context) ctx, servletName, servletClreplaced);
    }

    /**
     * Static version of {@link #addServlet(String, String, String)}
     * @param ctx           Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servletClreplaced  The clreplaced to be used for the Servlet
     * @return The wrapper for the servlet
     */
    public static Wrapper addServlet(Context ctx, String servletName, String servletClreplaced) {
        // will do clreplaced for name and set init params
        Wrapper sw = ctx.createWrapper();
        sw.setServletClreplaced(servletClreplaced);
        sw.setName(servletName);
        ctx.addChild(sw);
        return sw;
    }

    /**
     * Add an existing Servlet to the context with no clreplaced.forName or
     * initialisation.
     * @param contextPath   Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servlet       The Servlet to add
     * @return The wrapper for the servlet
     */
    public Wrapper addServlet(String contextPath, String servletName, Servlet servlet) {
        Container ctx = getHost().findChild(contextPath);
        return addServlet((Context) ctx, servletName, servlet);
    }

    /**
     * Static version of {@link #addServlet(String, String, Servlet)}.
     * @param ctx           Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servlet       The Servlet to add
     * @return The wrapper for the servlet
     */
    public static Wrapper addServlet(Context ctx, String servletName, Servlet servlet) {
        // will do clreplaced for name and set init params
        Wrapper sw = new ExistingStandardWrapper(servlet);
        sw.setName(servletName);
        ctx.addChild(sw);
        return sw;
    }

    /**
     * Initialise the server.
     *
     * @throws LifecycleException
     */
    public void init() throws LifecycleException {
        getServer();
        getConnector();
        server.init();
    }

    /**
     * Start the server.
     *
     * @throws LifecycleException
     */
    public void start() throws LifecycleException {
        getServer();
        getConnector();
        server.start();
    }

    /**
     * Stop the server.
     *
     * @throws LifecycleException
     */
    public void stop() throws LifecycleException {
        getServer();
        server.stop();
    }

    /**
     * Destroy the server. This object cannot be used once this method has been
     * called.
     */
    public void destroy() throws LifecycleException {
        getServer();
        server.destroy();
    // Could null out objects here
    }

    /**
     * Add a user for the in-memory realm. All created apps use this
     * by default, can be replaced using setRealm().
     */
    public void addUser(String user, String preplaced) {
        userPreplaced.put(user, preplaced);
    }

    /**
     * @see #addUser(String, String)
     */
    public void addRole(String user, String role) {
        List<String> roles = userRoles.get(user);
        if (roles == null) {
            roles = new ArrayList<String>();
            userRoles.put(user, roles);
        }
        roles.add(role);
    }

    // ------- Extra customization -------
    // You can tune individual tomcat objects, using internal APIs
    /**
     * Get the default http connector. You can set more
     * parameters - the port is already initialized.
     *
     * Alternatively, you can construct a Connector and set any params,
     * then call addConnector(Connector)
     *
     * @return A connector object that can be customized
     */
    public Connector getConnector() {
        getServer();
        if (connector != null) {
            return connector;
        }
        // This will load Apr connector if available,
        // default to nio. I'm having strange problems with apr
        // XXX: jfclere weird... Don't add the AprLifecycleListener then.
        // and for the use case the speed benefit wouldn't matter.
        connector = new Connector("HTTP/1.1");
        // connector = new Connector("org.apache.coyote.http11.Http11Protocol");
        connector.setPort(port);
        service.addConnector(connector);
        return connector;
    }

    public void setConnector(Connector connector) {
        this.connector = connector;
    }

    /**
     * Get the service object. Can be used to add more
     * connectors and few other global settings.
     */
    public Service getService() {
        getServer();
        return service;
    }

    /**
     * Sets the current host - all future webapps will
     * be added to this host. When tomcat starts, the
     * host will be the default host.
     *
     * @param host
     */
    public void setHost(Host host) {
        this.host = host;
    }

    public Host getHost() {
        if (host == null) {
            host = new StandardHost();
            host.setName(hostname);
            getEngine().addChild(host);
        }
        return host;
    }

    /**
     * Set a custom realm for auth. If not called, a simple
     * default will be used, using an internal map.
     *
     * Must be called before adding a context.
     *
     * @deprecated Will be removed in Tomcat 8.0.x.
     */
    @Deprecated
    public void setDefaultRealm(Realm realm) {
        defaultRealm = realm;
    }

    /**
     * Access to the engine, for further customization.
     */
    public Engine getEngine() {
        if (engine == null) {
            getServer();
            engine = new StandardEngine();
            engine.setName("Tomcat");
            engine.setDefaultHost(hostname);
            if (defaultRealm == null) {
                initSimpleAuth();
            }
            engine.setRealm(defaultRealm);
            service.setContainer(engine);
        }
        return engine;
    }

    /**
     * Get the server object. You can add listeners and few more
     * customizations. JNDI is disabled by default.
     */
    public Server getServer() {
        if (server != null) {
            return server;
        }
        initBaseDir();
        System.setProperty("catalina.useNaming", "false");
        server = new StandardServer();
        server.setPort(-1);
        service = new StandardService();
        service.setName("Tomcat");
        server.addService(service);
        return server;
    }

    public Context addContext(Host host, String contextPath, String dir) {
        return addContext(host, contextPath, contextPath, dir);
    }

    public Context addContext(Host host, String contextPath, String contextName, String dir) {
        silence(host, contextPath);
        Context ctx = createContext(host, contextPath);
        ctx.setName(contextName);
        ctx.setPath(contextPath);
        ctx.setDocBase(dir);
        ctx.addLifecycleListener(new FixContextListener());
        if (host == null) {
            getHost().addChild(ctx);
        } else {
            host.addChild(ctx);
        }
        return ctx;
    }

    public Context addWebapp(Host host, String contextPath, String docBase) {
        return addWebapp(host, contextPath, contextPath, docBase);
    }

    /**
     * @see #addWebapp(String, String)
     *
     * @param name Ignored. The contextPath will be used
     *
     * @deprecated Use {@link #addWebapp(Host, String, String)}
     */
    @Deprecated
    public Context addWebapp(Host host, String contextPath, String name, String docBase) {
        silence(host, contextPath);
        Context ctx = createContext(host, contextPath);
        ctx.setPath(contextPath);
        ctx.setDocBase(docBase);
        ctx.addLifecycleListener(new DefaultWebXmlListener());
        ctx.setConfigFile(getWebappConfigFile(docBase, contextPath));
        ContextConfig ctxCfg = new ContextConfig();
        ctx.addLifecycleListener(ctxCfg);
        // prevent it from looking ( if it finds one - it'll have dup error )
        ctxCfg.setDefaultWebXml(noDefaultWebXmlPath());
        if (host == null) {
            getHost().addChild(ctx);
        } else {
            host.addChild(ctx);
        }
        return ctx;
    }

    /**
     * Return a listener that provides the required configuration items for JSP
     * processing. From the standard Tomcat global web.xml. Preplaced this to
     * {@link Context#addLifecycleListener(LifecycleListener)} and then preplaced the
     * result of {@link #noDefaultWebXmlPath()} to
     * {@link ContextConfig#setDefaultWebXml(String)}.
     * @return a listener object that configures default JSP processing.
     */
    public LifecycleListener getDefaultWebXmlListener() {
        return new DefaultWebXmlListener();
    }

    /**
     * @return a pathname to preplaced to
     * {@link ContextConfig#setDefaultWebXml(String)} when using
     * {@link #getDefaultWebXmlListener()}.
     */
    public String noDefaultWebXmlPath() {
        return Constants.NoDefaultWebXml;
    }

    /**
     * For complex configurations, this accessor allows callers of this clreplaced
     * to obtain the simple realm created by default.
     * @return the simple in-memory realm created by default.
     * @deprecated Will be removed in Tomcat 8.0.x
     */
    @Deprecated
    public Realm getDefaultRealm() {
        if (defaultRealm == null) {
            initSimpleAuth();
        }
        return defaultRealm;
    }

    // ---------- Helper methods and clreplacedes -------------------
    /**
     * Create an in-memory realm. You can replace it for contexts with a real
     * one. The Realm created here will be added to the Engine by default and
     * may be replaced at the Engine level or over-ridden (as per normal Tomcat
     * behaviour) at the Host or Context level.
     * @deprecated Will be removed in Tomcat 8.0.x
     */
    @Deprecated
    protected void initSimpleAuth() {
        defaultRealm = new RealmBase() {

            @Override
            protected String getName() {
                return "Simple";
            }

            @Override
            protected String getPreplacedword(String username) {
                return userPreplaced.get(username);
            }

            @Override
            protected Principal getPrincipal(String username) {
                Principal p = userPrincipals.get(username);
                if (p == null) {
                    String preplaced = userPreplaced.get(username);
                    if (preplaced != null) {
                        p = new GenericPrincipal(username, preplaced, userRoles.get(username));
                        userPrincipals.put(username, p);
                    }
                }
                return p;
            }
        };
    }

    protected void initBaseDir() {
        String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP);
        if (basedir == null) {
            basedir = System.getProperty(Globals.CATALINA_BASE_PROP);
        }
        if (basedir == null) {
            basedir = catalinaHome;
        }
        if (basedir == null) {
            // Create a temp dir.
            basedir = System.getProperty("user.dir") + "/tomcat." + port;
            File home = new File(basedir);
            home.mkdir();
            if (!home.isAbsolute()) {
                try {
                    basedir = home.getCanonicalPath();
                } catch (IOException e) {
                    basedir = home.getAbsolutePath();
                }
            }
        }
        if (catalinaHome == null) {
            System.setProperty(Globals.CATALINA_HOME_PROP, basedir);
        }
        System.setProperty(Globals.CATALINA_BASE_PROP, basedir);
    }

    static final String[] silences = new String[] { "org.apache.coyote.http11.Http11Protocol", "org.apache.catalina.core.StandardService", "org.apache.catalina.core.StandardEngine", "org.apache.catalina.startup.ContextConfig", "org.apache.catalina.core.ApplicationContext", "org.apache.catalina.core.AprLifecycleListener" };

    /**
     * Controls if the loggers will be silenced or not.
     * @param silent    <code>true</code> sets the log level to WARN for the
     *                  loggers that log information on Tomcat start up. This
     *                  prevents the usual startup information being logged.
     *                  <code>false</code> sets the log level to the default
     *                  level of INFO.
     */
    public void setSilent(boolean silent) {
        for (String s : silences) {
            Logger logger = Logger.getLogger(s);
            pinnedLoggers.put(s, logger);
            if (silent) {
                logger.setLevel(Level.WARNING);
            } else {
                logger.setLevel(Level.INFO);
            }
        }
    }

    private void silence(Host host, String ctx) {
        String loggerName = getLoggerName(host, ctx);
        Logger logger = Logger.getLogger(loggerName);
        pinnedLoggers.put(loggerName, logger);
        logger.setLevel(Level.WARNING);
    }

    private String getLoggerName(Host host, String ctx) {
        String loggerName = "org.apache.catalina.core.ContainerBase.[default].[";
        if (host == null) {
            loggerName += getHost().getName();
        } else {
            loggerName += host.getName();
        }
        loggerName += "].[";
        loggerName += ctx;
        loggerName += "]";
        return loggerName;
    }

    /**
     * Create the configured {@link Context} for the given <code>host</code>.
     * The default constructor of the clreplaced that was configured with
     * {@link StandardHost#setContextClreplaced(String)} will be used
     *
     * @param host
     *            host for which the {@link Context} should be created, or
     *            <code>null</code> if default host should be used
     * @param url
     *            path of the webapp which should get the {@link Context}
     * @return newly created {@link Context}
     */
    private Context createContext(Host host, String url) {
        String contextClreplaced = StandardContext.clreplaced.getName();
        if (host == null) {
            host = this.getHost();
        }
        if (host instanceof StandardHost) {
            contextClreplaced = ((StandardHost) host).getContextClreplaced();
        }
        try {
            return (Context) Clreplaced.forName(contextClreplaced).getConstructor().newInstance();
        } catch (InstantiationException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (InvocationTargetException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (SecurityException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (ClreplacedNotFoundException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        }
    }

    /**
     * Enables JNDI naming which is disabled by default. Server must implement
     * {@link Lifecycle} in order for the {@link NamingContextListener} to be
     * used.
     */
    public void enableNaming() {
        // Make sure getServer() has been called as that is where naming is
        // disabled
        getServer();
        server.addLifecycleListener(new NamingContextListener());
        System.setProperty("catalina.useNaming", "true");
        String value = "org.apache.naming";
        String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
        if (oldValue != null) {
            if (oldValue.contains(value)) {
                value = oldValue;
            } else {
                value = value + ":" + oldValue;
            }
        }
        System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
        value = System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
        if (value == null) {
            System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        }
    }

    /**
     * Provide default configuration for a context. This is the programmatic
     * equivalent of the default web.xml.
     *
     *  TODO: in normal Tomcat, if default-web.xml is not found, use this
     *  method
     *
     * @param contextPath   The context to set the defaults for
     */
    public void initWebappDefaults(String contextPath) {
        Container ctx = getHost().findChild(contextPath);
        initWebappDefaults((Context) ctx);
    }

    /**
     * Static version of {@link #initWebappDefaults(String)}
     * @param ctx   The context to set the defaults for
     */
    public static void initWebappDefaults(Context ctx) {
        // Default servlet
        Wrapper servlet = addServlet(ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
        servlet.setLoadOnStartup(1);
        servlet.setOverridable(true);
        // JSP servlet (by clreplaced name - to avoid loading all deps)
        servlet = addServlet(ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
        servlet.addInitParameter("fork", "false");
        servlet.setLoadOnStartup(3);
        servlet.setOverridable(true);
        // Servlet mappings
        ctx.addServletMapping("/", "default");
        ctx.addServletMapping("*.jsp", "jsp");
        ctx.addServletMapping("*.jspx", "jsp");
        // Sessions
        ctx.setSessionTimeout(30);
        // MIME mappings
        for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length; ) {
            ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++], DEFAULT_MIME_MAPPINGS[i++]);
        }
        // Welcome files
        ctx.addWelcomeFile("index.html");
        ctx.addWelcomeFile("index.htm");
        ctx.addWelcomeFile("index.jsp");
    }

    /**
     * Fix startup sequence - required if you don't use web.xml.
     *
     * The start() method in context will set 'configured' to false - and
     * expects a listener to set it back to true.
     */
    public static clreplaced FixContextListener implements LifecycleListener {

        @Override
        public void lifecycleEvent(LifecycleEvent event) {
            try {
                Context context = (Context) event.getLifecycle();
                if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
                    context.setConfigured(true);
                }
                // LoginConfig is required to process @ServletSecurity
                // annotations
                if (context.getLoginConfig() == null) {
                    context.setLoginConfig(new LoginConfig("NONE", null, null, null));
                    context.getPipeline().addValve(new NonLoginAuthenticator());
                }
            } catch (ClreplacedCastException e) {
                return;
            }
        }
    }

    /**
     * Fix reload - required if reloading and using programmatic configuration.
     * When a context is reloaded, any programmatic configuration is lost. This
     * listener sets the equivalent of conf/web.xml when the context starts.
     */
    public static clreplaced DefaultWebXmlListener implements LifecycleListener {

        @Override
        public void lifecycleEvent(LifecycleEvent event) {
            if (Lifecycle.BEFORE_START_EVENT.equals(event.getType())) {
                initWebappDefaults((Context) event.getLifecycle());
            }
        }
    }

    /**
     * Helper clreplaced for wrapping existing servlets. This disables servlet
     * lifecycle and normal reloading, but also reduces overhead and provide
     * more direct control over the servlet.
     */
    public static clreplaced ExistingStandardWrapper extends StandardWrapper {

        private final Servlet existing;

        @SuppressWarnings("deprecation")
        public ExistingStandardWrapper(Servlet existing) {
            this.existing = existing;
            if (existing instanceof javax.servlet.SingleThreadModel) {
                singleThreadModel = true;
                instancePool = new Stack<Servlet>();
            }
        }

        @Override
        public synchronized Servlet loadServlet() throws ServletException {
            if (singleThreadModel) {
                Servlet instance;
                try {
                    instance = existing.getClreplaced().newInstance();
                } catch (InstantiationException e) {
                    throw new ServletException(e);
                } catch (IllegalAccessException e) {
                    throw new ServletException(e);
                }
                instance.init(facade);
                return instance;
            } else {
                if (!instanceInitialized) {
                    existing.init(facade);
                    instanceInitialized = true;
                }
                return existing;
            }
        }

        @Override
        public long getAvailable() {
            return 0;
        }

        @Override
        public boolean isUnavailable() {
            return false;
        }

        @Override
        public Servlet getServlet() {
            return existing;
        }

        @Override
        public String getServletClreplaced() {
            return existing.getClreplaced().getName();
        }
    }

    /**
     * TODO: would a properties resource be better ? Or just parsing
     * /etc/mime.types ?
     * This is needed because we don't use the default web.xml, where this
     * is encoded.
     */
    private static final String[] DEFAULT_MIME_MAPPINGS = { "abs", "audio/x-mpeg", "ai", "application/postscript", "aif", "audio/x-aiff", "aifc", "audio/x-aiff", "aiff", "audio/x-aiff", "aim", "application/x-aim", "art", "image/x-jg", "asf", "video/x-ms-asf", "asx", "video/x-ms-asf", "au", "audio/basic", "avi", "video/x-msvideo", "avx", "video/x-rad-screenplay", "bcpio", "application/x-bcpio", "bin", "application/octet-stream", "bmp", "image/bmp", "body", "text/html", "cdf", "application/x-cdf", "cer", "application/pkix-cert", "clreplaced", "application/java", "cpio", "application/x-cpio", "csh", "application/x-csh", "css", "text/css", "dib", "image/bmp", "doc", "application/msword", "dtd", "application/xml-dtd", "dv", "video/x-dv", "dvi", "application/x-dvi", "eps", "application/postscript", "etx", "text/x-setext", "exe", "application/octet-stream", "gif", "image/gif", "gtar", "application/x-gtar", "gz", "application/x-gzip", "hdf", "application/x-hdf", "hqx", "application/mac-binhex40", "htc", "text/x-component", "htm", "text/html", "html", "text/html", "ief", "image/ief", "jad", "text/vnd.sun.j2me.app-descriptor", "jar", "application/java-archive", "java", "text/x-java-source", "jnlp", "application/x-java-jnlp-file", "jpe", "image/jpeg", "jpeg", "image/jpeg", "jpg", "image/jpeg", "js", "application/javascript", "jsf", "text/plain", "jspf", "text/plain", "kar", "audio/midi", "latex", "application/x-latex", "m3u", "audio/x-mpegurl", "mac", "image/x-macpaint", "man", "text/troff", "mathml", "application/mathml+xml", "me", "text/troff", "mid", "audio/midi", "midi", "audio/midi", "mif", "application/x-mif", "mov", "video/quicktime", "movie", "video/x-sgi-movie", "mp1", "audio/mpeg", "mp2", "audio/mpeg", "mp3", "audio/mpeg", "mp4", "video/mp4", "mpa", "audio/mpeg", "mpe", "video/mpeg", "mpeg", "video/mpeg", "mpega", "audio/x-mpeg", "mpg", "video/mpeg", "mpv2", "video/mpeg2", "nc", "application/x-netcdf", "oda", "application/oda", "odb", "application/vnd.oasis.opendoreplacedent.database", "odc", "application/vnd.oasis.opendoreplacedent.chart", "odf", "application/vnd.oasis.opendoreplacedent.formula", "odg", "application/vnd.oasis.opendoreplacedent.graphics", "odi", "application/vnd.oasis.opendoreplacedent.image", "odm", "application/vnd.oasis.opendoreplacedent.text-master", "odp", "application/vnd.oasis.opendoreplacedent.presentation", "ods", "application/vnd.oasis.opendoreplacedent.spreadsheet", "odt", "application/vnd.oasis.opendoreplacedent.text", "otg", "application/vnd.oasis.opendoreplacedent.graphics-template", "oth", "application/vnd.oasis.opendoreplacedent.text-web", "otp", "application/vnd.oasis.opendoreplacedent.presentation-template", "ots", "application/vnd.oasis.opendoreplacedent.spreadsheet-template ", "ott", "application/vnd.oasis.opendoreplacedent.text-template", "ogx", "application/ogg", "ogv", "video/ogg", "oga", "audio/ogg", "ogg", "audio/ogg", "spx", "audio/ogg", "flac", "audio/flac", "anx", "application/annodex", "axa", "audio/annodex", "axv", "video/annodex", "xspf", "application/xspf+xml", "pbm", "image/x-portable-bitmap", "pct", "image/pict", "pdf", "application/pdf", "pgm", "image/x-portable-graymap", "pic", "image/pict", "pict", "image/pict", "pls", "audio/x-scpls", "png", "image/png", "pnm", "image/x-portable-anymap", "pnt", "image/x-macpaint", "ppm", "image/x-portable-pixmap", "ppt", "application/vnd.ms-powerpoint", "pps", "application/vnd.ms-powerpoint", "ps", "application/postscript", "psd", "image/vnd.adobe.photoshop", "qt", "video/quicktime", "qti", "image/x-quicktime", "qtif", "image/x-quicktime", "ras", "image/x-cmu-raster", "rdf", "application/rdf+xml", "rgb", "image/x-rgb", "rm", "application/vnd.rn-realmedia", "roff", "text/troff", "rtf", "application/rtf", "rtx", "text/richtext", "sh", "application/x-sh", "shar", "application/x-shar", /*"shtml", "text/x-server-parsed-html",*/
    "sit", "application/x-stuffit", "snd", "audio/basic", "src", "application/x-wais-source", "sv4cpio", "application/x-sv4cpio", "sv4crc", "application/x-sv4crc", "svg", "image/svg+xml", "svgz", "image/svg+xml", "swf", "application/x-shockwave-flash", "t", "text/troff", "tar", "application/x-tar", "tcl", "application/x-tcl", "tex", "application/x-tex", "texi", "application/x-texinfo", "texinfo", "application/x-texinfo", "tif", "image/tiff", "tiff", "image/tiff", "tr", "text/troff", "tsv", "text/tab-separated-values", "txt", "text/plain", "ulw", "audio/basic", "ustar", "application/x-ustar", "vxml", "application/voicexml+xml", "xbm", "image/x-xbitmap", "xht", "application/xhtml+xml", "xhtml", "application/xhtml+xml", "xls", "application/vnd.ms-excel", "xml", "application/xml", "xpm", "image/x-xpixmap", "xsl", "application/xml", "xslt", "application/xslt+xml", "xul", "application/vnd.mozilla.xul+xml", "xwd", "image/x-xwindowdump", "vsd", "application/vnd.visio", "wav", "audio/x-wav", "wbmp", "image/vnd.wap.wbmp", "wml", "text/vnd.wap.wml", "wmlc", "application/vnd.wap.wmlc", "wmls", "text/vnd.wap.wmlsc", "wmlscriptc", "application/vnd.wap.wmlscriptc", "wmv", "video/x-ms-wmv", "wrl", "model/vrml", "wspolicy", "application/wspolicy+xml", "Z", "application/x-compress", "z", "application/x-compress", "zip", "application/zip" };

    protected URL getWebappConfigFile(String path, String url) {
        File docBase = new File(path);
        if (docBase.isDirectory()) {
            return getWebappConfigFileFromDirectory(docBase, url);
        } else {
            return getWebappConfigFileFromJar(docBase, url);
        }
    }

    private URL getWebappConfigFileFromDirectory(File docBase, String url) {
        URL result = null;
        File webAppContextXml = new File(docBase, Constants.ApplicationContextXml);
        if (webAppContextXml.exists()) {
            try {
                result = webAppContextXml.toURI().toURL();
            } catch (MalformedURLException e) {
                Logger.getLogger(getLoggerName(getHost(), url)).log(Level.WARNING, "Unable to determine web application context.xml " + docBase, e);
            }
        }
        return result;
    }

    private URL getWebappConfigFileFromJar(File docBase, String url) {
        URL result = null;
        JarFile jar = null;
        try {
            jar = new JarFile(docBase);
            JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
            if (entry != null) {
                result = new URL("jar:" + docBase.toURI().toString() + "!/" + Constants.ApplicationContextXml);
            }
        } catch (IOException e) {
            Logger.getLogger(getLoggerName(getHost(), url)).log(Level.WARNING, "Unable to determine web application context.xml " + docBase, e);
        } finally {
            if (jar != null) {
                try {
                    jar.close();
                } catch (IOException e) {
                // ignore
                }
            }
        }
        return result;
    }
}

17 Source : ContainerBase.java
with Apache License 2.0
from tryandcatch

/**
 * Set the Realm with which this Container is replacedociated.
 *
 * @param realm The newly replacedociated Realm
 */
@Override
public void setRealm(Realm realm) {
    Lock l = realmLock.writeLock();
    try {
        l.lock();
        // Change components if necessary
        Realm oldRealm = this.realm;
        if (oldRealm == realm)
            return;
        this.realm = realm;
        // Stop the old component if necessary
        if (getState().isAvailable() && (oldRealm != null) && (oldRealm instanceof Lifecycle)) {
            try {
                ((Lifecycle) oldRealm).stop();
            } catch (LifecycleException e) {
                log.error("ContainerBase.setRealm: stop: ", e);
            }
        }
        // Start the new component if necessary
        if (realm != null)
            realm.setContainer(this);
        if (getState().isAvailable() && (realm != null) && (realm instanceof Lifecycle)) {
            try {
                ((Lifecycle) realm).start();
            } catch (LifecycleException e) {
                log.error("ContainerBase.setRealm: start: ", e);
            }
        }
        // Report this property change to interested listeners
        support.firePropertyChange("realm", oldRealm, this.realm);
    } finally {
        l.unlock();
    }
}

17 Source : ContainerBase.java
with Apache License 2.0
from tryandcatch

@Override
protected void destroyInternal() throws LifecycleException {
    if ((manager != null) && (manager instanceof Lifecycle)) {
        ((Lifecycle) manager).destroy();
    }
    Realm realm = getRealmInternal();
    if ((realm != null) && (realm instanceof Lifecycle)) {
        ((Lifecycle) realm).destroy();
    }
    if ((cluster != null) && (cluster instanceof Lifecycle)) {
        ((Lifecycle) cluster).destroy();
    }
    if ((loader != null) && (loader instanceof Lifecycle)) {
        ((Lifecycle) loader).destroy();
    }
    // Stop the Valves in our pipeline (including the basic), if any
    if (pipeline instanceof Lifecycle) {
        ((Lifecycle) pipeline).destroy();
    }
    // Remove children now this container is being destroyed
    for (Container child : findChildren()) {
        removeChild(child);
    }
    // Required if the child is destroyed directly.
    if (parent != null) {
        parent.removeChild(this);
    }
    // If init fails, this may be null
    if (startStopExecutor != null) {
        startStopExecutor.shutdownNow();
    }
    super.destroyInternal();
}

17 Source : CombinedRealm.java
with Apache License 2.0
from how2j

/**
 * Return the Principal replacedociated with the specified user name otherwise
 * return <code>null</code>.
 *
 * @param username
 *            User name of the Principal to look up
 */
@Override
public Principal authenticate(String username) {
    Principal authenticatedUser = null;
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getClreplaced().getName()));
        }
        authenticatedUser = realm.authenticate(username);
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getClreplaced().getName()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClreplaced().getName()));
            }
            break;
        }
    }
    return authenticatedUser;
}

17 Source : CombinedRealm.java
with Apache License 2.0
from how2j

/**
 * Return the Principal replacedociated with the specified username, which
 * matches the digest calculated using the given parameters using the method
 * described in RFC 2069; otherwise return <code>null</code>.
 *
 * @param username
 *            Username of the Principal to look up
 * @param clientDigest
 *            Digest which has been submitted by the client
 * @param nonce
 *            Unique (or supposedly unique) token which has been used for
 *            this request
 * @param realmName
 *            Realm name
 * @param md5a2
 *            Second MD5 digest used to calculate the digest : MD5(Method +
 *            ":" + uri)
 */
@Override
public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce, String qop, String realmName, String md5a2) {
    Principal authenticatedUser = null;
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
        }
        authenticatedUser = realm.authenticate(username, clientDigest, nonce, nc, cnonce, qop, realmName, md5a2);
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getInfo()));
            }
            break;
        }
    }
    return authenticatedUser;
}

17 Source : CombinedRealm.java
with Apache License 2.0
from how2j

/**
 * Set the Container with which this Realm has been replacedociated.
 *
 * @param container
 *            The replacedociated Container
 */
@Override
public void setContainer(Container container) {
    for (Realm realm : realms) {
        // Set the realmPath for JMX naming
        if (realm instanceof RealmBase) {
            ((RealmBase) realm).setRealmPath(getRealmPath() + "/realm" + realms.indexOf(realm));
        }
        // Set the container for sub-realms. Mainly so logging works.
        realm.setContainer(container);
    }
    super.setContainer(container);
}

17 Source : CombinedRealm.java
with Apache License 2.0
from how2j

/**
 * Return the Principal replacedociated with the specified username and
 * credentials, if there is one; otherwise return <code>null</code>.
 *
 * @param username
 *            Username of the Principal to look up
 * @param credentials
 *            Preplacedword or other credentials to use in authenticating this
 *            username
 */
@Override
public Principal authenticate(String username, String credentials) {
    Principal authenticatedUser = null;
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
        }
        authenticatedUser = realm.authenticate(username, credentials);
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getInfo()));
            }
            break;
        }
    }
    return authenticatedUser;
}

17 Source : ContainerBase.java
with Apache License 2.0
from how2j

/**
 * Set the Realm with which this Container is replacedociated.
 *
 * @param realm
 *            The newly replacedociated Realm
 */
@Override
public void setRealm(Realm realm) {
    Lock l = realmLock.writeLock();
    try {
        l.lock();
        // Change components if necessary
        Realm oldRealm = this.realm;
        if (oldRealm == realm)
            return;
        this.realm = realm;
        // Stop the old component if necessary
        if (getState().isAvailable() && (oldRealm != null) && (oldRealm instanceof Lifecycle)) {
            try {
                ((Lifecycle) oldRealm).stop();
            } catch (LifecycleException e) {
                log.error("ContainerBase.setRealm: stop: ", e);
            }
        }
        // Start the new component if necessary
        if (realm != null)
            realm.setContainer(this);
        if (getState().isAvailable() && (realm != null) && (realm instanceof Lifecycle)) {
            try {
                ((Lifecycle) realm).start();
            } catch (LifecycleException e) {
                log.error("ContainerBase.setRealm: start: ", e);
            }
        }
        // Report this property change to interested listeners
        support.firePropertyChange("realm", oldRealm, this.realm);
    } finally {
        l.unlock();
    }
}

17 Source : AuthenticatorBase.java
with Apache License 2.0
from how2j

/**
 * Attempts reauthentication to the <code>Realm</code> using the credentials
 * included in argument <code>entry</code>.
 *
 * @param ssoId
 *            identifier of SingleSignOn session with which the caller is
 *            replacedociated
 * @param request
 *            the request that needs to be authenticated
 */
protected boolean reauthenticateFromSSO(String ssoId, Request request) {
    if (sso == null || ssoId == null)
        return false;
    boolean reauthenticated = false;
    Container parent = getContainer();
    if (parent != null) {
        Realm realm = parent.getRealm();
        if (realm != null) {
            reauthenticated = sso.reauthenticate(ssoId, realm, request);
        }
    }
    if (reauthenticated) {
        replacedociate(ssoId, request.getSessionInternal(true));
        if (log.isDebugEnabled()) {
            log.debug(" Reauthenticated cached principal '" + request.getUserPrincipal().getName() + "' with auth type '" + request.getAuthType() + "'");
        }
    }
    return reauthenticated;
}

17 Source : RealmSF.java
with GNU General Public License v3.0
from guang19

/**
 * Store the specified Realm properties and child (Realm)
 *
 * @param aWriter
 *            PrintWriter to which we are storing
 * @param indent
 *            Number of spaces to indent this element
 * @param aRealm
 *            Realm whose properties are being stored
 *
 * @exception Exception
 *                if an exception occurs while storing
 */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aRealm, StoreDescription parentDesc) throws Exception {
    if (aRealm instanceof CombinedRealm) {
        CombinedRealm combinedRealm = (CombinedRealm) aRealm;
        // Store nested <Realm> element
        Realm[] realms = combinedRealm.getNestedRealms();
        storeElementArray(aWriter, indent, realms);
    }
    // Store nested <CredentialHandler> element
    CredentialHandler credentialHandler = ((Realm) aRealm).getCredentialHandler();
    if (credentialHandler != null) {
        storeElement(aWriter, indent, credentialHandler);
    }
}

17 Source : CombinedRealm.java
with GNU General Public License v3.0
from guang19

/**
 * Add a realm to the list of realms that will be used to authenticate
 * users.
 * @param theRealm realm which should be wrapped by the combined realm
 */
public void addRealm(Realm theRealm) {
    realms.add(theRealm);
    if (log.isDebugEnabled()) {
        sm.getString("combinedRealm.addRealm", theRealm.getClreplaced().getName(), Integer.toString(realms.size()));
    }
}

17 Source : MBeanFactory.java
with GNU General Public License v3.0
from guang19

private String addRealmToParent(String parent, Realm realm) throws Exception {
    ObjectName pname = new ObjectName(parent);
    Container container = getParentContainerFromParent(pname);
    // Add the new instance to its parent component
    container.setRealm(realm);
    // Return the corresponding MBean name
    ObjectName oname = null;
    if (realm instanceof JmxEnabled) {
        oname = ((JmxEnabled) realm).getObjectName();
    }
    if (oname != null) {
        return oname.toString();
    } else {
        return null;
    }
}

17 Source : ContainerBase.java
with GNU General Public License v3.0
from guang19

/**
 * Set the Realm with which this Container is replacedociated.
 *
 * @param realm The newly replacedociated Realm
 */
@Override
public void setRealm(Realm realm) {
    Lock l = realmLock.writeLock();
    l.lock();
    try {
        // Change components if necessary
        Realm oldRealm = this.realm;
        if (oldRealm == realm)
            return;
        this.realm = realm;
        // Stop the old component if necessary
        if (getState().isAvailable() && (oldRealm != null) && (oldRealm instanceof Lifecycle)) {
            try {
                ((Lifecycle) oldRealm).stop();
            } catch (LifecycleException e) {
                log.error(sm.getString("containerBase.realm.stop"), e);
            }
        }
        // Start the new component if necessary
        if (realm != null)
            realm.setContainer(this);
        if (getState().isAvailable() && (realm != null) && (realm instanceof Lifecycle)) {
            try {
                ((Lifecycle) realm).start();
            } catch (LifecycleException e) {
                log.error(sm.getString("containerBase.realm.start"), e);
            }
        }
        // Report this property change to interested listeners
        support.firePropertyChange("realm", oldRealm, this.realm);
    } finally {
        l.unlock();
    }
}

17 Source : ContainerBase.java
with MIT License
from chenmudu

/**
 * Set the Realm with which this Container is replacedociated.
 *
 * @param realm The newly replacedociated Realm
 */
@Override
public void setRealm(Realm realm) {
    Lock l = realmLock.writeLock();
    l.lock();
    try {
        // Change components if necessary
        Realm oldRealm = this.realm;
        if (oldRealm == realm)
            return;
        this.realm = realm;
        // Stop the old component if necessary
        if (getState().isAvailable() && (oldRealm != null) && (oldRealm instanceof Lifecycle)) {
            try {
                ((Lifecycle) oldRealm).stop();
            } catch (LifecycleException e) {
                log.error("ContainerBase.setRealm: stop: ", e);
            }
        }
        // Start the new component if necessary
        if (realm != null)
            realm.setContainer(this);
        if (getState().isAvailable() && (realm != null) && (realm instanceof Lifecycle)) {
            try {
                ((Lifecycle) realm).start();
            } catch (LifecycleException e) {
                log.error("ContainerBase.setRealm: start: ", e);
            }
        }
        // Report this property change to interested listeners
        support.firePropertyChange("realm", oldRealm, this.realm);
    } finally {
        l.unlock();
    }
}

17 Source : AuthenticatorBase.java
with MIT License
from chenmudu

/**
 * Attempts reauthentication to the <code>Realm</code> using the credentials
 * included in argument <code>entry</code>.
 *
 * @param ssoId
 *            identifier of SingleSignOn session with which the caller is
 *            replacedociated
 * @param request
 *            the request that needs to be authenticated
 * @return <code>true</code> if the reauthentication from SSL occurred
 */
protected boolean reauthenticateFromSSO(String ssoId, Request request) {
    if (sso == null || ssoId == null) {
        return false;
    }
    boolean reauthenticated = false;
    Container parent = getContainer();
    if (parent != null) {
        Realm realm = parent.getRealm();
        if (realm != null) {
            reauthenticated = sso.reauthenticate(ssoId, realm, request);
        }
    }
    if (reauthenticated) {
        replacedociate(ssoId, request.getSessionInternal(true));
        if (log.isDebugEnabled()) {
            log.debug(" Reauthenticated cached principal '" + request.getUserPrincipal().getName() + "' with auth type '" + request.getAuthType() + "'");
        }
    }
    return reauthenticated;
}

16 Source : CombinedRealm.java
with Apache License 2.0
from wangyingjie

/**
 * Return the Principal replacedociated with the specified chain of X509
 * client certificates.  If there is none, return <code>null</code>.
 *
 * @param certs Array of client certificates, with the first one in
 *  the array being the certificate of the client itself.
 */
@Override
public Principal authenticate(X509Certificate[] certs) {
    Principal authenticatedUser = null;
    String username = null;
    if (certs != null && certs.length > 0) {
        username = certs[0].getSubjectDN().getName();
    }
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
        }
        authenticatedUser = realm.authenticate(certs);
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getInfo()));
            }
            break;
        }
    }
    return authenticatedUser;
}

16 Source : ContainerBase.java
with Apache License 2.0
from tryandcatch

/**
 * Start this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void startInternal() throws LifecycleException {
    // Start our subordinate components, if any
    if ((loader != null) && (loader instanceof Lifecycle))
        ((Lifecycle) loader).start();
    logger = null;
    getLogger();
    if ((manager != null) && (manager instanceof Lifecycle))
        ((Lifecycle) manager).start();
    if ((cluster != null) && (cluster instanceof Lifecycle))
        ((Lifecycle) cluster).start();
    Realm realm = getRealmInternal();
    if ((realm != null) && (realm instanceof Lifecycle))
        ((Lifecycle) realm).start();
    if ((resources != null) && (resources instanceof Lifecycle))
        ((Lifecycle) resources).start();
    // Start our child containers, if any
    Container[] children = findChildren();
    List<Future<Void>> results = new ArrayList<Future<Void>>();
    for (int i = 0; i < children.length; i++) {
        results.add(startStopExecutor.submit(new StartChild(children[i])));
    }
    boolean fail = false;
    for (Future<Void> result : results) {
        try {
            result.get();
        } catch (Exception e) {
            log.error(sm.getString("containerBase.threadedStartFailed"), e);
            fail = true;
        }
    }
    if (fail) {
        throw new LifecycleException(sm.getString("containerBase.threadedStartFailed"));
    }
    // Start the Valves in our pipeline (including the basic), if any
    if (pipeline instanceof Lifecycle)
        ((Lifecycle) pipeline).start();
    setState(LifecycleState.STARTING);
    // Start our thread
    threadStart();
}

16 Source : 1031.java
with MIT License
from masud-technope

/**
 * Minimal tomcat starter for embedding/unit tests.
 *
 * Tomcat supports multiple styles of configuration and
 * startup - the most common and stable is server.xml-based,
 * implemented in org.apache.catalina.startup.Bootstrap.
 *
 * This clreplaced is for use in apps that embed tomcat.
 * Requirements:
 *
 * - all tomcat clreplacedes and possibly servlets are in the clreplacedpath.
 * ( for example all is in one big jar, or in eclipse CP, or in any other
 * combination )
 *
 * - we need one temporary directory for work files
 *
 * - no config file is required. This clreplaced provides methods to
 * use if you have a webapp with a web.xml file, but it is
 * optional - you can use your own servlets.
 *
 * There are a variety of 'add' methods to configure servlets and webapps. These
 * methods, by default, create a simple in-memory security realm and apply it.
 * If you need more complex security processing, you can define a subclreplaced of
 * this clreplaced.
 *
 * This clreplaced provides a set of convenience methods for configuring webapp
 * contexts, all overloads of the method <pre>addWebapp</pre>. These methods
 * create a webapp context, configure it, and then add it to a {@link Host}.
 * They do not use a global default web.xml; rather, they add a lifecycle
 * listener that adds the standard DefaultServlet, JSP processing, and welcome
 * files.
 *
 * In complex cases, you may prefer to use the ordinary Tomcat API to create
 * webapp contexts; for example, you might need to install a custom Loader
 * before the call to {@link Host#addChild(Container)}. To replicate the basic
 * behavior of the <pre>addWebapp</pre> methods, you may want to call two
 * methods of this clreplaced: {@link #noDefaultWebXmlPath()} and
 * {@link #getDefaultWebXmlListener()}.
 *
 * {@link #getDefaultRealm()} returns the simple security realm.
 *
 * {@link #getDefaultWebXmlListener()} returns a {@link LifecycleListener} that
 * adds the standard DefaultServlet, JSP processing, and welcome files. If you
 * add this listener, you must prevent Tomcat from applying any standard global
 * web.xml with ...
 *
 * {@link #noDefaultWebXmlPath()} returns a dummy pathname to configure to
 * prevent {@link ContextConfig} from trying to apply a global web.xml file.
 *
 * This clreplaced provides a main() and few simple CLI arguments,
 * see setters for doc. It can be used for simple tests and
 * demo.
 *
 * @see <a href="http://svn.apache.org/repos/asf/tomcat/trunk/test/org/apache/catalina/startup/TestTomcat.java">TestTomcat</a>
 * @author Costin Manolache
 */
public clreplaced Tomcat {

    // Some logging implementations use weak references for loggers so there is
    // the possibility that logging configuration could be lost if GC runs just
    // after Loggers are configured but before they are used. The purpose of
    // this Map is to retain strong references to explicitly configured loggers
    // so that configuration is not lost.
    private final Map<String, Logger> pinnedLoggers = new HashMap<String, Logger>();

    // Single engine, service, server, connector - few cases need more,
    // they can use server.xml
    protected Server server;

    protected Service service;

    protected Engine engine;

    // for more - customize the clreplacedes
    protected Connector connector;

    // To make it a bit easier to config for the common case
    // ( one host, one context ).
    protected Host host;

    // TODO: it's easy to add support for more hosts - but is it
    // really needed ?
    // TODO: allow use of in-memory connector
    protected int port = 8080;

    protected String hostname = "localhost";

    protected String basedir;

    // Default in-memory realm, will be set by default on the Engine. Can be
    // replaced at engine level or over-ridden at Host or Context level
    // Will be removed in Tomcat 8.0.x.
    @Deprecated
    protected Realm defaultRealm;

    private final Map<String, String> userPreplaced = new HashMap<String, String>();

    private final Map<String, List<String>> userRoles = new HashMap<String, List<String>>();

    private final Map<String, Principal> userPrincipals = new HashMap<String, Principal>();

    public Tomcat() {
    // NOOP
    }

    /**
     * Tomcat needs a directory for temp files. This should be the
     * first method called.
     *
     * By default, if this method is not called, we use:
     *  - system properties - catalina.base, catalina.home
     *  - $HOME/tomcat.$PORT
     * ( /tmp doesn't seem a good choice for security ).
     *
     * TODO: better default ? Maybe current dir ?
     * TODO: disable work dir if not needed ( no jsp, etc ).
     */
    public void setBaseDir(String basedir) {
        this.basedir = basedir;
    }

    /**
     * Set the port for the default connector. Must
     * be called before start().
     */
    public void setPort(int port) {
        this.port = port;
    }

    /**
     * The the hostname of the default host, default is
     * 'localhost'.
     */
    public void setHostname(String s) {
        hostname = s;
    }

    /**
     * This is equivalent to adding a web application to Tomcat's webapps
     * directory. The equivalent of the default web.xml will be applied  to the
     * web application and any WEB-INF/web.xml and META-INF/context.xml packaged
     * with the application will be processed normally. Normal web fragment and
     * {@link javax.servlet.ServletContainerInitializer} processing will be
     * applied.
     *
     * @throws ServletException
     */
    public Context addWebapp(String contextPath, String docBase) throws ServletException {
        return addWebapp(getHost(), contextPath, docBase);
    }

    /**
     * Add a context - programmatic mode, no web.xml used.
     *
     * API calls equivalent with web.xml:
     *
     * context-param
     *  ctx.addParameter("name", "value");
     *
     * error-page
     *    ErrorPage ep = new ErrorPage();
     *    ep.setErrorCode(500);
     *    ep.setLocation("/error.html");
     *    ctx.addErrorPage(ep);
     *
     * ctx.addMimeMapping("ext", "type");
     *
     * Note: If you reload the Context, all your configuration will be lost. If
     * you need reload support, consider using a LifecycleListener to provide
     * your configuration.
     *
     * TODO: add the rest
     *
     *  @param contextPath "" for root context.
     *  @param docBase base dir for the context, for static files. Must exist,
     *  relative to the server home
     */
    public Context addContext(String contextPath, String docBase) {
        return addContext(getHost(), contextPath, docBase);
    }

    /**
     * Equivalent with
     *  <servlet><servlet-name><servlet-clreplaced>.
     *
     * In general it is better/faster to use the method that takes a
     * Servlet as param - this one can be used if the servlet is not
     * commonly used, and want to avoid loading all deps.
     * ( for example: jsp servlet )
     *
     * You can customize the returned servlet, ex:
     *
     *    wrapper.addInitParameter("name", "value");
     *
     * @param contextPath   Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servletClreplaced  The clreplaced to be used for the Servlet
     * @return The wrapper for the servlet
     */
    public Wrapper addServlet(String contextPath, String servletName, String servletClreplaced) {
        Container ctx = getHost().findChild(contextPath);
        return addServlet((Context) ctx, servletName, servletClreplaced);
    }

    /**
     * Static version of {@link #addServlet(String, String, String)}
     * @param ctx           Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servletClreplaced  The clreplaced to be used for the Servlet
     * @return The wrapper for the servlet
     */
    public static Wrapper addServlet(Context ctx, String servletName, String servletClreplaced) {
        // will do clreplaced for name and set init params
        Wrapper sw = ctx.createWrapper();
        sw.setServletClreplaced(servletClreplaced);
        sw.setName(servletName);
        ctx.addChild(sw);
        return sw;
    }

    /**
     * Add an existing Servlet to the context with no clreplaced.forName or
     * initialisation.
     * @param contextPath   Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servlet       The Servlet to add
     * @return The wrapper for the servlet
     */
    public Wrapper addServlet(String contextPath, String servletName, Servlet servlet) {
        Container ctx = getHost().findChild(contextPath);
        return addServlet((Context) ctx, servletName, servlet);
    }

    /**
     * Static version of {@link #addServlet(String, String, Servlet)}.
     * @param ctx           Context to add Servlet to
     * @param servletName   Servlet name (used in mappings)
     * @param servlet       The Servlet to add
     * @return The wrapper for the servlet
     */
    public static Wrapper addServlet(Context ctx, String servletName, Servlet servlet) {
        // will do clreplaced for name and set init params
        Wrapper sw = new ExistingStandardWrapper(servlet);
        sw.setName(servletName);
        ctx.addChild(sw);
        return sw;
    }

    /**
     * Initialise the server.
     *
     * @throws LifecycleException
     */
    public void init() throws LifecycleException {
        getServer();
        getConnector();
        server.init();
    }

    /**
     * Start the server.
     *
     * @throws LifecycleException
     */
    public void start() throws LifecycleException {
        getServer();
        getConnector();
        server.start();
    }

    /**
     * Stop the server.
     *
     * @throws LifecycleException
     */
    public void stop() throws LifecycleException {
        getServer();
        server.stop();
    }

    /**
     * Destroy the server. This object cannot be used once this method has been
     * called.
     */
    public void destroy() throws LifecycleException {
        getServer();
        server.destroy();
    // Could null out objects here
    }

    /**
     * Add a user for the in-memory realm. All created apps use this
     * by default, can be replaced using setRealm().
     */
    public void addUser(String user, String preplaced) {
        userPreplaced.put(user, preplaced);
    }

    /**
     * @see #addUser(String, String)
     */
    public void addRole(String user, String role) {
        List<String> roles = userRoles.get(user);
        if (roles == null) {
            roles = new ArrayList<String>();
            userRoles.put(user, roles);
        }
        roles.add(role);
    }

    // ------- Extra customization -------
    // You can tune individual tomcat objects, using internal APIs
    /**
     * Get the default http connector. You can set more
     * parameters - the port is already initialized.
     *
     * Alternatively, you can construct a Connector and set any params,
     * then call addConnector(Connector)
     *
     * @return A connector object that can be customized
     */
    public Connector getConnector() {
        getServer();
        if (connector != null) {
            return connector;
        }
        // The same as in standard Tomcat configuration.
        // This creates an APR HTTP connector if AprLifecycleListener has been
        // configured (created) and Tomcat Native library is available.
        // Otherwise it creates a BIO HTTP connector (Http11Protocol).
        connector = new Connector("HTTP/1.1");
        connector.setPort(port);
        service.addConnector(connector);
        return connector;
    }

    public void setConnector(Connector connector) {
        this.connector = connector;
    }

    /**
     * Get the service object. Can be used to add more
     * connectors and few other global settings.
     */
    public Service getService() {
        getServer();
        return service;
    }

    /**
     * Sets the current host - all future webapps will
     * be added to this host. When tomcat starts, the
     * host will be the default host.
     *
     * @param host
     */
    public void setHost(Host host) {
        this.host = host;
    }

    public Host getHost() {
        if (host == null) {
            host = new StandardHost();
            host.setName(hostname);
            getEngine().addChild(host);
        }
        return host;
    }

    /**
     * Set a custom realm for auth. If not called, a simple
     * default will be used, using an internal map.
     *
     * Must be called before adding a context.
     *
     * @deprecated Will be removed in Tomcat 8.0.x.
     */
    @Deprecated
    public void setDefaultRealm(Realm realm) {
        defaultRealm = realm;
    }

    /**
     * Access to the engine, for further customization.
     */
    public Engine getEngine() {
        if (engine == null) {
            getServer();
            engine = new StandardEngine();
            engine.setName("Tomcat");
            engine.setDefaultHost(hostname);
            if (defaultRealm == null) {
                initSimpleAuth();
            }
            engine.setRealm(defaultRealm);
            service.setContainer(engine);
        }
        return engine;
    }

    /**
     * Get the server object. You can add listeners and few more
     * customizations. JNDI is disabled by default.
     */
    public Server getServer() {
        if (server != null) {
            return server;
        }
        initBaseDir();
        System.setProperty("catalina.useNaming", "false");
        server = new StandardServer();
        server.setPort(-1);
        service = new StandardService();
        service.setName("Tomcat");
        server.addService(service);
        return server;
    }

    public Context addContext(Host host, String contextPath, String dir) {
        return addContext(host, contextPath, contextPath, dir);
    }

    public Context addContext(Host host, String contextPath, String contextName, String dir) {
        silence(host, contextName);
        Context ctx = createContext(host, contextPath);
        ctx.setName(contextName);
        ctx.setPath(contextPath);
        ctx.setDocBase(dir);
        ctx.addLifecycleListener(new FixContextListener());
        if (host == null) {
            getHost().addChild(ctx);
        } else {
            host.addChild(ctx);
        }
        return ctx;
    }

    public Context addWebapp(Host host, String contextPath, String docBase) {
        return addWebapp(host, contextPath, contextPath, docBase);
    }

    /**
     * @see #addWebapp(String, String)
     *
     * @param name Ignored. The contextPath will be used
     *
     * @deprecated Use {@link #addWebapp(Host, String, String)}
     */
    @Deprecated
    public Context addWebapp(Host host, String contextPath, String name, String docBase) {
        silence(host, contextPath);
        Context ctx = createContext(host, contextPath);
        ctx.setPath(contextPath);
        ctx.setDocBase(docBase);
        ctx.addLifecycleListener(new DefaultWebXmlListener());
        ctx.setConfigFile(getWebappConfigFile(docBase, contextPath));
        ContextConfig ctxCfg = new ContextConfig();
        ctx.addLifecycleListener(ctxCfg);
        // prevent it from looking ( if it finds one - it'll have dup error )
        ctxCfg.setDefaultWebXml(noDefaultWebXmlPath());
        if (host == null) {
            getHost().addChild(ctx);
        } else {
            host.addChild(ctx);
        }
        return ctx;
    }

    /**
     * Return a listener that provides the required configuration items for JSP
     * processing. From the standard Tomcat global web.xml. Preplaced this to
     * {@link Context#addLifecycleListener(LifecycleListener)} and then preplaced the
     * result of {@link #noDefaultWebXmlPath()} to
     * {@link ContextConfig#setDefaultWebXml(String)}.
     * @return a listener object that configures default JSP processing.
     */
    public LifecycleListener getDefaultWebXmlListener() {
        return new DefaultWebXmlListener();
    }

    /**
     * @return a pathname to preplaced to
     * {@link ContextConfig#setDefaultWebXml(String)} when using
     * {@link #getDefaultWebXmlListener()}.
     */
    public String noDefaultWebXmlPath() {
        return Constants.NoDefaultWebXml;
    }

    /**
     * For complex configurations, this accessor allows callers of this clreplaced
     * to obtain the simple realm created by default.
     * @return the simple in-memory realm created by default.
     * @deprecated Will be removed in Tomcat 8.0.x
     */
    @Deprecated
    public Realm getDefaultRealm() {
        if (defaultRealm == null) {
            initSimpleAuth();
        }
        return defaultRealm;
    }

    // ---------- Helper methods and clreplacedes -------------------
    /**
     * Create an in-memory realm. You can replace it for contexts with a real
     * one. The Realm created here will be added to the Engine by default and
     * may be replaced at the Engine level or over-ridden (as per normal Tomcat
     * behaviour) at the Host or Context level.
     * @deprecated Will be removed in Tomcat 8.0.x
     */
    @Deprecated
    protected void initSimpleAuth() {
        defaultRealm = new RealmBase() {

            @Override
            protected String getName() {
                return "Simple";
            }

            @Override
            protected String getPreplacedword(String username) {
                return userPreplaced.get(username);
            }

            @Override
            protected Principal getPrincipal(String username) {
                Principal p = userPrincipals.get(username);
                if (p == null) {
                    String preplaced = userPreplaced.get(username);
                    if (preplaced != null) {
                        p = new GenericPrincipal(username, preplaced, userRoles.get(username));
                        userPrincipals.put(username, p);
                    }
                }
                return p;
            }
        };
    }

    protected void initBaseDir() {
        String catalinaHome = System.getProperty(Globals.CATALINA_HOME_PROP);
        if (basedir == null) {
            basedir = System.getProperty(Globals.CATALINA_BASE_PROP);
        }
        if (basedir == null) {
            basedir = catalinaHome;
        }
        if (basedir == null) {
            // Create a temp dir.
            basedir = System.getProperty("user.dir") + "/tomcat." + port;
            File home = new File(basedir);
            home.mkdir();
            if (!home.isAbsolute()) {
                try {
                    basedir = home.getCanonicalPath();
                } catch (IOException e) {
                    basedir = home.getAbsolutePath();
                }
            }
        }
        if (catalinaHome == null) {
            System.setProperty(Globals.CATALINA_HOME_PROP, basedir);
        }
        System.setProperty(Globals.CATALINA_BASE_PROP, basedir);
    }

    static final String[] silences = new String[] { "org.apache.coyote.http11.Http11Protocol", "org.apache.catalina.core.StandardService", "org.apache.catalina.core.StandardEngine", "org.apache.catalina.startup.ContextConfig", "org.apache.catalina.core.ApplicationContext", "org.apache.catalina.core.AprLifecycleListener" };

    private boolean silent = false;

    /**
     * Controls if the loggers will be silenced or not.
     * @param silent    <code>true</code> sets the log level to WARN for the
     *                  loggers that log information on Tomcat start up. This
     *                  prevents the usual startup information being logged.
     *                  <code>false</code> sets the log level to the default
     *                  level of INFO.
     */
    public void setSilent(boolean silent) {
        this.silent = silent;
        for (String s : silences) {
            Logger logger = Logger.getLogger(s);
            pinnedLoggers.put(s, logger);
            if (silent) {
                logger.setLevel(Level.WARNING);
            } else {
                logger.setLevel(Level.INFO);
            }
        }
    }

    private void silence(Host host, String contextPath) {
        String loggerName = getLoggerName(host, contextPath);
        Logger logger = Logger.getLogger(loggerName);
        pinnedLoggers.put(loggerName, logger);
        if (silent) {
            logger.setLevel(Level.WARNING);
        } else {
            logger.setLevel(Level.INFO);
        }
    }

    /*
     * Uses essentially the same logic as {@link ContainerBase#logName()}.
     */
    private String getLoggerName(Host host, String contextName) {
        if (host == null) {
            host = getHost();
        }
        StringBuilder loggerName = new StringBuilder();
        loggerName.append(ContainerBase.clreplaced.getName());
        loggerName.append(".[");
        // Engine name
        loggerName.append(host.getParent().getName());
        loggerName.append("].[");
        // Host name
        loggerName.append(host.getName());
        loggerName.append("].[");
        // Context name
        if (contextName == null || contextName.equals("")) {
            loggerName.append("/");
        } else if (contextName.startsWith("##")) {
            loggerName.append("/");
            loggerName.append(contextName);
        }
        loggerName.append(']');
        return loggerName.toString();
    }

    /**
     * Create the configured {@link Context} for the given <code>host</code>.
     * The default constructor of the clreplaced that was configured with
     * {@link StandardHost#setContextClreplaced(String)} will be used
     *
     * @param host
     *            host for which the {@link Context} should be created, or
     *            <code>null</code> if default host should be used
     * @param url
     *            path of the webapp which should get the {@link Context}
     * @return newly created {@link Context}
     */
    private Context createContext(Host host, String url) {
        String contextClreplaced = StandardContext.clreplaced.getName();
        if (host == null) {
            host = this.getHost();
        }
        if (host instanceof StandardHost) {
            contextClreplaced = ((StandardHost) host).getContextClreplaced();
        }
        try {
            return (Context) Clreplaced.forName(contextClreplaced).getConstructor().newInstance();
        } catch (InstantiationException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (InvocationTargetException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (SecurityException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        } catch (ClreplacedNotFoundException e) {
            throw new IllegalArgumentException("Can't instantiate context-clreplaced " + contextClreplaced + " for host " + host + " and url " + url, e);
        }
    }

    /**
     * Enables JNDI naming which is disabled by default. Server must implement
     * {@link Lifecycle} in order for the {@link NamingContextListener} to be
     * used.
     */
    public void enableNaming() {
        // Make sure getServer() has been called as that is where naming is
        // disabled
        getServer();
        server.addLifecycleListener(new NamingContextListener());
        System.setProperty("catalina.useNaming", "true");
        String value = "org.apache.naming";
        String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES);
        if (oldValue != null) {
            if (oldValue.contains(value)) {
                value = oldValue;
            } else {
                value = value + ":" + oldValue;
            }
        }
        System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value);
        value = System.getProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY);
        if (value == null) {
            System.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        }
    }

    /**
     * Provide default configuration for a context. This is the programmatic
     * equivalent of the default web.xml.
     *
     *  TODO: in normal Tomcat, if default-web.xml is not found, use this
     *  method
     *
     * @param contextPath   The context to set the defaults for
     */
    public void initWebappDefaults(String contextPath) {
        Container ctx = getHost().findChild(contextPath);
        initWebappDefaults((Context) ctx);
    }

    /**
     * Static version of {@link #initWebappDefaults(String)}
     * @param ctx   The context to set the defaults for
     */
    public static void initWebappDefaults(Context ctx) {
        // Default servlet
        Wrapper servlet = addServlet(ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
        servlet.setLoadOnStartup(1);
        servlet.setOverridable(true);
        // JSP servlet (by clreplaced name - to avoid loading all deps)
        servlet = addServlet(ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
        servlet.addInitParameter("fork", "false");
        servlet.setLoadOnStartup(3);
        servlet.setOverridable(true);
        // Servlet mappings
        ctx.addServletMapping("/", "default");
        ctx.addServletMapping("*.jsp", "jsp");
        ctx.addServletMapping("*.jspx", "jsp");
        // Sessions
        ctx.setSessionTimeout(30);
        // MIME mappings
        for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length; ) {
            ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++], DEFAULT_MIME_MAPPINGS[i++]);
        }
        // Welcome files
        ctx.addWelcomeFile("index.html");
        ctx.addWelcomeFile("index.htm");
        ctx.addWelcomeFile("index.jsp");
    }

    /**
     * Fix startup sequence - required if you don't use web.xml.
     *
     * The start() method in context will set 'configured' to false - and
     * expects a listener to set it back to true.
     */
    public static clreplaced FixContextListener implements LifecycleListener {

        @Override
        public void lifecycleEvent(LifecycleEvent event) {
            try {
                Context context = (Context) event.getLifecycle();
                if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
                    context.setConfigured(true);
                }
                // annotations
                if (context.getLoginConfig() == null) {
                    context.setLoginConfig(new LoginConfig("NONE", null, null, null));
                    context.getPipeline().addValve(new NonLoginAuthenticator());
                }
            } catch (ClreplacedCastException e) {
                return;
            }
        }
    }

    /**
     * Fix reload - required if reloading and using programmatic configuration.
     * When a context is reloaded, any programmatic configuration is lost. This
     * listener sets the equivalent of conf/web.xml when the context starts.
     */
    public static clreplaced DefaultWebXmlListener implements LifecycleListener {

        @Override
        public void lifecycleEvent(LifecycleEvent event) {
            if (Lifecycle.BEFORE_START_EVENT.equals(event.getType())) {
                initWebappDefaults((Context) event.getLifecycle());
            }
        }
    }

    /**
     * Helper clreplaced for wrapping existing servlets. This disables servlet
     * lifecycle and normal reloading, but also reduces overhead and provide
     * more direct control over the servlet.
     */
    public static clreplaced ExistingStandardWrapper extends StandardWrapper {

        private final Servlet existing;

        @SuppressWarnings("deprecation")
        public ExistingStandardWrapper(Servlet existing) {
            this.existing = existing;
            if (existing instanceof javax.servlet.SingleThreadModel) {
                singleThreadModel = true;
                instancePool = new Stack<Servlet>();
            }
        }

        @Override
        public synchronized Servlet loadServlet() throws ServletException {
            if (singleThreadModel) {
                Servlet instance;
                try {
                    instance = existing.getClreplaced().newInstance();
                } catch (InstantiationException e) {
                    throw new ServletException(e);
                } catch (IllegalAccessException e) {
                    throw new ServletException(e);
                }
                instance.init(facade);
                return instance;
            } else {
                if (!instanceInitialized) {
                    existing.init(facade);
                    instanceInitialized = true;
                }
                return existing;
            }
        }

        @Override
        public long getAvailable() {
            return 0;
        }

        @Override
        public boolean isUnavailable() {
            return false;
        }

        @Override
        public Servlet getServlet() {
            return existing;
        }

        @Override
        public String getServletClreplaced() {
            return existing.getClreplaced().getName();
        }
    }

    /**
     * TODO: would a properties resource be better ? Or just parsing
     * /etc/mime.types ?
     * This is needed because we don't use the default web.xml, where this
     * is encoded.
     */
    private static final String[] DEFAULT_MIME_MAPPINGS = { "abs", "audio/x-mpeg", "ai", "application/postscript", "aif", "audio/x-aiff", "aifc", "audio/x-aiff", "aiff", "audio/x-aiff", "aim", "application/x-aim", "art", "image/x-jg", "asf", "video/x-ms-asf", "asx", "video/x-ms-asf", "au", "audio/basic", "avi", "video/x-msvideo", "avx", "video/x-rad-screenplay", "bcpio", "application/x-bcpio", "bin", "application/octet-stream", "bmp", "image/bmp", "body", "text/html", "cdf", "application/x-cdf", "cer", "application/pkix-cert", "clreplaced", "application/java", "cpio", "application/x-cpio", "csh", "application/x-csh", "css", "text/css", "dib", "image/bmp", "doc", "application/msword", "dtd", "application/xml-dtd", "dv", "video/x-dv", "dvi", "application/x-dvi", "eps", "application/postscript", "etx", "text/x-setext", "exe", "application/octet-stream", "gif", "image/gif", "gtar", "application/x-gtar", "gz", "application/x-gzip", "hdf", "application/x-hdf", "hqx", "application/mac-binhex40", "htc", "text/x-component", "htm", "text/html", "html", "text/html", "ief", "image/ief", "jad", "text/vnd.sun.j2me.app-descriptor", "jar", "application/java-archive", "java", "text/x-java-source", "jnlp", "application/x-java-jnlp-file", "jpe", "image/jpeg", "jpeg", "image/jpeg", "jpg", "image/jpeg", "js", "application/javascript", "jsf", "text/plain", "jspf", "text/plain", "kar", "audio/midi", "latex", "application/x-latex", "m3u", "audio/x-mpegurl", "mac", "image/x-macpaint", "man", "text/troff", "mathml", "application/mathml+xml", "me", "text/troff", "mid", "audio/midi", "midi", "audio/midi", "mif", "application/x-mif", "mov", "video/quicktime", "movie", "video/x-sgi-movie", "mp1", "audio/mpeg", "mp2", "audio/mpeg", "mp3", "audio/mpeg", "mp4", "video/mp4", "mpa", "audio/mpeg", "mpe", "video/mpeg", "mpeg", "video/mpeg", "mpega", "audio/x-mpeg", "mpg", "video/mpeg", "mpv2", "video/mpeg2", "nc", "application/x-netcdf", "oda", "application/oda", "odb", "application/vnd.oasis.opendoreplacedent.database", "odc", "application/vnd.oasis.opendoreplacedent.chart", "odf", "application/vnd.oasis.opendoreplacedent.formula", "odg", "application/vnd.oasis.opendoreplacedent.graphics", "odi", "application/vnd.oasis.opendoreplacedent.image", "odm", "application/vnd.oasis.opendoreplacedent.text-master", "odp", "application/vnd.oasis.opendoreplacedent.presentation", "ods", "application/vnd.oasis.opendoreplacedent.spreadsheet", "odt", "application/vnd.oasis.opendoreplacedent.text", "otg", "application/vnd.oasis.opendoreplacedent.graphics-template", "oth", "application/vnd.oasis.opendoreplacedent.text-web", "otp", "application/vnd.oasis.opendoreplacedent.presentation-template", "ots", "application/vnd.oasis.opendoreplacedent.spreadsheet-template ", "ott", "application/vnd.oasis.opendoreplacedent.text-template", "ogx", "application/ogg", "ogv", "video/ogg", "oga", "audio/ogg", "ogg", "audio/ogg", "spx", "audio/ogg", "flac", "audio/flac", "anx", "application/annodex", "axa", "audio/annodex", "axv", "video/annodex", "xspf", "application/xspf+xml", "pbm", "image/x-portable-bitmap", "pct", "image/pict", "pdf", "application/pdf", "pgm", "image/x-portable-graymap", "pic", "image/pict", "pict", "image/pict", "pls", "audio/x-scpls", "png", "image/png", "pnm", "image/x-portable-anymap", "pnt", "image/x-macpaint", "ppm", "image/x-portable-pixmap", "ppt", "application/vnd.ms-powerpoint", "pps", "application/vnd.ms-powerpoint", "ps", "application/postscript", "psd", "image/vnd.adobe.photoshop", "qt", "video/quicktime", "qti", "image/x-quicktime", "qtif", "image/x-quicktime", "ras", "image/x-cmu-raster", "rdf", "application/rdf+xml", "rgb", "image/x-rgb", "rm", "application/vnd.rn-realmedia", "roff", "text/troff", "rtf", "application/rtf", "rtx", "text/richtext", "sh", "application/x-sh", "shar", "application/x-shar", /*"shtml", "text/x-server-parsed-html",*/
    "sit", "application/x-stuffit", "snd", "audio/basic", "src", "application/x-wais-source", "sv4cpio", "application/x-sv4cpio", "sv4crc", "application/x-sv4crc", "svg", "image/svg+xml", "svgz", "image/svg+xml", "swf", "application/x-shockwave-flash", "t", "text/troff", "tar", "application/x-tar", "tcl", "application/x-tcl", "tex", "application/x-tex", "texi", "application/x-texinfo", "texinfo", "application/x-texinfo", "tif", "image/tiff", "tiff", "image/tiff", "tr", "text/troff", "tsv", "text/tab-separated-values", "txt", "text/plain", "ulw", "audio/basic", "ustar", "application/x-ustar", "vxml", "application/voicexml+xml", "xbm", "image/x-xbitmap", "xht", "application/xhtml+xml", "xhtml", "application/xhtml+xml", "xls", "application/vnd.ms-excel", "xml", "application/xml", "xpm", "image/x-xpixmap", "xsl", "application/xml", "xslt", "application/xslt+xml", "xul", "application/vnd.mozilla.xul+xml", "xwd", "image/x-xwindowdump", "vsd", "application/vnd.visio", "wav", "audio/x-wav", "wbmp", "image/vnd.wap.wbmp", "wml", "text/vnd.wap.wml", "wmlc", "application/vnd.wap.wmlc", "wmls", "text/vnd.wap.wmlsc", "wmlscriptc", "application/vnd.wap.wmlscriptc", "wmv", "video/x-ms-wmv", "wrl", "model/vrml", "wspolicy", "application/wspolicy+xml", "Z", "application/x-compress", "z", "application/x-compress", "zip", "application/zip" };

    protected URL getWebappConfigFile(String path, String contextName) {
        File docBase = new File(path);
        if (docBase.isDirectory()) {
            return getWebappConfigFileFromDirectory(docBase, contextName);
        } else {
            return getWebappConfigFileFromJar(docBase, contextName);
        }
    }

    private URL getWebappConfigFileFromDirectory(File docBase, String contextName) {
        URL result = null;
        File webAppContextXml = new File(docBase, Constants.ApplicationContextXml);
        if (webAppContextXml.exists()) {
            try {
                result = webAppContextXml.toURI().toURL();
            } catch (MalformedURLException e) {
                Logger.getLogger(getLoggerName(getHost(), contextName)).log(Level.WARNING, "Unable to determine web application context.xml " + docBase, e);
            }
        }
        return result;
    }

    private URL getWebappConfigFileFromJar(File docBase, String contextName) {
        URL result = null;
        JarFile jar = null;
        try {
            jar = new JarFile(docBase);
            JarEntry entry = jar.getJarEntry(Constants.ApplicationContextXml);
            if (entry != null) {
                result = UriUtil.buildJarUrl(docBase, Constants.ApplicationContextXml);
            }
        } catch (IOException e) {
            Logger.getLogger(getLoggerName(getHost(), contextName)).log(Level.WARNING, "Unable to determine web application context.xml " + docBase, e);
        } finally {
            if (jar != null) {
                try {
                    jar.close();
                } catch (IOException e) {
                }
            }
        }
        return result;
    }
}

16 Source : CombinedRealm.java
with Apache License 2.0
from how2j

/**
 * Return the Principal replacedociated with the specified chain of X509 client
 * certificates. If there is none, return <code>null</code>.
 *
 * @param certs
 *            Array of client certificates, with the first one in the array
 *            being the certificate of the client itself.
 */
@Override
public Principal authenticate(X509Certificate[] certs) {
    Principal authenticatedUser = null;
    String username = null;
    if (certs != null && certs.length > 0) {
        username = certs[0].getSubjectDN().getName();
    }
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getInfo()));
        }
        authenticatedUser = realm.authenticate(certs);
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getInfo()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getInfo()));
            }
            break;
        }
    }
    return authenticatedUser;
}

16 Source : ContainerBase.java
with Apache License 2.0
from how2j

/**
 * Start this component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException
 *                if this component detects a fatal error that prevents this
 *                component from being used
 */
@Override
protected synchronized void startInternal() throws LifecycleException {
    // Start our subordinate components, if any
    if ((loader != null) && (loader instanceof Lifecycle))
        ((Lifecycle) loader).start();
    logger = null;
    getLogger();
    if ((manager != null) && (manager instanceof Lifecycle))
        ((Lifecycle) manager).start();
    if ((cluster != null) && (cluster instanceof Lifecycle))
        ((Lifecycle) cluster).start();
    Realm realm = getRealmInternal();
    if ((realm != null) && (realm instanceof Lifecycle))
        ((Lifecycle) realm).start();
    if ((resources != null) && (resources instanceof Lifecycle))
        ((Lifecycle) resources).start();
    // Start our child containers, if any
    Container[] children = findChildren();
    List<Future<Void>> results = new ArrayList<Future<Void>>();
    for (int i = 0; i < children.length; i++) {
        results.add(startStopExecutor.submit(new StartChild(children[i])));
    }
    boolean fail = false;
    for (Future<Void> result : results) {
        try {
            result.get();
        } catch (Exception e) {
            log.error(sm.getString("containerBase.threadedStartFailed"), e);
            fail = true;
        }
    }
    if (fail) {
        throw new LifecycleException(sm.getString("containerBase.threadedStartFailed"));
    }
    // Start the Valves in our pipeline (including the basic), if any
    if (pipeline instanceof Lifecycle)
        ((Lifecycle) pipeline).start();
    setState(LifecycleState.STARTING);
    // Start our thread
    threadStart();
}

16 Source : CombinedRealm.java
with GNU General Public License v3.0
from guang19

/**
 * Return the Principal replacedociated with the specified username and
 * credentials, if there is one; otherwise return <code>null</code>.
 *
 * @param username Username of the Principal to look up
 * @param credentials Preplacedword or other credentials to use in
 *  authenticating this username
 */
@Override
public Principal authenticate(String username, String credentials) {
    Principal authenticatedUser = null;
    for (Realm realm : realms) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("combinedRealm.authStart", username, realm.getClreplaced().getName()));
        }
        authenticatedUser = realm.authenticate(username, credentials);
        if (authenticatedUser == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authFail", username, realm.getClreplaced().getName()));
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("combinedRealm.authSuccess", username, realm.getClreplaced().getName()));
            }
            break;
        }
    }
    return authenticatedUser;
}

See More Examples