info.gewton.slsecurity.test.Test.java Source code

Java tutorial

Introduction

Here is the source code for info.gewton.slsecurity.test.Test.java

Source

/*
 * Copyright 2011 Gewton Jhames <gewtonj@gmail.com>
 * 
 * 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 info.gewton.slsecurity.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Classe utilitria para testes simples do projeto Service Layer Security <br />.
 * Os casos de testes devem herdar essa classe e implementar {@link #doTest()}. <br />
 * Os testes so feitos sem assertivas, apenas exibindo ao usurio os resultados.
 * 
 * @author gewton
 */
public abstract class Test {
    private ApplicationContext ac;
    protected Logger log = LoggerFactory.getLogger(Test.class);

    /**
     * Carrega o application context do Spring atravs do arquivo de configurao
     * padro applicationContext.xml, que dever estar disponvel no classpath 
     */
    protected void loadApplicationContext() {
        ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    }

    /**
     * Efetua autenticao, criando um contexto do Spring Security
     * @param login usurio
     * @param password senha
     */
    protected void setSecurityContext(String login, String password) {
        SecurityContextHolder.getContext()
                .setAuthentication(new UsernamePasswordAuthenticationToken(login, password));
    }

    /**
     * Retorna o contexto do Spring, caso o contexto no exista ainda, executa
     * {@link #loadApplicationContext()}.
     * @return o contexto do Spring
     */
    protected ApplicationContext getAc() {
        if (ac == null) {
            loadApplicationContext();
        }
        return ac;
    }

    /**
     * Efetua um caso de teste
     */
    protected abstract void doTest();
}