/*
  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.appserver.publisher;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opengroupware.jope.appserver.core.WOContext;
import org.opengroupware.jope.appserver.core.WOElement;
import org.opengroupware.jope.appserver.core.WOMessage;
import org.opengroupware.jope.appserver.core.WOResponse;

/*
 * JoResource
 * 
 * TODO: document
 */
public class JoResource extends WOElement {
  protected static final Log log = LogFactory.getLog("JoResource");
  
  protected WOContext context;
  protected URL       url;
  
  public JoResource(WOContext _ctx, URL _url) {
    this.context = _ctx;
    this.url     = _url;
  }
  
  /* generate response */

  @Override
  public void appendToResponse(WOResponse _r, WOContext _ctx) {
    InputStream is = null;
    try {
      URLConnection con = this.url.openConnection();
      
      is = con.getInputStream();
      
      String mimeType = con.getContentType();
      _r.setHeaderForKey(mimeType, "content-type");
      _r.setHeaderForKey("" + con.getContentLength(), "content-length");
      
      /* start streaming */
      
      _r.enableStreaming();
      
      byte[] buffer = new byte[0xFFFF];
      for (int len; (len = is.read(buffer)) != -1; )
        _r.appendContentData(buffer, len);
    }
    catch (IOException e) {
      log.error("IO error trying to deliver resource: " + this.url, e);
      _r.setStatus(WOMessage.HTTP_STATUS_INTERNAL_ERROR);
    }
    finally {
      try {
        if (is != null) is.close();
      }
      catch (IOException e) {
        log.warn("could not close URL input stream: " + this.url, e);
      }
    }
  }
  
  /* description */

  @Override
  public void appendAttributesToDescription(StringBuffer _d) {
    super.appendAttributesToDescription(_d);
    
    if (this.url != null)
      _d.append(" url=" + this.url);
  }
}
