import java.security.PrivilegedAction;
import java.io.*;

/**
 * This class implements the PrivilegedAction interface to demonstrate the
 * reading of a file that belongs to the client. This code will be 
 * executed by the server while impersonating the client principal.
 */
public class ReadFileAction implements PrivilegedAction {

    private String fileName;

    /**
     * Contructs a ReadFileAction instance.
     *
     * @param kerberosPrincipalName the name of the Kerberos principal
     * who owns the file that will be read. The filename is constructed
     * from the name of the principal.
     */
    public ReadFileAction(String kerberosPrincipalName) {
	/*
	 * Separate the realm component from the name and use the rest of
	 * it for constructing the filename. If the principal name is
	 * "joe@REALM" then the file that will be read is
	 * "data/joe_info.txt". The path separator "/" might be "\" in the
	 * case of Windows.
	 */
	int realmSeparatorPos = kerberosPrincipalName.lastIndexOf('@');
	fileName = "data" + File.separatorChar 
	    + kerberosPrincipalName.substring(0, realmSeparatorPos)
	    + "_info.txt";
    }

    /**
     * Does the actual reading of the file. It displays the text contained
     * in the file.
     */
    public Object run() {
	System.out.println("===============================================");
	System.out.println("Reading file: " + fileName);
	try {
	    BufferedReader reader = new BufferedReader(new FileReader(fileName));
	    String str = reader.readLine();
	    while (str != null) {
		System.out.println(str);
		str = reader.readLine();
	    }
	} catch (IOException e) {
	    System.err.println(e);
	}
	System.out.println("===============================================");
	return null;
    }
}
