/**
 * 
 */
package gov.nih.nci.cabig.caaers.security;

import java.io.File;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.TestingAuthenticationToken;
import org.dbunit.database.DatabaseDataSourceConnection;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import gov.nih.nci.security.acegi.csm.authorization.AuthorizationSwitch;

/**
 * @author <a href="mailto:joshua.phillips@semanticbits.com">Joshua Phillips</a>
 *
 */
public class SecurityTestUtils {
    public static void switchUser(String userName, String... roles) {
        GrantedAuthority[] authorities = new GrantedAuthority[roles.length];
        for (int i = 0; i < roles.length; i++) {
            authorities[i] = new GrantedAuthorityImpl(roles[i]);
        }
        Authentication auth = new TestingAuthenticationToken(userName,
            "ignored", authorities);
        auth.setAuthenticated(true);
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    public static void switchToSuperuser() {
        switchUser("test-default-user", "ROLE_caaers_super_user");
    }

    public static void switchToNoUser() {
        switchUser(null);
    }

    public static boolean enableAuthorization(boolean on, ApplicationContext context) {
        AuthorizationSwitch sw = (AuthorizationSwitch) context.getBean("authorizationSwitch");
        if (sw == null) throw new RuntimeException("Authorization switch not found");
        boolean current = sw.isOn();
        sw.setOn(on);
        return current;
    }
    
    public static Throwable getRootCause(Exception ex) {
		Throwable t = ex;
		do{
			t = t.getCause();
		}while(t.getCause() != null);
		return t;
	}

    public static void insertCSMPolicy(DataSource dataSource) throws SQLException {
        DatabaseDataSourceConnection conn = null;
        try{
            conn = new DatabaseDataSourceConnection(dataSource);
            FlatXmlDataSet data = new FlatXmlDataSet(Thread.currentThread().getContextClassLoader().getResourceAsStream("gov/nih/nci/cabig/caaers/security/testdata/CSM_policy.xml"));
            DatabaseOperation op = DatabaseOperation.INSERT;
            op.execute(conn, data);
        } catch (Exception ex) {
            throw new RuntimeException("Error inserting CSM policy: " + ex.getMessage(), ex);
        } finally {
            if (conn != null) conn.close();
        }
    }

    public static void deleteCSMPolicy(DataSource dataSource) throws SQLException {
        DatabaseDataSourceConnection conn = null;
        try{
            conn = new DatabaseDataSourceConnection(dataSource);
            FlatXmlDataSet data = new FlatXmlDataSet(Thread.currentThread().getContextClassLoader().getResourceAsStream("gov/nih/nci/cabig/caaers/security/testdata/CSM_policy.xml"));
            DatabaseOperation op = DatabaseOperation.DELETE_ALL;
            op.execute(conn, data);
            conn.close();
        }catch(Exception ex){
            throw new RuntimeException("Error inserting CSM policy: " + ex.getMessage(), ex);
        } finally {
            if (conn == null) conn.close();
        }
    }

}

@@ -1,16 +1,4 @@
-/**%0A * %0A */%0A
 pack
@@ -48,82 +48,73 @@
 ort 
-java.io.File;%0Aimport java.sql.SQLException;%0A%0Aimport javax.sql.DataSource;%0A
+gov.nih.nci.security.acegi.csm.authorization.AuthorizationSwitch;
 %0Aimp
@@ -360,16 +360,57 @@
 nToken;%0A
+import org.dbunit.DatabaseUnitException;%0A
 import o
@@ -610,154 +610,94 @@
 xt;%0A
+%0A
 import 
-org.springframework.context.support.ClassPathXmlApplicationContext;%0Aimport gov.nih.nci.security.acegi.csm.authorization.AuthorizationSwitch
+javax.sql.DataSource;%0Aimport java.io.IOException;%0Aimport java.sql.SQLException
 ;%0A%0A/
@@ -782,16 +782,38 @@
 s%3C/a%3E%0A *
+ @author Rhett Sutphin
 %0A */%0Apub
@@ -2103,35 +2103,32 @@
 aSource) throws 
-SQL
 Exception %7B%0A    
@@ -2135,115 +2135,52 @@
     
-DatabaseDataSourceConnection conn = null;%0A        try%7B%0A            conn = new DatabaseDataSourceConnection(
+applyPolicy(DatabaseOperation.CLEAN_INSERT, 
 data
@@ -2196,484 +2196,154 @@
     
+%7D%0A%0A
     
-    FlatXmlDataSet data = new FlatXmlDataSet(Thread.currentThread().getContextClassLoader().getResourceAsStream(%22gov/nih/nci/cabig/caaers/security/testdata/CSM_policy.xml%22));%0A            DatabaseOperation op = DatabaseOperation.INSERT;%0A            op.execute(conn, data);%0A        %7D catch (Exception ex) %7B%0A            throw new RuntimeException(%22Error inserting CSM policy: %22 + ex.getMessage(), ex);%0A        %7D finally %7B%0A            if (conn != null) conn.close();%0A        %7D
+public static void deleteCSMPolicy(DataSource dataSource) throws Exception %7B%0A        applyPolicy(DatabaseOperation.DELETE_ALL, dataSource);
 %0A   
@@ -2343,37 +2343,38 @@
 e);%0A    %7D%0A%0A    p
-ublic
+rivate
  static void del
@@ -2370,32 +2370,50 @@
 ic void 
-deleteCSM
+apply
 Policy(
+DatabaseOperation op, 
 DataSour
@@ -2438,32 +2438,68 @@
 ows SQLException
+, IOException, DatabaseUnitException
  %7B%0A        Datab
@@ -2546,16 +2546,17 @@
      try
+ 
 %7B%0A      
@@ -2713,16 +2713,33 @@
 Loader()
+%0A                
 .getReso
@@ -2830,244 +2830,29 @@
     
-DatabaseOperation op = DatabaseOperation.DELETE_ALL;%0A            op.execute(conn, data);%0A            conn.close();%0A        %7Dcatch(Exception ex)%7B%0A            throw new RuntimeException(%22Error inserting CSM policy: %22 + ex.getMessage(), ex
+op.execute(conn, data
 );%0A 
@@ -2891,17 +2891,17 @@
 f (conn 
-=
+!
 = null) 

Refactor to remove code repetition in csm policy methods; switch to CLEAN_INSERT to eliminate data left over by failed test runs