Package tkuri.jxy.server

Source Code of tkuri.jxy.server.TaskUtil

package tkuri.jxy.server;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Set;

import tkuri.jxy.Const;
import tkuri.jxy.Util;
import tkuri.jxy.arch.GeneralHeaderInfo;
import tkuri.jxy.arch.HeaderList;
import tkuri.jxy.arch.HeaderPair;
import tkuri.uty.Bs;
import tkuri.uty.Buf;

public class TaskUtil {


  static final Bs SP = Bs.valueOf(" ");
  static final Bs HTTPVER = Bs.valueOf("HTTP/1.1");
  static final Bs CRLF = Bs.valueOf("\r\n");
  static final Bs COLON_SP = Bs.valueOf(": ");


  /*
   *
   */
  static ByteBuffer makeRequestHeaderBuffer(ClientRequest aReq) {

    Buf buf = new Buf();

    buf.appendAll(aReq.method, SP, aReq.path, SP, HTTPVER, CRLF);

    buildHeaderBuffer(buf, aReq.headerList, aReq.headerInfo);

    buf.append(CRLF);

    return bufToByteBuf(buf);
  }


  /*
   *
   */
  static ByteBuffer makeResponseHeaderBuffer(OriginResponse aRes, boolean aConnClose) {

    Buf buf = new Buf();

    buf.appendAll(aRes.statusLine);

    buildHeaderBuffer(buf, aRes.headerList, aRes.headerInfo);
    if (aConnClose) {
      buf.appendAll(Const.S_CONNECTION, COLON_SP, Const.S_CLOSE, CRLF);
    }

    buf.append(CRLF);

    return bufToByteBuf(buf);
  }


  static void buildHeaderBuffer(Buf oBuf, HeaderList aList, GeneralHeaderInfo aInfo) {

    Set<Bs> hopByHop = aInfo.hopByHop;
    for (HeaderPair hp: aList) {
      if (hopByHop.contains(hp.name.toLower())) {
        // ignore hop-by-hop
      } else {
        oBuf.appendAll(hp.name, COLON_SP, hp.value, CRLF);
      }
    }
  }

  static ByteBuffer bufToByteBuf(Buf aBuf) {

    ByteBuffer buf = ByteBuffer.allocate(aBuf.length());
    try {
      aBuf.getInputStream().read(buf.array());
    } catch (Exception x) {
      // ignore
    }

    // 書き込むためのバッファ。書き込み準備ができているはず
    assert buf.remaining() == buf.limit();

    return buf;
  }


  static boolean finishConnection(SocketChannel aSock) {

    try {
      return aSock.finishConnect();
    } catch (Exception x) {
      // TODO error?
      //Util.say(x);
      return false;
    }
  }
}
TOP

Related Classes of tkuri.jxy.server.TaskUtil

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.