/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/testsuite/junit/urm/org/apache/slide/urm/test/authenticator/userdb/threads/TestThreadCreateUsers.java,v 1.3 2004/07/30 06:52:21 ozeigermann Exp $
 * $Revision: 1.3 $
 * $Date: 2004/07/30 06:52:21 $
 *
 * ====================================================================
 *
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * 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 org.apache.slide.urm.test.authenticator.userdb.threads;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.slide.urm.URMException;
import org.apache.slide.urm.authenticator.URMAdministrator;
import org.apache.slide.urm.authenticator.URMAuthenticationFailsException;
import org.apache.slide.urm.authenticator.URMAuthenticator;
import org.apache.slide.urm.common.URMPrincipal;

/**
 * @author zsa
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class TestThreadCreateUsers extends TestThreadUserDbBase {
    
    private String           mNamePrefix    = null;
    private int              mUserNumber    = 0;
    private List             mCreatedUsers  = Collections.synchronizedList(new LinkedList());
    
    public TestThreadCreateUsers(URMAuthenticator auth, URMAdministrator admin, String domain,
                                String namePrefix, int userNumber) {
        super(auth,  admin, domain);
        mAdministrator = admin;
        mDomain = domain;
        mNamePrefix = namePrefix;
        mUserNumber = userNumber;
    }
    
    public void create() {
        try {
        if (mNamePrefix == null) {
            String threadname = Thread.currentThread().getName();
            mNamePrefix = "URM_mt_test_usr"+threadname.substring(threadname.indexOf('-') + 1) + "_";
        }
        for (int i = 0; i < mUserNumber; ++i) {
            String usrname = mNamePrefix + Integer.toString(i);
            if (!mAdministrator.isUser(usrname, mDomain)) {
                /*try {
                    Thread.sleep(1 * mRandom.nextInt(50));
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }*/
                mAdministrator.createUser(usrname, usrname.toCharArray(), mDomain);
            }
            /*try {
                Thread.sleep(10 * mRandom.nextInt(3) + 20);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }*/
            if (!mAdministrator.isUser(usrname, mDomain)) {
                System.out.println("\nisUser() returns false for user '"+usrname+"' (it was just created).");
                break;
            }
            mCreatedUsers.add(usrname);
            if ((i % 3) == 0)
                Thread.yield();
        }
        } catch (URMException e) {
            e.printStackTrace();
            mThrowable = e;
        } finally {
            if (mThrowable != null) {
                List usrs = new LinkedList(mCreatedUsers);
                for (int i = 0; i < usrs.size(); ++i) {
                    try {
                        mAdministrator.deleteUser((String)usrs.get(i), mDomain);
                        mCreatedUsers.remove(usrs.get(i));
                    } catch (URMException e) {
                        //e.printStackTrace();
                    }
                }
            }
        }
    }
    
    public void check() {
        String usrname = null;
        try {
            int i = 0;
            for (Iterator iter = mCreatedUsers.iterator(); iter.hasNext(); ++i) {
                usrname = (String)iter.next();
                if (!mAdministrator.isUser(usrname, mDomain)) {
                    System.out.println("\nisUser() returns false for user '"+usrname+"' (it must be created).");
                }
                else {
                    URMPrincipal princ = mAuthenticator.authenticateUser(usrname, usrname.toCharArray(), mDomain);
                    if (princ == null)
                        System.out.println("\nauthenticateUser() returns null for user '"+usrname+"'.");
                }
                if ((i % 3) == 0)
                    Thread.yield();
            }
        } catch (URMException e) {
            System.out.println("\nauthenticateUser() of user '"+usrname+"' failed.");
            e.printStackTrace();
            mThrowable = e;
        }
    }
    
    public void update() {
        try {
            if (mCreatedUsers.size() > 1) {
                String usrname = (String)mCreatedUsers.get(mCreatedUsers.size() - 1);
                mAdministrator.deleteUser(usrname, mDomain);
                if (mAdministrator.isUser(usrname, mDomain))
                    System.out.println("\nisUser() returns true for user '"+usrname+"' (it was just removed in update()).");
                else
                    mCreatedUsers.remove(usrname);
                if (mCreatedUsers.size() > 1) {
                    usrname = (String)mCreatedUsers.get(0);
                    mAdministrator.deleteUser(usrname, mDomain);
                    if (mAdministrator.isUser(usrname, mDomain))
                        System.out.println("\nisUser() returns true for user '"+usrname+"' (it was just removed in update()).");
                    else
                        mCreatedUsers.remove(usrname);
                }
            }
        } catch (URMException e) {
            e.printStackTrace();
            mThrowable = e;
        }
    }
    
    public void clear() {
        int last_size;
        do {
            last_size = mCreatedUsers.size();
            List usrs = new LinkedList(mCreatedUsers);
            for (Iterator iter = usrs.iterator(); iter.hasNext();) {
                try {
                    String usrname = (String)iter.next();
                    /*try { Thread.sleep(mRandom.nextInt(50));
                    } catch (InterruptedException e1) { e1.printStackTrace(); }*/
                    mAdministrator.deleteUser(usrname, mDomain);
                    if (mAdministrator.isUser(usrname, mDomain)) {
                        System.out.println("\nisUser() returns true for user '"+usrname+"' (it was just removed in clear()).");
                        continue;
                    }
                    URMPrincipal princ = null;
                    try {
                        princ = mAuthenticator.authenticateUser(usrname, usrname.toCharArray(), mDomain);
                    } catch (URMAuthenticationFailsException e) {}
                    if (princ != null) {
                        System.out.println("\nThe user '"+usrname+"' can be still authenticated (it was just removed in clear()).");
                        continue;
                    }
                    mCreatedUsers.remove(usrname);
                } catch (URMException e) {
                    e.printStackTrace();
                    mThrowable = e;
                }
            }
        } while(mCreatedUsers.size() < last_size);
    }

    public List getCreatedUsers() {
        return mCreatedUsers;
    }
}
