Пример #1
0
  @Override
  public void pause() {
    if (context.needToCheckClientState()) {
      checkClientState(
          State.STARTED,
          "Kaa client is not started (" + clientState.toString().toLowerCase() + " now)");
    }
    setClientState(State.PAUSED);

    getLifeCycleExecutor()
        .submit(
            new Runnable() {
              @Override
              public void run() {
                try {
                  kaaClientState.persist();
                  channelManager.pause();
                  if (stateListener != null) {
                    stateListener.onPaused();
                  }
                } catch (Exception e) {
                  LOG.error("Pause failed", e);
                  if (stateListener != null) {
                    stateListener.onPauseFailure(new KaaException(e));
                  }
                }
              }
            });
  }
Пример #2
0
  // ===========================================================
  // Methods
  // ===========================================================
  public void changeState(final State pState) {
    if (pState == this.mState) {
      return;
    }

    final IEntity pNewFace = this.mEntities[pState.getEntityIndex()];
    final IEntity pOldFace = this.mEntities[this.mState.getEntityIndex()];
    this.mState = pState;

    detachChild(pOldFace);
    detachChild(pNewFace);
    if (pNewFace == null) {
      attachDefaultFace();
      Debug.w(
          this.getClass().getSimpleName()
              + " changed its "
              + State.class.getSimpleName()
              + " to "
              + pState.toString()
              + ", which doesn't have an "
              + IEntity.class.getSimpleName()
              + " supplied. Applying default "
              + IEntity.class.getSimpleName()
              + ".");
    } else {
      attachChild(pNewFace);
    }
    sortChildren(false);
  }
 @JsonIgnore
 public void setState(State state) {
   if (State.UNKNOWN == state) {
     throw new IllegalArgumentException("Cannot set state to an UNKNOWN value");
   }
   stateString = state.toString();
 }
Пример #4
0
  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();

    if (StringUtil.ensureStringExists(poBox)) {
      builder.append(poBox);
    }

    if (StringUtil.ensureStringExists(streetAddress)) {
      builder = StringUtil.ensureEndsWithSpace(builder);
      builder.append(streetAddress);
    }

    if (StringUtil.ensureStringExists(unit)) {
      builder = StringUtil.ensureEndsWithSpace(builder);
      builder.append(unit);
    }

    if (StringUtil.ensureStringExists(city)) {
      builder = StringUtil.ensureEndsWithCommaSpace(builder);
      builder.append(city);
    }

    if (state != null) {
      builder = StringUtil.ensureEndsWithCommaSpace(builder);
      builder.append(state.toString());
    }

    if (StringUtil.ensureStringExists(zip)) {
      builder = StringUtil.ensureEndsWithSpace(builder);
      builder.append(zip);
    }

    return builder.toString();
  }
  @Test
  public void shouldUseConstructorWithOneParamAndSetCorrectStateName() throws Exception {
    String stateName = "state";
    String expectedStateName = "State: state";
    state = new FinalState(stateName);

    assertEquals(expectedStateName, state.toString());
  }
Пример #6
0
 @Override
 public void start() {
   Log.e(TAG, "STARTING");
   mBreakout = false;
   ok = true;
   State currState = getState();
   Log.e(TAG, "CURRENT THREAD STATE = " + currState.toString());
   if ((currState == State.RUNNABLE || currState == State.NEW || currState == State.TERMINATED)
       && init()) super.start();
 }
Пример #7
0
 @Override
 public ContentValues toValues() {
   ContentValues values = new ContentValues();
   values.put(ID, id);
   values.put(STATE, state.toString());
   values.put(ATTEMPT, lastAttempt);
   values.put(SUCCESSFUL, lastSuccessful);
   values.put(DESCRIPTION, description);
   return values;
 }
 public void checkFill() throws IOException {
   State s = _state.get();
   switch (s) {
     case ISHUT:
     case ISHUTTING:
     case CLOSED:
       throw new IOException(s.toString());
     default:
       break;
   }
 }
Пример #9
0
 public String getState() {
   StringBuffer result = new StringBuffer();
   result.append(state_.toString());
   if (env_ != null) {
     // add the mode to the end of the state.
     for (int i = 0; i < names_.length; i++) {
       if (!env_.isDefined(names_[i])) result.append('O');
       else result.append('I'); // an input
     }
   }
   return result.toString();
 }
Пример #10
0
 /**
  * Provides a string representation of the {@link ImsCallSession}. Primarily intended for use in
  * log statements.
  *
  * @return String representation of session.
  */
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append("[ImsCallSession objId:");
   sb.append(System.identityHashCode(this));
   sb.append(" state:");
   sb.append(State.toString(getState()));
   sb.append(" callId:");
   sb.append(getCallId());
   sb.append("]");
   return sb.toString();
 }
