/*
  Copyright (C) 2007 Helge Hess

  This file is part of JOPE.

  JOPE is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the
  Free Software Foundation; either version 2, or (at your option) any
  later version.

  JOPE is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
  License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with JOPE; see the file COPYING.  If not, write to the
  Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  02111-1307, USA.
*/
package org.opengroupware.jope.ofs;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.opengroupware.jope.foundation.NSException;

public class OFSFile extends OFSBaseObject {
  
  public OFSFile(Object _container, String _name, File _file) {
    super(_container, _name, _file);
  }
  
  /* content */

  public InputStream openStream() {
    if (this.file == null)
      return null;
    
    FileInputStream in;
    try {
      in = new FileInputStream(this.file);
    }
    catch (FileNotFoundException e) {
      log.error("could not open document: " + this.file);
      return null;
    }
    
    return new BufferedInputStream(in);
  }
  
  public byte[] content() {
    try {
      byte[] contents = new byte[(int)this.file.length()];
      byte[] buffer = new byte[4096];
      int gotlen, pos = 0;
      
      InputStream in = new FileInputStream(this.file);
      
      while ((gotlen = in.read(buffer)) != -1) {
        System.arraycopy(buffer, 0, contents, pos, gotlen);
        pos += gotlen;
      }
      
      in.close();
      in = null;
      
      return contents;
    }
    catch (IOException ioe) {      
      // TODO: what to do with failed requests?
      log().warn("could not read request ...");
      return null;
    }
  }
  
  public Exception writeContent(Object _content) {
    return new NSException("not implemented");
  }
    
  /* description */

  @Override
  public void appendAttributesToDescription(StringBuffer _d) {
    super.appendAttributesToDescription(_d);
  }
}
