/*
 * Copyright 2002-2008 the original author or authors.
 *
 * Licensed 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 test.feature.websupport;

import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.instanceOf;

import javax.servlet.ServletContext;

import org.junit.Assert;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;
import org.springframework.config.java.context.JavaConfigWebApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


/** TODO: JAVADOC */
public class JettyTests {

    private static final String CONTEXT_ROOT =
        "src/test/java/test/feature/websupport/contextroot";

    @Test
    public void testRootAppContextRegistration() throws Exception {
        Server server = new Server(0);
        WebAppContext webAppContext = new WebAppContext(CONTEXT_ROOT, "/");
        server.addHandler(webAppContext);
        server.start();

        ServletContext servletContext = webAppContext.getServletContext();

        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

        Assert.assertNotNull("root application context was not registered!", ctx);
        Assert.assertThat(ctx, instanceOf(JavaConfigWebApplicationContext.class));

        JavaConfigWebApplicationContext jctx = (JavaConfigWebApplicationContext) ctx;

        String configBeanName = AppConfig.class.getName();
        Assert.assertTrue(format("context did not contain @Configuration bean [%s] as expected", configBeanName),
                          jctx.containsBean(configBeanName));

        String serviceBeanName = "service";
        Assert.assertTrue(format("context did not contain @Bean [%s] as expected", serviceBeanName),
                          jctx.containsBean(serviceBeanName));

        MyService service = jctx.getBean(MyService.class, "service");
        Assert.assertEquals("service was not injected with property as expected",
                            "cbeams", service.getName());

        server.stop();
    }

}