Пример #11
0
 public static synchronized State release() {
   long now = System.currentTimeMillis();
   if (marks.empty())
     throw new RuntimeException(
         "TimeStiatistics: Called release() without a matching call to mark()");
   State m = marks.pop();
   m.garbageCounterDelta = garbageCounter.get() - m.garbageCounterMark;
   m.end = now;
   MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
   m.memoryUsedEnd = memoryUsage.getUsed();
   System.out.println(m.toString());
   return m;
 }
Пример #12
0
  public boolean isGoal(State p) {
    boolean goal = true;

    String state = p.toString();

    for (int x = 0; x < state.length(); x++) {

      if (state.charAt(x) != 'X') {
        goal = false;
        break;
      }
    }

    return goal;
  }
Пример #13
0
 public Element writeXML(Document document) {
   final Element root = document.createElement("pumping");
   DomUtil.addElement(root, "url", url.toString());
   DomUtil.addElement(root, "realUrl", realUrl != null ? realUrl.toString() : null);
   DomUtil.addElement(root, "length", String.valueOf(length));
   DomUtil.addElement(root, "lastModif", String.valueOf(lastModif.getTime()));
   DomUtil.addElement(root, "acceptBytes", String.valueOf(acceptBytes));
   DomUtil.addElement(root, "state", state.toString());
   DomUtil.addElement(root, "file", file != null ? file.getAbsolutePath() : null);
   DomUtil.addElement(root, "folder", folder.getAbsolutePath());
   for (SectionImpl section : sections) {
     DomUtil.addChild(root, section);
   }
   return root;
 }
Пример #14
0
  public String getMessage(Context context) {
    StringBuilder builder = new StringBuilder();
    builder
        .append("Connection: ")
        .append(state.toString().replace('_', ' '))
        .append(".\nLast Attempt: ")
        .append(getLastAttemptWithTimeZone(context))
        .append(".\nLast Successful: ")
        .append(getLastSuccessfulWithTimeZone(context))
        .append('.');
    if (!isEmpty(description)) {
      builder.append("\n\nLast Error: \n").append(description);
    }

    return builder.toString();
  }
Пример #15
0
  public static void main(String argv[]) {

    // argv[0]: input file containing source code using tokens defined above
    // argv[1]: output file to display a list of the tokens

    setLex(argv[0], argv[1]);

    int i;

    while (a != -1) // while "a" is not end-of-stream
    {
      i = driver(); // extract the next token
      if (i == 1) displayln(t + "   : " + state.toString());
      else if (i == 0) displayln(t + "  -- Invalid Token");
    }

    closeIO();
  }
Пример #16
0
  /** Core of engine. Finite State Machine */
  StateEnd run() {
    String action;

    do {
      if (mustStop) {
        nextState = manager.END_FALSE;
        break;
      }
      action = nextState.toString();

      nextState.doJob(this);
      manager.spy(action, this);

    } while (!(nextState instanceof StateEnd));
    nextState.doJob(this);

    return (StateEnd) (nextState);
  }
Пример #17
0
  @Override
  public void timerExpired(Object callbackData) {
    State newState = state;
    switch (state) {
      case STATE_IDLE:
        localCarPositionIndicator.set(floor);
        mCarPositionIndicator.set(floor);
        newState = State.STATE_IDLE;

        for (int i = 0; i < mAtFloors.length; i++) {
          // #transition T10.1
          if (mAtFloors[i].getValue()) {
            floor = AtFloorFloors[i];
            newState = State.STATE_CAR_AT_FLOOR;
            break;
          }
        }
        break;
      case STATE_CAR_AT_FLOOR:
        localCarPositionIndicator.set(floor);
        mCarPositionIndicator.set(floor);
        // #transition T10.2
        newState = State.STATE_IDLE;
        break;

      default:
        throw new RuntimeException("State " + state + " was not recognized.");
    }
    // log the results of this iteration
    if (state == newState) {
      log("remains in state: ", state);
    } else {
      log("Transition:", state, "->", newState);
    }
    // update the state variable
    state = newState;
    // report the current state
    setState(STATE_KEY, newState.toString());

    // schedule the next iteration of the controller
    timer.start(period);
  }
  @Override
  public <State extends AbsFSMState<State, TxnEType>, TxnEType extends IDistEventType>
      String nodeToString(int nodeId, State node, boolean isInitial, boolean isTerminal) {
    // String attributes = "label=\"" + quote(Integer.toString(nodeId))
    String attributes = "label=\"" + quote(node.toString()) + "\",shape=circle";
    String extra = "";

    if (isInitial) {
      String startId = "start_" + startStateCount;
      extra = "  " + startId + " [label=\"start\",shape=plaintext];\n";
      extra += "  " + startId + "->" + nodeId + ";\n";
      startStateCount++;
    }

    if (isTerminal) {
      attributes += ",shape=doublecircle";
    }

    return "  " + nodeId + " [" + attributes + "];\n" + extra;
  }
