Examples of CWDataBuffers


Examples of com.planet_ink.coffee_web.util.CWDataBuffers

    {
      response.insertTop(header, 0,false);
      return response;
    }
    if(response!=null)
      return new CWDataBuffers(header, response.getLastModified().getTime(),false);
    return new CWDataBuffers(header, System.currentTimeMillis(),false);
  }
View Full Code Here

Examples of com.planet_ink.coffee_web.util.CWDataBuffers

   
    final MIMEType mimeType = MIMEType.getMIMEType(pageFile.getName());
    DataBuffers buffers = null;
    try
    {
      buffers = new CWDataBuffers(); // before forming output, process range request
      final Class<? extends HTTPOutputConverter> converterClass=config.getConverters().findConverter(mimeType);
      if(converterClass != null)
      {
        buffers=config.getFileCache().getFileData(pageFile, null);
        //checkIfModifiedSince(request,buffers); this is RETARDED!!!
        HTTPOutputConverter converter;
        try {
          converter = converterClass.newInstance();
          return new CWDataBuffers(converter.convertOutput(config, request, pathFile, HTTPStatus.S200_OK, buffers.flushToBuffer()), System.currentTimeMillis(), true);
        }
        catch (final Exception e) { }
        return buffers;
      }
      else
View Full Code Here

Examples of com.planet_ink.coffee_web.util.CWDataBuffers

   
    HTTPStatus responseStatus = HTTPStatus.S200_OK;
    DataBuffers buffers = null;
    try
    {
      buffers = new CWDataBuffers(); // before forming output, process range request
      switch(request.getMethod())
      {
      case HEAD:
      case GET:
      case POST:
      {
        final Class<? extends HTTPOutputConverter> converterClass=config.getConverters().findConverter(mimeType);
        if(converterClass != null)
        {
          buffers=config.getFileCache().getFileData(pageFile, null);
          //checkIfModifiedSince(request,buffers); this is RETARDED!!!
          try
          {
            HTTPOutputConverter converter;
            converter = converterClass.newInstance();
            extraHeaders.put(HTTPHeader.CACHE_CONTROL, "no-cache");
            final long dateTime=System.currentTimeMillis();
            extraHeaders.put(HTTPHeader.EXPIRES, HTTPIOHandler.DATE_FORMAT.format(Long.valueOf(dateTime)));
            buffers=new CWDataBuffers(converter.convertOutput(config, request, pathFile, HTTPStatus.S200_OK, buffers.flushToBuffer()), dateTime, true);
            buffers = handleEncodingRequest(request, null, buffers, extraHeaders);
          }
          catch (final Exception e)
          {
            config.getLogger().throwing("", "", e);
            throw HTTPException.standardException(HTTPStatus.S500_INTERNAL_ERROR);
          }
        }
        else
        {
          final String[] eTagMarker =generateETagMarker(request);
          buffers=config.getFileCache().getFileData(pageFile, eTagMarker);
          if((eTagMarker[0]!=null)&&(eTagMarker[0].length()>0))
            extraHeaders.put(HTTPHeader.ETAG, eTagMarker[0]);
          checkIfModifiedSince(request,buffers);
          buffers = handleEncodingRequest(request, pageFile, buffers, extraHeaders);
        }
        if(buffers == null)
        {
          throw HTTPException.standardException(HTTPStatus.S500_INTERNAL_ERROR);
        }
        final long fullSize = buffers.getLength();
        final long[] fullRange = setRangeRequests(request, buffers);
        if(fullRange != null)
        {
          responseStatus = HTTPStatus.S206_PARTIAL_CONTENT;
          extraHeaders.put(HTTPHeader.CONTENT_RANGE, "bytes "+fullRange[0]+"-"+fullRange[1]+"/"+fullSize);
        }
        break;
      }
      default:
        break;
      }

      lastHttpStatusCode=responseStatus.getStatusCode();

      String specifiedHost = request.getHost(); // check for chunking
      int chunkedSize = 0;
      if(specifiedHost != null)
      {
        int portIndex=specifiedHost.indexOf(':');
        if(portIndex > 0)
          specifiedHost=specifiedHost.substring(0,portIndex);
        final ChunkSpec chunkSpec = config.getChunkSpec(specifiedHost, request.getClientPort(), request.getUrlPath());
        if((chunkSpec != null) && (buffers.getLength() >= chunkSpec.getMinFileSize()))
        {
          chunkedSize = chunkSpec.getChunkSize(); // set chunking flag
          extraHeaders.put(HTTPHeader.TRANSFER_ENCODING, "chunked");
        }
      }
     
      // finally, generate the response headers and body
      switch(request.getMethod())
      {
      case HEAD:
        final DataBuffers header=new CWDataBuffers(generateStandardHeaderResponse(request, responseStatus, extraHeaders, buffers), buffers.getLastModified().getTime(), false);
        buffers.close();
        return header;
      case GET:
      case POST:
        final DataBuffers buf = generateStandardResponse(request, responseStatus, extraHeaders, buffers);
View Full Code Here

Examples of com.planet_ink.coffee_web.util.CWDataBuffers

        final ByteBuffer outBuf=ByteBuffer.allocate(sslOutgoingBuffer.capacity());
        sslEngine.wrap(appSizedBuf, outBuf);
        if(outBuf.position() > 0)
        {
          outBuf.flip();
          super.writeBytesToChannel(new CWDataBuffers(outBuf, 0, false));
        }
      }
    }
    buffers.close();
  }
