/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the License).  You may not use this file except in
 * compliance with the License.
 *
 * You can obtain a copy of the license at
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * Header Notice in each file and include the License file
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.
 * If applicable, add the following below the CDDL Header,
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Copyright (c) Ericsson AB, 2004-2007. All rights reserved.
 */
package org.jvnet.glassfish.comms.clb.core.sip;

import org.jvnet.glassfish.comms.clb.core.ConsistentHashRequest;
import org.jvnet.glassfish.comms.clb.core.ServerInstance;
import org.jvnet.glassfish.comms.clb.core.common.chr.ConsistentHashRouter;
import org.jvnet.glassfish.comms.clb.core.common.chr.StickyConsistentHashRouter;


/**
 * Component used to select a server. Uses a {@link StickyConsistentHashRouter}
 * and a {@link ConsistentHashRouter} (i.e DCR).
 */
class ServerSelectorImpl implements ServerSelector {
    StickyConsistentHashRouter stickyRouter;
    ConsistentHashRouter dcrRouter;

    /**
     * Creates an instance.
     * @param stickyRouter sticky router
     * @param router the non-sticky router
     */
    ServerSelectorImpl(StickyConsistentHashRouter stickyRouter,
        ConsistentHashRouter dcrRouter) {
        this.stickyRouter = stickyRouter;
        this.dcrRouter = dcrRouter;
    }

    /**
     * Select an instance to serve the specified request.
     *
     * @param req the request
     * @return an instance to server the specified request, or null if none was
     *         found.
     */
    public ServerInstance selectInstance(ConsistentHashRequest req) {
        ServerInstance server = stickyRouter.selectInstance(req);

        if (server != null) {
            return server;
        }

        return dcrRouter.selectInstance(req);
    }
}