Пример #19
0
 public String getStateTest() {
   return stt.toString();
 }
Пример #20
0
 public String getResultTestCase() {
   return "[" + stt.toString() + "]" + " : (" + Double.toString(time) + "seg) ;";
 }
Пример #21
0
 /**
  * Returns a formatted string containing the State data.
  *
  * @return a formatted string containing the State data.
  */
 @Override
 public String toString() {
   return value.toString();
 }
Пример #22
0
 @Override
 public String toString() {
   return state.toString();
 }
Пример #23
0
 public String toString() {
   return String.format("%02d %08d %s %s", session, id, state.toString(), info);
 }
Пример #24
0
 public String getStateAsString() {
   return state.toString();
 }
  @Test
  public void shouldCheckToStringAndReturnCorrectValue() throws Exception {
    String expectedStateToString = "State: testState";

    assertEquals(expectedStateToString, state.toString());
  }
 public String toString() {
   if (state != null) return state.toString();
   else return contextToString();
 }
Пример #27
0
 @Override
 public String toString() {
   return userState.toString();
 }
Пример #28
0
  @Override
  public void timerExpired(Object callbackData) {
    State newState = state;
    curr_pos = mCarLevelPosition.getPosition();
    // We add 100 in order to make sure the floor is being updated correctly.
    curr_f = (curr_pos + 100) / 5000 + 1;
    if (curr_f != lastFloor) {
      lastFloor = curr_f;
      // System.out.println("resetting overweight");
      overweight = false;
      lastClosedAt = 0;
    }
    // System.out.println("curr_pos is " + curr_pos + " and curr_f is " + curr_f);
    if (Elevator.hasLanding(curr_f, Hallway.FRONT)) {
      if (Elevator.hasLanding(curr_f, Hallway.BACK)) curr_h = Hallway.BOTH;
      else curr_h = Hallway.FRONT;
    } else curr_h = Hallway.BACK;
    // State Machine
    switch (state) {
        // #state State 2: Doors Open
      case STATE_DOORSOPEN:
        // State actions for 'DOORSOPEN'
        waitCounter = waitTime;
        // If mDesiredDirection.d is STOP, we continue to look for hall and car halls.
        // mDesiredDirection.d is also set at curr_d
        // System.out.println("1current desired direction:" + mDesiredFloor.getDirection());
        if (mDesiredFloor.getDirection() == Direction.STOP) {
          /*
           * NOTE: When nextTarget is called, curr_d is set to the desired direction,
           * direction is set to the NEXT desired direction and floor is set to
           * the NEXT target floor. BUT we only want to change the directional
           * portion of mDesiredFloor, hence we use hallway, curr_f, and curr_d
           * to set the next Desired Floor.
           *
           * If no additional floors are found. Nothing changes so it is safe to
           * set mDesired dwell to curr_f, hallway, and curr_d still.
           */
          nextTarget(mDriveSpeed.getSpeed(), mCarLevelPosition.getPosition(), curr_d);
          // Now set the next target.
          // System.out.println("open floor is " + floor + " next direction is " + direction + "
          // current direction is " + curr_d + " hallway " + hallway);
          // System.out.println("changing direction to " + curr_d);
          mDesiredFloor.set(curr_f, curr_d, hallway);
          // System.out.println("2current desired direction:" + mDesiredFloor.getDirection());
        }
        // If the car is overweight, dont answer hall calls at this floor until later!
        if (mCarWeight.getValue() > Elevator.MaxCarCapacity) {
          overweight = true;
        }

        if (hallway == Hallway.BOTH) {
          // If either side of doors open and we're not at the floor, emergency!
          // #transition 11.T.4
          if ((!mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.FRONT, Side.LEFT)]
                      .getValue()
                  || !mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.BACK, Side.LEFT)]
                      .getValue())
              && !mAtFloor[ReplicationComputer.computeReplicationId(curr_f, Hallway.FRONT)]
                  .getValue()) {
            newState = State.STATE_EMERGENCY;
          }
          // #transition 11.T.3 when doors closed.
          else if ((mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.FRONT, Side.LEFT)]
                  .getValue()
              && mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.BACK, Side.LEFT)]
                  .getValue())) lastClosedAt = curr_f;
          newState = State.STATE_DOORSCLOSED;
        }
        // if it is not at ANY floor and ANY doors are open, jump to emergency state
        // #transition 11.T.4
        else if ((!mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.FRONT, Side.LEFT)]
                    .getValue()
                || !mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.BACK, Side.LEFT)]
                    .getValue())
            && !mAtFloor[ReplicationComputer.computeReplicationId(curr_f, hallway)].getValue()) {
          newState = State.STATE_EMERGENCY;
        }
        // if no issues, move to the next state when doors closed
        // #transition 11.T.3
        else if ((mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.FRONT, Side.LEFT)]
                .getValue()
            && mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.BACK, Side.LEFT)]
                .getValue())) {
          lastClosedAt = curr_f;
          newState = State.STATE_DOORSCLOSED;
        } else newState = state;
        break;

        // State actions for 'Doors Closed'
        // #state State 1: Doors Closed
      case STATE_DOORSCLOSED:
        // If waitForCall flag set, wait for 2 seconds for passenger to make car call.
        if (waitForCall) {
          // System.out.println("waiting");
          // while counter is greater than zero, keep subtracting;
          if (waitCounter.isPositive()) waitCounter = SimTime.subtract(waitCounter, period);
          else {
            // Reset waitCounter for next time and set waitForCall false
            waitForCall = false;
          }
          break;
        } else {
          // System.out.println("not waiting");
          // Check both sides for closed doors if that is the case.
          if (hallway == Hallway.BOTH || curr_h == Hallway.BOTH) {
            // If we're at the next target floor AND doors are opening, jump to DOORSOPEN
            // #transition 11.T.1
            if (mAtFloor[ReplicationComputer.computeReplicationId(floor, Hallway.FRONT)].getValue()
                && ((!mDoorClosed[
                        ReplicationComputer.computeReplicationId(Hallway.FRONT, Side.LEFT)]
                        .getValue()
                    || !mDoorClosed[
                        ReplicationComputer.computeReplicationId(Hallway.BACK, Side.LEFT)]
                        .getValue()))) {
              newState = State.STATE_DOORSOPEN;
              // If car is answering a hall call, wait for carcall after doors close.
              if (mDesiredFloor.getDirection() != Direction.STOP) waitForCall = true;
              // curr_d updated within nextTarget() but also updated when we open doors.
              curr_d = direction;
              // promised_d = direction;
            }
            // If either side of doors open and we're not at any floor, emergency!
            // #transition 11.T.2
            else if ((!mDoorClosed[
                        ReplicationComputer.computeReplicationId(Hallway.FRONT, Side.LEFT)]
                        .getValue()
                    || !mDoorClosed[
                        ReplicationComputer.computeReplicationId(Hallway.BACK, Side.LEFT)]
                        .getValue())
                && !(mAtFloor[ReplicationComputer.computeReplicationId(curr_f, Hallway.FRONT)]
                        .getValue()
                    || mAtFloor[ReplicationComputer.computeReplicationId(curr_f, Hallway.BACK)]
                        .getValue())
                && !mAtFloor[ReplicationComputer.computeReplicationId(floor, Hallway.FRONT)]
                    .getValue()) {
              newState = State.STATE_EMERGENCY;
            } else newState = state;
          }
          // If we're at the next target floor AND doors are opening, jump to DOORSOPEN
          // #transition 11.T.1
          else if (mAtFloor[ReplicationComputer.computeReplicationId(floor, hallway)].getValue()
              && ((!mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.FRONT, Side.LEFT)]
                      .getValue()
                  || !mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.BACK, Side.LEFT)]
                      .getValue()))) {
            newState = State.STATE_DOORSOPEN;
            curr_d = direction;
            // promised_d = direction;
            if (mDesiredFloor.getDirection() != Direction.STOP) waitForCall = true;
          }

          // If either side of doors open and we're not at any floor, emergency!
          // #transition 11.T.2
          else if ((!mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.FRONT, Side.LEFT)]
                      .getValue()
                  || !mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.BACK, Side.LEFT)]
                      .getValue())
              && !mAtFloor[ReplicationComputer.computeReplicationId(curr_f, curr_h)].getValue()
              && !mAtFloor[ReplicationComputer.computeReplicationId(floor, hallway)].getValue()) {
            newState = State.STATE_EMERGENCY;
          } else newState = state;
        }
        // Only change nextTarget if we're not transitioning states
        if (newState == state) {
          // Set next Direction and  next target Floor
          nextTarget(mDriveSpeed.getSpeed(), mCarLevelPosition.getPosition(), curr_d);

          /*This code is invalid. Must check if landing has call as well.
           * Decide which hallway is valid. If front and back, then both, else either front or back.*/
          hallIndexF = ReplicationComputer.computeReplicationId(floor, Hallway.FRONT, direction);
          carIndexF = ReplicationComputer.computeReplicationId(floor, Hallway.FRONT);
          hallIndexB = ReplicationComputer.computeReplicationId(floor, Hallway.BACK, direction);
          carIndexB = ReplicationComputer.computeReplicationId(floor, Hallway.BACK);
          if (Elevator.hasLanding(floor, Hallway.FRONT)) {
            if (Elevator.hasLanding(floor, Hallway.BACK)) {
              // Check both landings for valid calls. If not both, then select one.
              if ((mHallCall[hallIndexF].getValue() || mCarCall[carIndexF].getValue())
                  && (mHallCall[hallIndexB].getValue() || mCarCall[carIndexB].getValue())) {
                hallway = Hallway.BOTH;
              } else if (mHallCall[hallIndexF].getValue() || mCarCall[carIndexF].getValue()) {
                hallway = Hallway.FRONT;
              } else if (mHallCall[hallIndexB].getValue() || mCarCall[carIndexB].getValue()) {
                hallway = Hallway.BACK;
              }
            } else {
              if (mHallCall[hallIndexF].getValue() || mCarCall[carIndexF].getValue()) {
                hallway = Hallway.FRONT;
              }
            }
          } else {
            if (mHallCall[hallIndexB].getValue() || mCarCall[carIndexB].getValue()) {
              hallway = Hallway.BACK;
            }
          }
          /*if(promised_d != Direction.STOP && promised_d != curr_d ){
          	mDesiredFloor.setDirection(curr_d);
          }*/
          // log("floor is ", floor, " next direction is ", direction, " current direction is",
          // curr_d);
          // System.out.println("Closed floor is " + floor + " next direction is " + direction + "
          // current direction is " + curr_d + " hallway " + hallway);
          // Now set the next target.
          // else{
          mDesiredFloor.set(floor, direction, hallway);
          // }
        }
        break;

        // State actions for 'EMERGENCY'
        // #state State 3: Emergency
      case STATE_EMERGENCY:
        // System.out.println("emergency at supposedly" + curr_f + " but at postion " +
        // mCarLevelPosition.getPosition() +
        //		" with desiredfloor " +
        // mDesiredFloor.getFloor()+mDesiredFloor.getHallway()+mDesiredFloor.getDirection());
        floor = 1;
        hallway = Hallway.BOTH;
        direction = Direction.STOP;
        // Set the desired floor back down to the lobby!
        mDesiredFloor.set(floor, hallway, direction);

        // Once the doors have opened at the lobby, we can return to normal operation.
        // #transition 11.T.5
        if (!mDoorClosed[ReplicationComputer.computeReplicationId(Hallway.FRONT, Side.LEFT)]
                .getValue()
            && mAtFloor[ReplicationComputer.computeReplicationId(1, Hallway.FRONT)].getValue())
          newState = State.STATE_DOORSOPEN;
        else newState = state;
        break;

      default:
        throw new RuntimeException("State " + state + " was not recognized.");
    }

    /*log the results of this iteration
    if (state == newState) {
    	log("remains in state: ",state);
    } else {
    	log("Transition:",state,"->",newState);
    }
     */
    // update the state variable
    state = newState;

    // report the current state
    setState(STATE_KEY, newState.toString());

    // schedule the next iteration of the controller
    // you must do this at the end of the timer callback in order to restart
    // the timer
    timer.start(period);
  }
