// $Header$
/*
 * Copyright 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.jmeter.functions;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

/**
 * This class wraps the FileRowColContainer for use across multiple threads.
 * 
 * It does this by maintaining a list of open files, keyed by file name (or
 * alias, if used). A list of open files is also maintained for each thread,
 * together with the current line number.
 * 
 * @version $Revision$ $Date$
 */
public class FileWrapper {

	transient private static Logger log = LoggingManager.getLoggerForClass();

	private FileRowColContainer container;

	private int currentRow;

	private static final int NO_LINE = -1;

	private static String defaultFile = ""; // for omitted file names

	private static Map fileContainers = new HashMap(); // Map file names to
														// containers

	/*
	 * Only needed locally
	 */
	private FileWrapper(FileRowColContainer fdc) {
		super();
		container = fdc;
		currentRow = -1;
	}

	/* The cache of file packs */
	private static ThreadLocal filePacks = new ThreadLocal() {
		protected Object initialValue() {
			return new HashMap();
		}
	};

	private static String checkDefault(String file) {
		if (file.length() == 0) {
			if (fileContainers.size() == 1 && defaultFile.length() > 0) {
				log.warn("Using default: " + defaultFile);
				file = defaultFile;
			} else {
				log.error("Cannot determine default file name");
			}
		}
		return file;
	}

	/*
	 * called by CSVRead(file,alias)
	 */
	public static synchronized void open(String file, String alias) {
		log.info("Opening " + file + " as " + alias);
		file = checkDefault(file);
		if (alias.length() == 0) {
			log.error("Alias cannot be empty");
			return;
		}
		Map m = (Map) filePacks.get();
		if (m.get(alias) == null) {
			FileRowColContainer frcc;
			try {
				frcc = getFile(file, alias);
				log.info("Stored " + file + " as " + alias);
				m.put(alias, new FileWrapper(frcc));
			} catch (FileNotFoundException e) {
				// Already logged
			} catch (IOException e) {
				// Already logged
			}
		}
	}

	private static FileRowColContainer getFile(String file, String alias) throws FileNotFoundException, IOException {
		FileRowColContainer frcc;
		if ((frcc = (FileRowColContainer) fileContainers.get(alias)) == null) {
			frcc = new FileRowColContainer(file);
			fileContainers.put(alias, frcc);
			log.info("Saved " + file + " as " + alias + " delimiter=<" + frcc.getDelimiter() + ">");
			if (defaultFile.length() == 0) {
				defaultFile = file;// Save in case needed later
			}
		}
		return frcc;
	}

	/*
	 * Called by CSVRead(x,next) - sets the row to nil so the next row will be
	 * picked up the next time round
	 * 
	 */
	public static void endRow(String file) {
		file = checkDefault(file);
		Map my = (Map) filePacks.get();
		FileWrapper fw = (FileWrapper) (my).get(file);
		if (fw == null) {
			log.warn("endRow(): no entry for " + file);
		} else {
			fw.endRow();
		}
	}

	private void endRow() {
		if (currentRow == NO_LINE) {
			log.warn("endRow() called twice in succession");
		}
		currentRow = NO_LINE;
	}

	public static String getColumn(String file, int col) {
		Map my = (Map) filePacks.get();
		FileWrapper fw = (FileWrapper) (my).get(file);
		if (fw == null) // First call
		{
			if (file.startsWith("*")) {
				log.warn("Cannot perform initial open using alias " + file);
			} else {
				file = checkDefault(file);
				log.info("Attaching " + file);
				open(file, file);
				fw = (FileWrapper) my.get(file);
			}
			// TODO improve the error handling
			if (fw == null)
				return "";
		}
		return fw.getColumn(col);
	}

	private String getColumn(int col) {
		if (currentRow == NO_LINE) {
			currentRow = container.nextRow();

		}
		return container.getColumn(currentRow, col);
	}

	/**
	 * Gets the current row number (mainly for error reporting)
	 * 
	 * @param file
	 * @return the current row number for this thread
	 */
	public static int getCurrentRow(String file) {

		Map my = (Map) filePacks.get();
		FileWrapper fw = (FileWrapper) (my).get(file);
		if (fw == null) // Not yet open
		{
			return -1;
		} else {
			return fw.currentRow;
		}
	}

	/**
	 * 
	 */
	public static void clearAll() {
		log.debug("clearAll()");
		Map my = (Map) filePacks.get();
		for (Iterator i = my.entrySet().iterator(); i.hasNext();) {
			Object fw = i.next();
			log.info("Removing " + fw.toString());
			i.remove();
		}
		fileContainers.clear();
		defaultFile = "";
	}
}

@@ -1487,107 +1487,209 @@
 s%0A%0A%09
-private static M
+/*%0A     * This Map serves two purposes:%0A     * - m
 ap
+s
  file
-Containers = new HashMap(); // Map file names to%0A%09%09%09%09%09%09%09%09%09%09%09%09%09%09// containers
+ names to  containers%0A     * - ensures only one container per file across all threads%0A%09 */%0A%09private static Map fileContainers = new HashMap(); 
 %0A%0A%09/
@@ -1820,16 +1820,16 @@
 -1;%0A%09%7D%0A%0A
-
 %09/* The 
@@ -1848,16 +1848,48 @@
 e packs 
+- used to improve thread access 
 */%0A%09priv

Document usage of Maps