View Full Code Here

Examples of com.planet_ink.coffee_web.util.CWDataBuffers

    if(!normalizedHeaders.contains(HTTPHeader.DATE.lowerCaseName()))
      str.append(HTTPHeader.DATE.makeLine(HTTPIOHandler.DATE_FORMAT.format(new Date(System.currentTimeMillis()))));
    for(String key : cookies.keySet())
      str.append(HTTPHeader.SET_COOKIE.makeLine(key+"="+cookies.get(key)));
    str.append(EOLN);
    CWDataBuffers bufs=new CWDataBuffers(str.toString().getBytes(), System.currentTimeMillis(),false);
    if(bout.size()>0)
    {
      final byte[] output=bout.toByteArray();
      bufs.add(output, System.currentTimeMillis(),true);
      try{ bout.flush();  bout.reset(); bout.close(); }catch(final Exception e){}
    }
    return bufs;
  }
View Full Code Here

Examples of com.planet_ink.coffee_web.util.CWDataBuffers

          }
          responseBuffer.flip(); // turn the writeable buffer into a "readable" one
          final ByteBuffer writeableBuf=ByteBuffer.allocate(responseBuffer.remaining());
          writeableBuf.put(responseBuffer);
          writeableBuf.flip();
          clientReader.writeBytesToChannel(new CWDataBuffers(writeableBuf,0,false));
          responseBuffer.clear();
        }
        handleWrites();
        if((!closeMe) // if eof is reached, close this channel and mark it for deletion by the web server
        && ((bytesRead < 0)
View Full Code Here

Examples of com.planet_ink.coffee_web.util.CWDataBuffers

        {
          buffer.flip(); // turn the writeable buffer into a "readable" one
          final ByteBuffer writeableBuf=ByteBuffer.allocate(buffer.remaining());
          writeableBuf.put(buffer);
          writeableBuf.flip();
          forwarder.writeBytesToChannel(new CWDataBuffers(writeableBuf,0,false));
          buffer.clear();
        }
        break;
      }
      default:
      {
        buffer.flip(); // turn the writeable buffer into a "readable" one
        int lastEOLIndex = 0; // the marker for the last place an EOLN was found
        char c;  // current character being examined
        while(buffer.position() < buffer.limit())
        {
          c=(char)buffer.get();
          switch(state)
          {
          case CHUNKED_ENDER_INLINE:
          {
            if(c=='\r')
              state=ParseState.CHUNKED_ENDER_EOLN;
            else
              throw HTTPException.standardException(HTTPStatus.S400_BAD_REQUEST);
            break;
          }
          case CHUNKED_ENDER_EOLN:
          {
            if(c=='\n')
            {
              lastEOLIndex=buffer.position();
              state=ParseState.CHUNKED_HEADER_INLINE;
            }
            else
              throw HTTPException.standardException(HTTPStatus.S400_BAD_REQUEST);
            break;
          }
          case CHUNKED_HEADER_INLINE:
          {
            if(c=='\r')
              state=ParseState.CHUNKED_HEADER_EOLN;
            break;
          }
          case CHUNKED_HEADER_EOLN:
          {
            if (c=='\n')
            {
              final String chunkSizeStr = new String(Arrays.copyOfRange(buffer.array(), lastEOLIndex, buffer.position()-2),utf8).trim();
              lastEOLIndex=buffer.position();
              if (chunkSizeStr.length()>0)
              {
                final String[] parts=chunkSizeStr.split(";");
                this.nextChunkSize = Integer.parseInt(parts[0],16);
                if(this.nextChunkSize == 0) // we've reached the last chunk
                {
                  buffer = currentReq.setToReceiveContentChunkedBody((int)config.getRequestLineBufBytes());
                  buffer.flip();
                  lastEOLIndex=0;
                  state=ParseState.CHUNKED_TRAILER_INLINE;
                }
                else
                {
                   // check for illegal request
                  if((this.nextChunkSize + currentReq.getBufferSize()) > config.getRequestMaxBodyBytes())
                  {
                    throw HTTPException.standardException(HTTPStatus.S413_REQUEST_ENTITY_TOO_LARGE);
                  }
                  buffer = currentReq.setToReceiveContentChunkedBody(this.nextChunkSize);
                  buffer.flip();
                  lastEOLIndex=0;
                  state=ParseState.CHUNKED_BODY;
                }
              }
              else
                throw HTTPException.standardException(HTTPStatus.S400_BAD_REQUEST);
            }
            else
              throw HTTPException.standardException(HTTPStatus.S400_BAD_REQUEST);
            break;
          }
          case REQ_INLINE:
            if(c=='\r')
              state=ParseState.REQ_EOLN;
            break;
          case REQ_EOLN:
          {
            if (c=='\n')
            {
              final String requestLine = new String(Arrays.copyOfRange(buffer.array(), lastEOLIndex, buffer.position()-2),utf8);
              lastEOLIndex=buffer.position();
              state=ParseState.HDR_INLINE;
              if (requestLine.length()>0)
              {
                try
                {
                  currentReq.parseRequest(requestLine);
                }
                catch(final NumberFormatException ne)
                {
                  throw HTTPException.standardException(HTTPStatus.S400_BAD_REQUEST);
                }
              }
              else
              {
                // ignore blank lines here -- perhaps someone telnetted in.
              }
            }
            else // an error! Ignore this line!
            {
              lastEOLIndex=buffer.position();
              state=ParseState.REQ_INLINE;
            }
            break;
          }
          case HDR_INLINE:
            if(c=='\r')
              state=ParseState.HDR_EOLN;
            break;
          case CHUNKED_TRAILER_INLINE:
            if(c=='\r')
              state=ParseState.CHUNKED_TRAILER_EOLN;
            break;
          case CHUNKED_TRAILER_EOLN:
          case HDR_EOLN:
          {
            if (c=='\n')
            {
              final String headerLine = new String(Arrays.copyOfRange(buffer.array(), lastEOLIndex, buffer.position()-2),utf8);
              lastEOLIndex=buffer.position();
              if(headerLine.length()>0)
              {
                String host = currentReq.parseHeaderLine(headerLine);
                if (state == ParseState.CHUNKED_TRAILER_EOLN)
                  state=ParseState.CHUNKED_TRAILER_INLINE;
                else
                  state=ParseState.HDR_INLINE;
               
                if(host!=null)
                {
                  final int x=host.indexOf(':');
                  if(x>0) host=host.substring(0, x); // we only care about the host, we KNOW the port.
                  final Pair<String,WebAddress> forward=config.getPortForward(host,currentReq.getClientPort(),currentReq.getUrlPath());
                  if((forward != null) && (state != ParseState.CHUNKED_TRAILER_INLINE))
                  {
                    final String requestLine=startPortForwarding(forward.second, forward.first);
                    if(forwarder!=null)
                    {
                      final DataBuffers out=new CWDataBuffers();
                      out.add(ByteBuffer.wrap(requestLine.getBytes()),0,false);
                      final ByteBuffer writeableBuf=ByteBuffer.allocate(buffer.remaining());
                      writeableBuf.put(buffer);
                      writeableBuf.flip();
                      out.add(writeableBuf,0,false);
                      forwarder.writeBytesToChannel(out);
                      buffer.clear();
                      state=ParseState.FORWARD;
                    }
                  }
                  outputThrottle = config.getResponseThrottle(host,currentReq.getClientPort(),currentReq.getUrlPath());
                  currentReq.getAllHeaderReferences(true);
                }
              }
              else // a blank line means the end of the header section!!!
              {
                if(state == ParseState.CHUNKED_TRAILER_EOLN)
                {
                  currentReq.finishRequest();
                  state=ParseState.DONE;
                }
                else
                if("chunked".equalsIgnoreCase(currentReq.getHeader(HTTPHeader.TRANSFER_ENCODING.lowerCaseName())))
                {
                  state=ParseState.CHUNKED_HEADER_INLINE;
                  buffer = currentReq.setToReceiveContentChunkedBody(0); // prepare for chunk length/headers
                  buffer.flip();
                  lastEOLIndex=0;
                }
                else
                {
                  //the headers will tell you what to do next "BODY" is too vague
                  final String contentLengthStr=currentReq.getHeader(HTTPHeader.CONTENT_LENGTH.lowerCaseName());
                  if(contentLengthStr!=null)
                  {
                    try
                    {
                      // moment of truth, do we have a body forthcoming?
                      final int contentLength = Integer.parseInt(contentLengthStr);
                      if ((contentLength < 0) || (contentLength > config.getRequestMaxBodyBytes())) // illegal request
                      {
                        throw HTTPException.standardException(HTTPStatus.S413_REQUEST_ENTITY_TOO_LARGE);
                      }
                      else
                      if(contentLength == 0) // no content means we are done .. finish the request
                      {
                        currentReq.setToReceiveContentBody(contentLength);
                        currentReq.finishRequest();
                        state=ParseState.DONE;
                      }
                      else // a positive content length means we should prepare to receive the body
                      {
                        currentReq.setToReceiveContentBody(contentLength);
                        state=ParseState.BODY;
                        // the line buffer might have contained the entire body, so check for that state and finish
                        // if necessary
                        if(currentReq.getBuffer().position() >= currentReq.getBuffer().capacity())
                        {
                          currentReq.finishRequest();
                          state=ParseState.DONE;
                        }
                      }
                    }
                    catch(final NumberFormatException ne)
                    {
                      throw HTTPException.standardException(HTTPStatus.S411_LENGTH_REQUIRED);
                    }
                  }
                  else
                  {
                    // we have an http exception for this, but why be a jerk
                    currentReq.finishRequest();
                    state=ParseState.DONE;
                  }
                }
              }
              // continue
              if((state != ParseState.DONE)
              &&(currentReq.isExpect("100-continue")))
              {
                if(currentReq.getHttpVer()>1.0)
                  writeBytesToChannel(new CWDataBuffers(ByteBuffer.wrap(HTTPIOHandler.CONT_RESPONSE),0,false));
              }
            }
            else // an error! Ignore this line!
            {
              lastEOLIndex=buffer.position();
View Full Code Here

Examples of com.planet_ink.coffee_web.util.CWDataBuffers

          headers.put(HTTPHeader.CONTENT_TYPE, mimeType.getType());
          final Class<? extends HTTPOutputConverter> converterClass=config.getConverters().findConverter(mimeType);
          if(converterClass != null)
          {
            final HTTPOutputConverter converter=converterClass.newInstance();
            finalBody=new CWDataBuffers(converter.convertOutput(config, request, errorFile, status, fileBytes.flushToBuffer()),0,true);
          }
          else
            finalBody=fileBytes;
        }
        else
          finalBody=fileBytes;
      }
      catch(final Exception e)
      {
        if(fileBytes!=null)
          fileBytes.close();
      }
    }
    if(finalBody==null)
    {
      finalBody=new CWDataBuffers(body.getBytes(), 0, true);
    }
    for(final HTTPHeader header : headers.keySet())
    {
      str.append(header.makeLine(headers.get(header)));
    }
View Full Code Here

Examples of com.planet_ink.coffee_web.util.CWDataBuffers

      fileName = pageFile.getAbsolutePath();
      final FileCacheEntry entry = getFileData(fileName, null);
      if((entry != null) && (entry.buf[type.ordinal()]!=null))
      {
        uncompressedData.close(); // we aren't going to need this.
        return new CWDataBuffers(entry.buf[type.ordinal()],entry.modified, true);
      }
    }
    else
      fileName=Integer.toString(uncompressedData.hashCode());
    final boolean cacheActive=(cacheMaxBytes > 0);
    synchronized(fileName.intern())
    {
      final FileCacheEntry entry = getFileData(fileName, null);
      if((entry != null) && (entry.buf[type.ordinal()]!=null))
      {
        uncompressedData.close(); // we aren't going to need this.
        return new CWDataBuffers(entry.buf[type.ordinal()],entry.modified, true);
      }
      DeflaterOutputStream compressor=null;
      final ByteArrayOutputStream bufStream=new ByteArrayOutputStream();
      try
      {
        switch(type)
        {
        case GZIP:
          compressor=new GZIPOutputStream(bufStream);
          break;
        case DEFLATE:
          compressor=new DeflaterOutputStream(bufStream);
          break;
        default: return null;
        }
        while(uncompressedData.hasNext())
        {
          final ByteBuffer buf=uncompressedData.next();
          compressor.write(buf.array(),buf.position(),buf.remaining());
          buf.position(buf.limit());
        }
        compressor.flush();
        compressor.finish();
      }
      catch(final IOException ioe)
      {
        uncompressedData.close();
        logger.throwing("", "", ioe);
        return null;
      }
      finally
      {
        if(compressor!=null)
          try
          { compressor.close();} catch(final Exception e){}
      }
      final byte[] compressedBytes = bufStream.toByteArray();
      if((cacheActive) && (entry != null) && (entry.buf[type.ordinal()] == null))
      {
        entry.buf[type.ordinal()] = compressedBytes;
        totalBytes.addAndGet(entry.bufsSize.addAndGet(compressedBytes.length));
      }
      final long lastModified=uncompressedData.getLastModified().getTime();
      uncompressedData.close();
      return new CWDataBuffers(compressedBytes, lastModified, true);
    }
  }
View Full Code Here

Examples of com.planet_ink.coffee_web.util.CWDataBuffers

  public DataBuffers getFileData(final File pageFile, final String[] eTag) throws HTTPException
  {
    final String fileName = pageFile.getAbsolutePath();
    FileCacheEntry entry = getFileData(fileName, eTag);
    if(entry != null)
      return new CWDataBuffers(entry.buf[CompressionType.NONE.ordinal()], entry.modified, true);
   
    synchronized(fileName.intern())
    {
      entry = getFileData(fileName, eTag);
      if(entry != null)
        return new CWDataBuffers(entry.buf[CompressionType.NONE.ordinal()], entry.modified, true);
      if(!fileManager.allowedToReadData(pageFile))
      {
        if(cacheActive)
        {
          synchronized(cache)
          {
          cache.put(fileName, new FileCacheEntry(null,0));
          }
        }
        throw HTTPException.standardException(HTTPStatus.S404_NOT_FOUND);
      }
      final boolean cacheActiveThisFile=cacheActive;
      try
      {
        if((cacheMaxFileBytes==0)||(pageFile.length()<=cacheMaxFileBytes)||(!fileManager.supportsRandomAccess(pageFile)))
        {
          final byte[] fileBuf = fileManager.readFile(pageFile);
          if(cacheActiveThisFile)
          {
            entry = new FileCacheEntry(fileBuf, pageFile.lastModified());
            possibleAddEntryToCache(fileName, entry, eTag);
          }
          return new CWDataBuffers(fileBuf, pageFile.lastModified(), true);
        }
        else
        {
          return new CWDataBuffers(fileManager.getRandomAccessFile(pageFile), pageFile.lastModified(), true);
        }
      }
      catch(final FileNotFoundException e)
      {
        logger.throwing("", "", e);
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.