Пример #29
0
  /* Parse a request or response line
   */
  private boolean parseLine(ByteBuffer buffer) {
    boolean handle = false;

    // Process headers
    while (_state.ordinal() < State.HEADER.ordinal() && buffer.hasRemaining() && !handle) {
      // process each character
      byte ch = next(buffer);
      if (ch == 0) break;

      if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) {
        if (_state == State.URI) {
          LOG.warn("URI is too large >" + _maxHeaderBytes);
          throw new BadMessage(HttpStatus.REQUEST_URI_TOO_LONG_414);
        } else {
          if (_requestHandler != null) LOG.warn("request is too large >" + _maxHeaderBytes);
          else LOG.warn("response is too large >" + _maxHeaderBytes);
          throw new BadMessage(HttpStatus.REQUEST_ENTITY_TOO_LARGE_413);
        }
      }

      switch (_state) {
        case METHOD:
          if (ch == HttpTokens.SPACE) {
            _length = _string.length();
            _methodString = takeString();
            HttpMethod method = HttpMethod.CACHE.get(_methodString);
            if (method != null && !_strict) _methodString = method.asString();
            setState(State.SPACE1);
          } else if (ch < HttpTokens.SPACE)
            throw new BadMessage(ch < 0 ? "Illegal character" : "No URI");
          else _string.append((char) ch);
          break;

        case RESPONSE_VERSION:
          if (ch == HttpTokens.SPACE) {
            _length = _string.length();
            String version = takeString();
            _version = HttpVersion.CACHE.get(version);
            if (_version == null)
              throw new BadMessage(HttpStatus.BAD_REQUEST_400, "Unknown Version");
            setState(State.SPACE1);
          } else if (ch < HttpTokens.SPACE)
            throw new BadMessage(ch < 0 ? "Illegal character" : "No Status");
          else _string.append((char) ch);
          break;

        case SPACE1:
          if (ch > HttpTokens.SPACE || ch < 0) {
            if (_responseHandler != null) {
              setState(State.STATUS);
              setResponseStatus(ch - '0');
            } else {
              _uri.clear();
              setState(State.URI);
              // quick scan for space or EoBuffer
              if (buffer.hasArray()) {
                byte[] array = buffer.array();
                int p = buffer.arrayOffset() + buffer.position();
                int l = buffer.arrayOffset() + buffer.limit();
                int i = p;
                while (i < l && array[i] > HttpTokens.SPACE) i++;

                int len = i - p;
                _headerBytes += len;

                if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) {
                  LOG.warn("URI is too large >" + _maxHeaderBytes);
                  throw new BadMessage(HttpStatus.REQUEST_URI_TOO_LONG_414);
                }
                if (_uri.remaining() <= len) {
                  ByteBuffer uri = ByteBuffer.allocate(_uri.capacity() + 2 * len);
                  _uri.flip();
                  uri.put(_uri);
                  _uri = uri;
                }
                _uri.put(array, p - 1, len + 1);
                buffer.position(i - buffer.arrayOffset());
              } else _uri.put(ch);
            }
          } else if (ch < HttpTokens.SPACE) {
            throw new BadMessage(
                HttpStatus.BAD_REQUEST_400, _requestHandler != null ? "No URI" : "No Status");
          }
          break;

        case STATUS:
          if (ch == HttpTokens.SPACE) {
            setState(State.SPACE2);
          } else if (ch >= '0' && ch <= '9') {
            _responseStatus = _responseStatus * 10 + (ch - '0');
          } else if (ch < HttpTokens.SPACE && ch >= 0) {
            handle = _responseHandler.startResponse(_version, _responseStatus, null) || handle;
            setState(State.HEADER);
          } else {
            throw new BadMessage();
          }
          break;

        case URI:
          if (ch == HttpTokens.SPACE) {
            setState(State.SPACE2);
          } else if (ch < HttpTokens.SPACE && ch >= 0) {
            // HTTP/0.9
            _uri.flip();
            handle = _requestHandler.startRequest(_method, _methodString, _uri, null) || handle;
            setState(State.END);
            BufferUtil.clear(buffer);
            handle = _handler.headerComplete() || handle;
            handle = _handler.messageComplete() || handle;
          } else {
            if (!_uri.hasRemaining()) {
              ByteBuffer uri = ByteBuffer.allocate(_uri.capacity() * 2);
              _uri.flip();
              uri.put(_uri);
              _uri = uri;
            }
            _uri.put(ch);
          }
          break;

        case SPACE2:
          if (ch > HttpTokens.SPACE) {
            _string.setLength(0);
            _string.append((char) ch);
            if (_responseHandler != null) {
              _length = 1;
              setState(State.REASON);
            } else {
              setState(State.REQUEST_VERSION);

              // try quick look ahead for HTTP Version
              HttpVersion version;
              if (buffer.position() > 0 && buffer.hasArray())
                version =
                    HttpVersion.lookAheadGet(
                        buffer.array(),
                        buffer.arrayOffset() + buffer.position() - 1,
                        buffer.arrayOffset() + buffer.limit());
              else version = HttpVersion.CACHE.getBest(buffer, 0, buffer.remaining());
              if (version != null) {
                int pos = buffer.position() + version.asString().length() - 1;
                if (pos < buffer.limit()) {
                  byte n = buffer.get(pos);
                  if (n == HttpTokens.CARRIAGE_RETURN) {
                    _cr = true;
                    _version = version;
                    _string.setLength(0);
                    buffer.position(pos + 1);
                  } else if (n == HttpTokens.LINE_FEED) {
                    _version = version;
                    _string.setLength(0);
                    buffer.position(pos);
                  }
                }
              }
            }
          } else if (ch == HttpTokens.LINE_FEED) {
            if (_responseHandler != null) {
              handle = _responseHandler.startResponse(_version, _responseStatus, null) || handle;
              setState(State.HEADER);
            } else {
              // HTTP/0.9
              _uri.flip();
              handle = _requestHandler.startRequest(_method, _methodString, _uri, null) || handle;
              setState(State.END);
              BufferUtil.clear(buffer);
              handle = _handler.headerComplete() || handle;
              handle = _handler.messageComplete() || handle;
            }
          } else if (ch < 0) throw new BadMessage();
          break;

        case REQUEST_VERSION:
          if (ch == HttpTokens.LINE_FEED) {
            if (_version == null) {
              _length = _string.length();
              _version = HttpVersion.CACHE.get(takeString());
            }
            if (_version == null)
              throw new BadMessage(HttpStatus.BAD_REQUEST_400, "Unknown Version");

            // Should we try to cache header fields?
            if (_connectionFields == null
                && _version.getVersion() >= HttpVersion.HTTP_1_1.getVersion()) {
              int header_cache = _handler.getHeaderCacheSize();
              if (header_cache > 0) _connectionFields = new ArrayTernaryTrie<>(header_cache);
            }

            setState(State.HEADER);
            _uri.flip();
            handle = _requestHandler.startRequest(_method, _methodString, _uri, _version) || handle;
            continue;
          } else if (ch >= HttpTokens.SPACE) _string.append((char) ch);
          else throw new BadMessage();

          break;

        case REASON:
          if (ch == HttpTokens.LINE_FEED) {
            String reason = takeString();

            setState(State.HEADER);
            handle = _responseHandler.startResponse(_version, _responseStatus, reason) || handle;
            continue;
          } else if (ch >= HttpTokens.SPACE) {
            _string.append((char) ch);
            if (ch != ' ' && ch != '\t') _length = _string.length();
          } else throw new BadMessage();
          break;

        default:
          throw new IllegalStateException(_state.toString());
      }
    }

    return handle;
  }
