make sure that state is stored in the session,
delete it from session - should be used only once

@param session
@param state
@throws Exception
329851
private StateData validateState(HttpSession session, String state) throws Exception {
        if (StringUtils.isNotEmpty(state)) {
            StateData stateDataInSession = removeStateFromSession(session, state);
            if (stateDataInSession != null) {
                return stateDataInSession;
            }
        }
        throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "could not validate state");
    }
630578
public void sessionDestroyed(final HttpSessionEvent event) {
		final HttpSession session = event.getSession();
		final String id = session.getId();
		SESSIONS.remove(id);
		counter--;
	}
1242987
public void onSessionDestruction(Request currentRequest, Session session)
	{
		HttpServletResponse response = (HttpServletResponse)httpResponse.get();
		storeSessionDataInCookie(SESSION_TOKEN_KEY, null, response);
		storeSessionDataInCookie(USER_ID_KEY, null, response);
	}
685556
public synchronized void checkState(State requiredState) throws IllegalStateException {
        if (requiredState != currentState) {
            throw new IllegalStateException(String.format(Locale.US,
                    "Expected state %s, but in state %s", requiredState, currentState));
        }
    }
1365811
private void clearState() {

        if (m_state != null) {
            ParamState state = m_state;
            m_state = null;
            state.undoChanges();
        }
    }
1275389
private <T extends OperationRequest, U extends OperationResponse, V> void submit(OperationAttempt<T, U, V> attempt) {
    if (state.getState() == Session.State.CLOSED || state.getState() == Session.State.EXPIRED) {
      attempt.fail(new ClosedSessionException("session closed"));
    } else {
      state.getLogger().trace("{} - Sending {}", state.getSessionId(), attempt.request);
      attempts.put(attempt.sequence, attempt);
      connection.<T, U>sendAndReceive(attempt.request).whenComplete(attempt);
      attempt.future.whenComplete((r, e) -> attempts.remove(attempt.sequence));
    }
  }
1330975
@Override
	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		log.error("Unhandled exception caught in session {}: {}", session,
				cause);
		this.sensorIoAdapter.exceptionCaught(session, cause);
	}
866989
private void saveSession(Session session) throws UnknownSessionException {
		if (session == null || session.getId() == null) {
			logger.error("session or session id is null");
			throw new UnknownSessionException("session or session id is null");
		}
		byte[] key;
		byte[] value;
		try {
			key = keySerializer.serialize(getRedisSessionKey(session.getId()));
			value = valueSerializer.serialize(session);
		} catch (SerializationException e) {
			logger.error("serialize session error. session id=" + session.getId());
			throw new UnknownSessionException(e);
		}
		if (expire == DEFAULT_EXPIRE) {
			this.redisManager.set(key, value, (int) (session.getTimeout() / MILLISECONDS_IN_A_SECOND));
			return;
		}
		if (expire != NO_EXPIRE && expire * MILLISECONDS_IN_A_SECOND < session.getTimeout()) {
			logger.warn("Redis session expire time: "
					+ (expire * MILLISECONDS_IN_A_SECOND)
					+ " is less than Session timeout: "
					+ session.getTimeout()
					+ " . It may cause some problems.");
		}
		this.redisManager.set(key, value, expire);
	}
1316796
public void run(ExpectState state) throws Exception {
        int flags = 0; // TCL.NAMESPACE_ONLY

        // TODO Inject expect object, so that expect wrapper can access it
        // clear previous expect_out
        //interp.unsetVar("expect_out", flags);

        String buffer = state.getBuffer();
        logger.trace("Setting var expect_out(buffer) to " + buffer);
        interp.setVar("expect_out", "buffer", buffer, flags);

        int group = 0;
        while(true) {
            String match = state.getMatch(group);
            String index = group + ",string";
            group++;
            if( match == null )
                break;
            logger.trace("Setting var expect_out(" + index +") to " + match);
            interp.setVar("expect_out", index , match, flags);
        }

        ExpectEmulation.setExpContinue(interp, false);

        if( tclCode != null && tclCode.toString().length() > 0 ) {
            logger.debug("Running a tcl bit of code: " + tclCode.toString());

            try {
                interp.eval(tclCode, 0);
            } catch(TclException e) {
                logger.warn("Exception: " + e);
                throw new Exception( interp.getResult().toString(), e);
            }
            if( ExpectEmulation.isExpContinue(interp) ) {
                logger.info("Asked to continue");
                state.exp_continue();
            }
        }
        //interp.unsetVar("expect_out", flags);

    }
1059646
public void destorySession(Session session) {
        session.attributes().clear();
        sessionMap.remove(session.id());

        Event event = new Event();
        event.attribute("session", session);

        eventManager.fireEvent(EventType.SESSION_DESTROY, event);
    }
132972
public synchronized void onCloseSession(ExtendedSession session)
   {
      this.cache.remove(key((ManageableRepository)session.getRepository(), session.getWorkspace().getName()));
   }
1356228
public void sessionEnd(SessionStatus finishState) {
    if (sessionStatusToMetrics.containsKey(finishState)) {
      sessionStatusToMetrics.get(finishState).inc();
    } else {
      throw new IllegalArgumentException("Invalid end state " + finishState);
    }
  }
1339889
public void setSessionState(JingleSessionState stateIs) {

        LOGGER.fine("Session state change: " + sessionState + "->" + stateIs);
        stateIs.enter();
        sessionState = stateIs;
    }
828997
private void register(RegisterAttempt attempt) {
    state.getLogger().debug("Registering session: attempt {}", attempt.attempt);

    RegisterRequest request = RegisterRequest.builder()
      .withClient(state.getClientId())
      .withTimeout(sessionTimeout.toMillis())
      .build();

    state.getLogger().trace("Sending {}", request);
    connection.reset().<RegisterRequest, RegisterResponse>sendAndReceive(request).whenComplete((response, error) -> {
      if (error == null) {
        state.getLogger().trace("Received {}", response);
        if (response.status() == Response.Status.OK) {
          interval = Duration.ofMillis(response.timeout()).dividedBy(2);
          connection.reset(response.leader(), response.members());
          state.setSessionId(response.session())
            .setState(Session.State.OPEN);
          state.getLogger().info("Registered session {}", response.session());
          attempt.complete();
          keepAlive();
        } else {
          strategy.attemptFailed(attempt);
        }
      } else {
        strategy.attemptFailed(attempt);
      }
    });
  }
471787
private void onStateChange(Session.State state) {
    switch (state) {
      // When the session is opened, transition the state to CONNECTED.
      case OPEN:
        setState(State.CONNECTED);
        break;
      // When the session becomes unstable, transition the state to SUSPENDED.
      case UNSTABLE:
        setState(State.SUSPENDED);
        break;
      case STALE:
        setState(State.SUSPENDED);
        this.close();
        break;
      // When the session is expired, transition the state to SUSPENDED if necessary. The recovery strategy
      // must determine whether to attempt to recover the client.
      case EXPIRED:
        setState(State.SUSPENDED);
        recoveryStrategy.recover(this);
        break;
      case CLOSED:
        setState(State.CLOSED);
        break;
      default:
        break;
    }
  }
637744
public void deleteSession(String session) {
    for (Set<String> sessions : hostsToSessions.values()) {
      sessions.remove(session);
    }
  }
806751
public void disconnect() throws Exception {
		if (session != null) {
			session.getCloseFuture().awaitUninterruptibly();
		}
		if (connector != null) {
			connector.dispose();
		}
	}