cocoon-cvs mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From froehl...@apache.org
Subject cvs commit: xml-cocoon2/src/scratchpad/src/org/apache/cocoon/reading ByteRangeResourceReader.java
Date Wed, 12 Jun 2002 17:25:23 GMT
froehlich    2002/06/12 10:25:23

  Added:       src/scratchpad/src/org/apache/cocoon/reading
                        ByteRangeResourceReader.java
  Log:
  applied patch from stuart.roebuck@adolos.co.uk.
  added ByteRangeResourceReader
  
  Revision  Changes    Path
  1.1                  xml-cocoon2/src/scratchpad/src/org/apache/cocoon/reading/ByteRangeResourceReader.java
  
  Index: ByteRangeResourceReader.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2002 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      apache@apache.org.
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.reading;
  
  import org.apache.avalon.framework.parameters.Parameters;
  import org.apache.cocoon.ProcessingException;
  import org.apache.cocoon.caching.CacheValidity;
  import org.apache.cocoon.caching.Cacheable;
  import org.apache.cocoon.caching.TimeStampCacheValidity;
  import org.apache.cocoon.environment.Context;
  import org.apache.cocoon.environment.ObjectModelHelper;
  import org.apache.cocoon.environment.Request;
  import org.apache.cocoon.environment.Response;
  import org.apache.cocoon.environment.Source;
  import org.apache.cocoon.environment.SourceResolver;
  import org.apache.cocoon.environment.http.HttpResponse;
  import org.apache.cocoon.util.ByteRange;
  import org.apache.cocoon.util.HashUtil;
  import org.xml.sax.SAXException;
  
  import java.io.IOException;
  import java.io.InputStream;
  import java.util.Date;
  import java.util.Map;
  import java.util.StringTokenizer;
  
  /**
   *
   *
   * The <code>ResourceReader</code> component is used to serve binary data
   * in a sitemap pipeline. It makes use of HTTP Headers to determine if
   * the requested resource should be written to the <code>OutputStream</code>
   * or if it can signal that it hasn't changed.
   *
   * Parameters:
   *   <dl>
   *     <dt>&lt;expires&gt;</dt>
   *       <dd>This parameter is optional. When specified it determines how long
   *           in miliseconds the resources can be cached by any proxy or browser
   *           between Cocoon2 and the requesting visitor.
   *       </dd>
   *   </dl>
   *
   * @author <a href="mailto:Giacomo.Pati@pwr.ch">Giacomo Pati</a>
   * @version CVS $Id: ByteRangeResourceReader.java,v 1.1 2002/06/12 17:25:23 froehlich Exp
$
   */
  public class ByteRangeResourceReader
    extends AbstractReader
    implements Cacheable {
  
      private final static int BUFFER_SIZE = 8192;
        
      /** The  source */
      private Source      inputSource;
  
  
      /**
       * Setup the reader.
       * The resource is opened to get an <code>InputStream</code>,
       * the length and the last modification date
       */
      public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par)
      throws ProcessingException, SAXException, IOException {
          super.setup(resolver, objectModel, src, par);
          this.inputSource = this.resolver.resolve(super.source);
      }
  
      public void recycle() {
          super.recycle();
          if (this.inputSource != null) {
              this.inputSource.recycle();
              this.inputSource = null;
          }
      }
  
      /**
       * Generate the unique key.
       * This key must be unique inside the space of this component.
       *
       * @return The generated key hashes the src
       */
      public long generateKey() {
          if (this.inputSource.getLastModified() != 0) {
              return HashUtil.hash(this.inputSource.getSystemId());
          }
          return 0;
      }
  
      /**
       * Generate the validity object.
       *
       * @return The generated validity object or <code>null</code> if the
       *         component is currently not cacheable.
       */
      public CacheValidity generateValidity() {
          if (getLastModified() != 0) {
              return new TimeStampCacheValidity(this.inputSource.getLastModified());
          }
          return null;
      }
  
      /**
       * @return the time the read source was last modified or 0 if it is not
       *         possible to detect
       */
      public long getLastModified() {
          final Request request = ObjectModelHelper.getRequest(this.objectModel);
          String byteRangeString = request.getHeader("Range");
          if (byteRangeString == null) {
              // There is no byte range request so return a value which will allow caching.
              return this.inputSource.getLastModified();
          } else {
              // This is a byte range request so we can't use the cache, return 0.
              return 0;
          }
      }
  
      /**
       * Generates the requested resource.
       */
      public void generate()
      throws IOException, ProcessingException {
          final Response response = ObjectModelHelper.getResponse(this.objectModel);
          final Request request = ObjectModelHelper.getRequest(this.objectModel);
          String byteRangeString = request.getHeader("Range");
  
          try {
              final long expires = parameters.getParameterAsInteger("expires", -1);
  
              if (expires > 0) {
                  response.setDateHeader("Expires", System.currentTimeMillis() + expires);
              }
  
              long contentLength = this.inputSource.getContentLength();
  
              // Set up byte range.
              ByteRange byteRange;
              if (byteRangeString != null) {
                  try {
                      byteRangeString = byteRangeString.substring(byteRangeString.indexOf('=')
+ 1);
                      byteRange = new ByteRange(byteRangeString);
                  } catch (NumberFormatException e) {
                      byteRange = null;
                      // Respond with status 416 (Request range not satisfiable)
                      ( (HttpResponse) response).setStatus(416);
                  }
              } else {
                  byteRange = null;
              }
  
              if (byteRange != null) {
                  String entityLength;
                  String entityRange;
                  if (contentLength != -1) {
                      entityLength = "" + contentLength;
                      entityRange = byteRange.intersection(new ByteRange(0, contentLength)).toString();
                  } else {
                      entityLength = "*";
                      entityRange = byteRange.toString();
                  }
                  response.setHeader("Content-Range", entityRange + "/" + entityLength);
                  // Response with status 206 (Partial content)
                  ( (HttpResponse) response).setStatus(206);
              } else {
                  // FIXME (VG): Environment has setContentLength, and
                  // Response interface has not. Strange.
                  response.setHeader("Content-Length", Long.toString(contentLength));
              }
              response.setHeader("Accept-Ranges", "bytes");
              
              byte[] buffer = new byte[BUFFER_SIZE];
              int length = -1;
              InputStream inputStream = this.inputSource.getInputStream();
              if (byteRange == null) {
                  while ((length = inputStream.read(buffer)) > -1) {
                      out.write(buffer, 0, length);
                  }
              } else {
                  int pos = 0;
                  int posEnd;
                  while ((length = inputStream.read(buffer)) > -1) {
                      posEnd = pos + length - 1;
                      ByteRange intersection = byteRange.intersection(new ByteRange(pos, posEnd));
                      if (intersection != null) {
                          out.write(buffer, (int) intersection.getStart() - pos, (int) intersection.length());
                      }
                      pos += length;
                  }
              }
              inputStream.close();
              inputStream = null;
              out.flush();
          } catch (IOException ioe) {
              getLogger().debug("Received an IOException, assuming client severed connection
on purpose");
          }
      }
  
      /**
       * Returns the mime-type of the resource in process.
       */
      public String getMimeType () {
          Context ctx = ObjectModelHelper.getContext(this.objectModel);
  
          if (ctx != null) {
             return ctx.getMimeType(this.source);
          } else {
             return null;
          }
      }
  
  
  }
  
  
  

----------------------------------------------------------------------
In case of troubles, e-mail:     webmaster@xml.apache.org
To unsubscribe, e-mail:          cocoon-cvs-unsubscribe@xml.apache.org
For additional commands, e-mail: cocoon-cvs-help@xml.apache.org


Mime
View raw message