/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.servicemix.components.http;

import org.apache.servicemix.jbi.container.SpringJBIContainer;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

/**
 * A Spring based HTTP Binding Servlet for ServiceMix which will
 * lookup the JBI container and the HttpBinding to use from the Spring
 * {@link ApplicationContext}
 * 
 * @version $Revision: 2153 $
 */
public class SpringBindingServlet extends BindingServlet {

    protected HttpBinding createHttpBinding(ServletConfig config) throws ServletException {
        ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        
        String jbiName = config.getInitParameter("jbi");
        if (jbiName == null) {
            jbiName = "jbi";
        }
        String endpointName = config.getInitParameter("endpoint");
        if (endpointName == null) {
            throw new ServletException("You must configure a servlet config parameter of endpointRef");
        }
        
        SpringJBIContainer jbi = (SpringJBIContainer) applicationContext.getBean(jbiName);
        if (jbi == null) {
            throw new ServletException("Could not find the JBIContainer in the Spring application context for name: " + jbiName);
        }
        
        Object value = jbi.getBean(endpointName);
        if (value == null) {
            throw new ServletException("Could not find bean in the SpringJBIContainer for id: " + endpointName);
        }
        if (value instanceof HttpBinding) {
            return (HttpBinding) value;
        }
        else {
            throw new ServletException("The endpoint is not a HttpBinding: " + value);
        }
    }
    

}
