ChunkedContent.java :  » Portal » Open-Portal » com » sun » portal » rproxy » rewriter » util » http » Java Open Source

Java Open Source » Portal » Open Portal 
Open Portal » com » sun » portal » rproxy » rewriter » util » http » ChunkedContent.java
package com.sun.portal.rproxy.rewriter.util.http;

import java.io.ByteArrayOutputStream;
import com.sun.portal.log.common.PortalLogger;
import java.io.IOException;
import java.io.InputStream;
import java.util.StringTokenizer;

/**
 * @author Noble Paul
 * Date: Dec 31, 2003
 * The class handles content with chunked encoding
 */
public class ChunkedContent
{
    public static byte[] readChunkedContent( InputStream in ) throws IOException
    {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  byte[] buf;
  int chunkSize = getChunkSize( in );//length := 0 .read chunk-size,chunk-ext (if any),and CRLF

  while ( chunkSize > 0 )//  while (chunk-size > 0) {
  {
      buf = new byte[chunkSize];
      in.read( buf );//  read chunk-data
      readCRLF( in );//and CRLF
      baos.write( buf );//append chunk-data to entity-body .length := length + chunk-size
      chunkSize = getChunkSize( in); //read chunk-size and CRLF

  }
  return baos.toByteArray();
    }

    private static int getChunkSize( InputStream in ) throws IOException
    {
  int chunksize = 0;
  String line = readLine( in );
  if ( line == null )
      throw new IOException( "Could not read chunk block size" );
  StringTokenizer st = new StringTokenizer( line, "\t \n\r(;" );
  if ( st.hasMoreTokens() )
  {
      String hex = st.nextToken();
      try
      {
    chunksize = Integer.parseInt( hex, 16 );
      }
      catch ( NumberFormatException e )
      {
    throw new IOException( "Chunk size should be a hex number: '" + line + "', '" + hex + "'." );
      }
  }
  else
  {
      throw new IOException( "Chunk could not be read." );
  }
  return chunksize;
    }

    public static void readCRLF( InputStream in ) throws IOException
    {
  int cr = in.read();
  int lf = in.read();
  if ( cr != 13 && lf != 10 )
      throw new IOException( "Could not read CR & LF correctly: " + cr + ", " + lf );
    }

    private static String readLine( InputStream in ) throws IOException
    {
  StringBuffer sb = new StringBuffer( 50 );
  int l = -1;
  int count = 0;
  while ( true )
  {
      int c = in.read();
      if ( c == -1 )
    break;
      count++;
      if ( l == '\r' && c == '\n' )
      {
    sb.setLength( sb.length() - 1 );
    break;
      }
      sb.append( (char) c );
      l = c;
  }
  if ( count == 0 )
      return null;
  return sb.toString();
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.