Пример #30
0
  /*
   * Parse the message headers and return true if the handler has signaled for a return
   */
  protected boolean parseHeaders(ByteBuffer buffer) {
    boolean handle = false;

    // Process headers
    while (_state.ordinal() < State.CONTENT.ordinal() && buffer.hasRemaining() && !handle) {
      // process each character
      byte ch = next(buffer);
      if (ch == 0) break;

      if (_maxHeaderBytes > 0 && ++_headerBytes > _maxHeaderBytes) {
        LOG.warn("Header is too large >" + _maxHeaderBytes);
        throw new BadMessage(HttpStatus.REQUEST_ENTITY_TOO_LARGE_413);
      }

      switch (_state) {
        case HEADER:
          switch (ch) {
            case HttpTokens.COLON:
            case HttpTokens.SPACE:
            case HttpTokens.TAB:
              {
                // header value without name - continuation?
                if (_valueString == null) {
                  _string.setLength(0);
                  _length = 0;
                } else {
                  setString(_valueString);
                  _string.append(' ');
                  _length++;
                  _valueString = null;
                }
                setState(State.HEADER_VALUE);
                break;
              }

            default:
              {
                // handler last header if any.  Delayed to here just in case there was a
                // continuation line (above)
                if (_headerString != null || _valueString != null) {
                  // Handle known headers
                  if (_header != null && handleKnownHeaders(buffer)) {
                    _headerString = _valueString = null;
                    _header = null;
                    _value = null;
                    _field = null;
                    return true;
                  }
                  handle =
                      _handler.parsedHeader(
                              _field != null
                                  ? _field
                                  : new HttpField(_header, _headerString, _valueString))
                          || handle;
                }
                _headerString = _valueString = null;
                _header = null;
                _value = null;
                _field = null;

                // now handle the ch
                if (ch == HttpTokens.LINE_FEED) {
                  _contentPosition = 0;

                  // End of headers!

                  // Was there a required host header?
                  if (!_host && _version != HttpVersion.HTTP_1_0 && _requestHandler != null) {
                    throw new BadMessage(HttpStatus.BAD_REQUEST_400, "No Host");
                  }

                  // is it a response that cannot have a body?
                  if (_responseHandler != null
                      && // response
                      (_responseStatus == 304
                          || // not-modified response
                          _responseStatus == 204
                          || // no-content response
                          _responseStatus < 200)) // 1xx response
                  _endOfContent = EndOfContent.NO_CONTENT; // ignore any other headers set

                  // else if we don't know framing
                  else if (_endOfContent == EndOfContent.UNKNOWN_CONTENT) {
                    if (_responseStatus == 0 // request
                        || _responseStatus == 304 // not-modified response
                        || _responseStatus == 204 // no-content response
                        || _responseStatus < 200) // 1xx response
                    _endOfContent = EndOfContent.NO_CONTENT;
                    else _endOfContent = EndOfContent.EOF_CONTENT;
                  }

                  // How is the message ended?
                  switch (_endOfContent) {
                    case EOF_CONTENT:
                      setState(State.EOF_CONTENT);
                      handle = _handler.headerComplete() || handle;
                      break;

                    case CHUNKED_CONTENT:
                      setState(State.CHUNKED_CONTENT);
                      handle = _handler.headerComplete() || handle;
                      break;

                    case NO_CONTENT:
                      handle = _handler.headerComplete() || handle;
                      setState(State.END);
                      handle = _handler.messageComplete() || handle;
                      break;

                    default:
                      setState(State.CONTENT);
                      handle = _handler.headerComplete() || handle;
                      break;
                  }
                } else if (ch <= HttpTokens.SPACE) throw new BadMessage();
                else {
                  if (buffer.hasRemaining()) {
                    // Try a look ahead for the known header name and value.
                    HttpField field =
                        _connectionFields == null
                            ? null
                            : _connectionFields.getBest(buffer, -1, buffer.remaining());
                    if (field == null) field = CACHE.getBest(buffer, -1, buffer.remaining());

                    if (field != null) {
                      final String n;
                      final String v;

                      if (_strict) {
                        // Have to get the fields exactly from the buffer to match case
                        String fn = field.getName();
                        String fv = field.getValue();
                        n =
                            BufferUtil.toString(
                                buffer,
                                buffer.position() - 1,
                                fn.length(),
                                StandardCharsets.US_ASCII);
                        if (fv == null) v = null;
                        else {
                          v =
                              BufferUtil.toString(
                                  buffer,
                                  buffer.position() + fn.length() + 1,
                                  fv.length(),
                                  StandardCharsets.ISO_8859_1);
                          field = new HttpField(field.getHeader(), n, v);
                        }
                      } else {
                        n = field.getName();
                        v = field.getValue();
                      }

                      _header = field.getHeader();
                      _headerString = n;

                      if (v == null) {
                        // Header only
                        setState(State.HEADER_VALUE);
                        _string.setLength(0);
                        _length = 0;
                        buffer.position(buffer.position() + n.length() + 1);
                        break;
                      } else {
                        // Header and value
                        int pos = buffer.position() + n.length() + v.length() + 1;
                        byte b = buffer.get(pos);

                        if (b == HttpTokens.CARRIAGE_RETURN || b == HttpTokens.LINE_FEED) {
                          _field = field;
                          _valueString = v;
                          setState(State.HEADER_IN_VALUE);

                          if (b == HttpTokens.CARRIAGE_RETURN) {
                            _cr = true;
                            buffer.position(pos + 1);
                          } else buffer.position(pos);
                          break;
                        } else {
                          setState(State.HEADER_IN_VALUE);
                          setString(v);
                          buffer.position(pos);
                          break;
                        }
                      }
                    }
                  }

                  // New header
                  setState(State.HEADER_IN_NAME);
                  _string.setLength(0);
                  _string.append((char) ch);
                  _length = 1;
                }
              }
          }
          break;

        case HEADER_IN_NAME:
          if (ch == HttpTokens.COLON || ch == HttpTokens.LINE_FEED) {
            if (_headerString == null) {
              _headerString = takeString();
              _header = HttpHeader.CACHE.get(_headerString);
            }
            _length = -1;

            setState(ch == HttpTokens.LINE_FEED ? State.HEADER : State.HEADER_VALUE);
            break;
          }

          if (ch >= HttpTokens.SPACE || ch == HttpTokens.TAB) {
            if (_header != null) {
              setString(_header.asString());
              _header = null;
              _headerString = null;
            }

            _string.append((char) ch);
            if (ch > HttpTokens.SPACE) _length = _string.length();
            break;
          }

          throw new BadMessage("Illegal character");

        case HEADER_VALUE:
          if (ch > HttpTokens.SPACE || ch < 0) {
            _string.append((char) (0xff & ch));
            _length = _string.length();
            setState(State.HEADER_IN_VALUE);
            break;
          }

          if (ch == HttpTokens.SPACE || ch == HttpTokens.TAB) break;

          if (ch == HttpTokens.LINE_FEED) {
            if (_length > 0) {
              _value = null;
              _valueString =
                  (_valueString == null) ? takeString() : (_valueString + " " + takeString());
            }
            setState(State.HEADER);
            break;
          }

          throw new BadMessage("Illegal character");

        case HEADER_IN_VALUE:
          if (ch >= HttpTokens.SPACE || ch < 0) {
            if (_valueString != null) {
              setString(_valueString);
              _valueString = null;
              _field = null;
            }
            _string.append((char) (0xff & ch));
            if (ch > HttpTokens.SPACE || ch < 0) _length = _string.length();
            break;
          }

          if (ch == HttpTokens.LINE_FEED) {
            if (_length > 0) {
              _value = null;
              _valueString = takeString();
              _length = -1;
            }
            setState(State.HEADER);
            break;
          }
          throw new BadMessage("Illegal character");

        default:
          throw new IllegalStateException(_state.toString());
      }
    }

    return handle;
  }