/*
 * 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.common.chr;

import com.ericsson.ssa.sip.AddressImpl;
import com.ericsson.ssa.sip.Header;

import org.jvnet.glassfish.comms.clb.core.util.LoadbalancerUtil;
import org.jvnet.glassfish.comms.clb.proxy.http.util.HttpRequest;

import javax.servlet.sip.ServletParseException;
import javax.servlet.sip.SipServletRequest;


/**
 * This extractor implements a fall-back solution that will always yield hash
 * key.
 */
public class DefaultHashKeyExtractor implements HashKeyExtractor {
    /**
     * Creates hash key by concatenating remote address and port.
     *
     * @see org.jvnet.glassfish.comms.clb.core.common.chr.HashKeyExtractor#getHashKey(javax.servlet.http.HttpServletRequest)
     */
    public String getHashKey(HttpRequest request) {
        return LoadbalancerUtil.encodeParameter(request.remoteAddr().toString() +
            request.getRemotePort());
    }

    /**
     * Creates the hash key by concatenating Call-ID and From headers.
     *
     * @see org.jvnet.glassfish.comms.clb.core.common.chr.HashKeyExtractor#getHashKey(javax.servlet.sip.SipServletRequest)
     */
    public String getHashKey(SipServletRequest req) {
        String callId = req.getHeader(Header.CALL_ID);
        String fromTag;

        try {
            fromTag = req.getAddressHeader(Header.FROM)
                         .getParameter(AddressImpl.TAG_PARAM);
        } catch (ServletParseException e) {
            fromTag = "UNDEFINED"; // Could never happen, but cope with it.
        }

        return LoadbalancerUtil.encodeParameter(callId + fromTag);
    }
}
