/**
   * Test for issue #49: Sessions not associated with a memcached node don't get associated as soon
   * as a memcached is available
   *
   * @throws InterruptedException
   * @throws IOException
   * @throws TimeoutException
   * @throws ExecutionException
   */
  @Test(enabled = true)
  public void testNotAssociatedSessionGetsAssociatedIssue49()
      throws InterruptedException, IOException, ExecutionException, TimeoutException {
    _daemon.stop();

    final SessionManager manager = _tomcat1.getManager();
    manager.setMaxInactiveInterval(5);
    manager.setSticky(true);
    final SessionIdFormat sessionIdFormat = new SessionIdFormat();

    final Session session = manager.createSession(null);
    assertNull(sessionIdFormat.extractMemcachedId(session.getId()));

    _daemon.start();

    // Wait so that the daemon will be available and the client can reconnect (async get didn't do
    // the trick)
    Thread.sleep(4000);

    final String newSessionId =
        manager.getMemcachedSessionService().changeSessionIdOnMemcachedFailover(session.getId());
    assertNotNull(newSessionId);
    assertEquals(newSessionId, session.getId());
    assertEquals(sessionIdFormat.extractMemcachedId(newSessionId), _memcachedNodeId);
  }
 private void startLocalMemcacheInstance(int port) {
   logger.info("Starting local memcache on port: " + port);
   CacheStorage<Key, LocalCacheElement> storage =
       ConcurrentLinkedHashMap.create(
           ConcurrentLinkedHashMap.EvictionPolicy.FIFO, 100, 1024 * 500);
   daemon.setCache(new CacheImpl(storage));
   daemon.setAddr(new InetSocketAddress("localhost", port));
   daemon.start();
 }
  /**
   * Test for issue #60 (Add possibility to disable msm at runtime): start msm disabled and
   * afterwards enable
   */
  @Test(enabled = true)
  public void testStartMsmDisabled() throws Exception {

    // shutdown our server and our client
    _memcached.shutdown();
    _daemon.stop();

    // start a new tomcat with msm initially disabled
    _tomcat1.stop();
    Thread.sleep(500);
    final String memcachedNodes = _memcachedNodeId + ":localhost:" + _memcachedPort;
    _tomcat1 =
        getTestUtils()
            .tomcatBuilder()
            .port(_portTomcat1)
            .memcachedNodes(memcachedNodes)
            .sticky(true)
            .enabled(false)
            .jvmRoute("app1")
            .buildAndStart();

    LOG.info("Waiting, check logs to see if the client causes any 'Connection refused' logging...");
    Thread.sleep(1000);

    // some basic tests for session functionality
    checkSessionFunctionalityWithMsmDisabled();

    // start memcached, client and reenable msm
    _daemon.start();
    _memcached =
        createMemcachedClient(memcachedNodes, new InetSocketAddress("localhost", _memcachedPort));
    _tomcat1.getManager().setEnabled(true);
    // Wait a little bit, so that msm's memcached client can connect and is ready when test starts
    Thread.sleep(100);

    // memcached based stuff should work again
    final String sessionId1 = makeRequest(_httpClient, _portTomcat1, null);
    assertNotNull(sessionId1, "No session created.");
    assertNotNull(
        new SessionIdFormat().extractMemcachedId(sessionId1),
        "memcached node id missing with msm switched to enabled");
    Thread.sleep(50);
    assertNotNull(_memcached.get(sessionId1), "Session not available in memcached.");

    waitForSessionExpiration(true);

    assertNull(_memcached.get(sessionId1), "Expired session still existing in memcached");
  }
  @BeforeMethod
  public void setUp(final Method testMethod) throws Throwable {

    _portTomcat1 = 18888;

    _memcachedPort = 21211;

    final InetSocketAddress address = new InetSocketAddress("localhost", _memcachedPort);
    _daemon = createDaemon(address);
    _daemon.start();

    final String[] testGroups = testMethod.getAnnotation(Test.class).groups();
    final String nodePrefix =
        testGroups.length == 0 || !GROUP_WITHOUT_NODE_ID.equals(testGroups[0])
            ? _memcachedNodeId + ":"
            : "";

    _memcachedNodes = nodePrefix + "localhost:" + _memcachedPort;

    try {
      System.setProperty("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true");
      _tomcat1 = tcBuilder().buildAndStart();
    } catch (final Throwable e) {
      LOG.error("could not start tomcat.", e);
      throw e;
    }

    _memcached = createMemcachedClient(_memcachedNodes, address);

    _httpClient = new DefaultHttpClient();
  }
 @AfterMethod
 public void tearDown() throws Exception {
   _memcached.shutdown();
   _tomcat1.stop();
   _httpClient.getConnectionManager().shutdown();
   _daemon.stop();
 }
  /** Test for issue #60 (Add possibility to disable msm at runtime): disable msm */
  @Test(enabled = true)
  public void testDisableMsmAtRuntime()
      throws InterruptedException, IOException, ExecutionException, TimeoutException,
          LifecycleException, HttpException {
    final SessionManager manager = _tomcat1.getManager();
    manager.setSticky(true);
    // disable msm, shutdown our server and our client
    manager.setEnabled(false);
    _memcached.shutdown();
    _daemon.stop();

    checkSessionFunctionalityWithMsmDisabled();
  }
  @Test(enabled = true, dataProviderClass = TestUtils.class, dataProvider = STICKYNESS_PROVIDER)
  public void testInvalidatedSessionRemovedFromMemcached(
      @Nonnull final SessionAffinityMode sessionAffinity)
      throws IOException, InterruptedException, HttpException {

    setStickyness(sessionAffinity);

    final String sessionId1 = makeRequest(_httpClient, _portTomcat1, null);
    assertNotNull(sessionId1, "No session created.");

    final Response response = get(_httpClient, _portTomcat1, PATH_INVALIDATE, sessionId1);
    assertNull(response.getResponseSessionId());
    assertEquals(_daemon.getCache().getGetMisses(), 1); // 1 is ok

    assertNull(_memcached.get(sessionId1), "Invalidated session still existing in memcached");
    if (!sessionAffinity.isSticky()) {
      assertNull(
          _memcached.get(createValidityInfoKeyName(sessionId1)),
          "ValidityInfo for invalidated session still exists in memcached.");
    }
  }