/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included  with this distribution in
 * the LICENSE file.
 */

// Contributors:  Mathias Bogaert
//                Mark Womack

package org.apache.log4j.helpers;

import java.io.InputStream;
import java.io.File;
import java.io.FileInputStream;

/**
   Return the modification time for a file, and when asked, return an
   InputStream to the file.
   
   New version extends Watchdog class instead of Thread.  After original
   version by Ceki G&uuml;lc&uuml;  New version written by Mark Womack.


   @author Ceki G&uuml;lc&uuml;
   @since version 0.9.1 */
public class FileWatchdog extends Watchdog {

  /**
     The file to observe for changes.
   */
  protected File file;
  private boolean warnedAlready = false;

  public
  FileWatchdog() { }
  
  public
  FileWatchdog(String filename) {
    file = new File(filename);
  }

  public
  void setFilename(String filename) {
    file = new File(filename);
  }
  
  public
  String getFilename() {
  	return file.getPath();
  }
  
  protected
  long getModificationTime() {
    boolean fileExists;
    try {
      fileExists = file.exists();
    } catch(SecurityException  e) {
      LogLog.warn("Was not allowed to read check file existance, file:["+
		  file.getPath() +"].");
      this.stopWatching(); // there is no point in continuing
      return 0;
    }

    if(fileExists) {
      long l = file.lastModified(); // this can also throw a SecurityException
	  warnedAlready = false;
	  return l;
    } else {
      if(!warnedAlready) {
	    LogLog.debug("["+file.getPath()+"] does not exist.");
	    warnedAlready = true;
      }
      return 0;
    }
 }

  protected
  InputStream getConfigurationStream() {
  	try {
  	  return new FileInputStream(file);
  	} catch (Exception e) {
  	  LogLog.debug("could not open file input stream, file:["+
		  file.getPath() +"].", e);
  	  return null;
  	}
  }
}
