use of io.undertow.server.session.Session in project wildfly by wildfly.
the class DistributableSingleSignOnTestCase method remove.
@Test
public void remove() {
String deployment = "deployment";
BatchContext context = mock(BatchContext.class);
Session session = mock(Session.class);
SessionManager manager = mock(SessionManager.class);
Sessions<String, String> sessions = mock(Sessions.class);
when(this.batcher.resumeBatch(this.batch)).thenReturn(context);
when(session.getSessionManager()).thenReturn(manager);
when(manager.getDeploymentName()).thenReturn(deployment);
when(this.sso.getSessions()).thenReturn(sessions);
this.subject.remove(session);
verify(sessions).removeSession(deployment);
verifyZeroInteractions(this.batch);
verify(context).close();
}
use of io.undertow.server.session.Session in project wildfly by wildfly.
the class DistributableSingleSignOnTestCase method iterator.
@Test
public void iterator() {
BatchContext context = mock(BatchContext.class);
Sessions<String, String> sessions = mock(Sessions.class);
SessionManager manager = mock(SessionManager.class);
Session session = mock(Session.class);
String deployment = "deployment";
String sessionId = "session";
when(this.batcher.resumeBatch(this.batch)).thenReturn(context);
when(this.sso.getSessions()).thenReturn(sessions);
when(sessions.getDeployments()).thenReturn(Collections.singleton(deployment));
when(sessions.getSession(deployment)).thenReturn(sessionId);
when(this.registry.getSessionManager(deployment)).thenReturn(manager);
when(manager.getSession(sessionId)).thenReturn(session);
when(session.getId()).thenReturn(sessionId);
Iterator<Session> results = this.subject.iterator();
assertTrue(results.hasNext());
Session result = results.next();
assertEquals(session.getId(), result.getId());
assertFalse(results.hasNext());
verifyZeroInteractions(this.batch);
verify(context).close();
// Validate that returned sessions can be invalidated
HttpServerExchange exchange = new HttpServerExchange(null);
Session mutableSession = mock(Session.class);
when(session.getSessionManager()).thenReturn(manager);
when(manager.getSession(same(exchange), Matchers.<SessionConfig>any())).thenReturn(mutableSession);
result.invalidate(exchange);
verify(mutableSession).invalidate(same(exchange));
verifyZeroInteractions(this.batch);
verifyNoMoreInteractions(context);
}
use of io.undertow.server.session.Session in project undertow by undertow-io.
the class SessionServer method main.
public static void main(String[] args) {
PathHandler pathHandler = new PathHandler();
pathHandler.addPrefixPath("/", new HttpHandler() {
public void handleRequest(HttpServerExchange exchange) throws Exception {
StringBuilder sb = new StringBuilder();
sb.append("<form action='addToSession' >");
sb.append("<label>Attribute Name</label>");
sb.append("<input name='attrName' />");
sb.append("<label>Attribute Value</label>");
sb.append("<input name='value' />");
sb.append("<button>Save to Session</button>");
// To retrive the SessionManager use the attachmentKey
SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
// same goes to SessionConfig
SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
sb.append("</form>");
sb.append("<a href='/destroySession'>Destroy Session</a>");
sb.append("<br/>");
Session session = sm.getSession(exchange, sessionConfig);
if (session == null)
session = sm.createSession(exchange, sessionConfig);
sb.append("<ul>");
for (String string : session.getAttributeNames()) {
sb.append("<li>" + string + " : " + session.getAttribute(string) + "</li>");
}
sb.append("</ul>");
exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "text/html;");
exchange.getResponseSender().send(sb.toString());
}
});
pathHandler.addPrefixPath("/addToSession", new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
Map<String, Deque<String>> reqParams = exchange.getQueryParameters();
Session session = sm.getSession(exchange, sessionConfig);
if (session == null)
session = sm.createSession(exchange, sessionConfig);
Deque<String> deque = reqParams.get("attrName");
Deque<String> dequeVal = reqParams.get("value");
session.setAttribute(deque.getLast(), dequeVal.getLast());
exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
exchange.getResponseHeaders().put(Headers.LOCATION, "/");
exchange.getResponseSender().close();
}
});
pathHandler.addPrefixPath("/destroySession", new HttpHandler() {
public void handleRequest(HttpServerExchange exchange) throws Exception {
SessionManager sm = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
SessionConfig sessionConfig = exchange.getAttachment(SessionConfig.ATTACHMENT_KEY);
Session session = sm.getSession(exchange, sessionConfig);
if (session == null)
session = sm.createSession(exchange, sessionConfig);
session.invalidate(exchange);
exchange.setStatusCode(StatusCodes.TEMPORARY_REDIRECT);
exchange.getResponseHeaders().put(Headers.LOCATION, "/");
exchange.getResponseSender().close();
}
});
SessionManager sessionManager = new InMemorySessionManager("SESSION_MANAGER");
SessionCookieConfig sessionConfig = new SessionCookieConfig();
/*
* Use the sessionAttachmentHandler to add the sessionManager and
* sessionCofing to the exchange of every request
*/
SessionAttachmentHandler sessionAttachmentHandler = new SessionAttachmentHandler(sessionManager, sessionConfig);
// set as next handler your root handler
sessionAttachmentHandler.setNext(pathHandler);
System.out.println("Open the url and fill the form to add attributes into the session");
Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(sessionAttachmentHandler).build();
server.start();
}
use of io.undertow.server.session.Session in project undertow by undertow-io.
the class InMemorySessionTestCase method inMemorySessionTimeoutExpirationTest.
// https://issues.redhat.com/browse/UNDERTOW-1419
@Test
public void inMemorySessionTimeoutExpirationTest() throws IOException, InterruptedException {
final int maxInactiveIntervalInSeconds = 1;
final int accessorThreadSleepInMilliseconds = 200;
TestHttpClient client = new TestHttpClient();
client.setCookieStore(new BasicCookieStore());
try {
final SessionCookieConfig sessionConfig = new SessionCookieConfig();
final SessionAttachmentHandler handler = new SessionAttachmentHandler(new InMemorySessionManager(""), sessionConfig);
handler.setNext(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
Session session = manager.getSession(exchange, sessionConfig);
if (session == null) {
// set 1 second timeout for this session expiration
manager.setDefaultSessionTimeout(maxInactiveIntervalInSeconds);
session = manager.createSession(exchange, sessionConfig);
session.setAttribute(COUNT, 0);
// let's call getAttribute() some times to be sure that the session timeout is no longer bumped
// by the method invocation
Runnable r = new Runnable() {
public void run() {
Session innerThreadSession = manager.getSession(exchange, sessionConfig);
int iterations = ((maxInactiveIntervalInSeconds * 1000) / accessorThreadSleepInMilliseconds);
for (int i = 0; i <= iterations; i++) {
try {
Thread.sleep(accessorThreadSleepInMilliseconds);
} catch (InterruptedException e) {
System.out.println(String.format("Unexpected error during Thread.sleep(): %s", e.getMessage()));
}
if (innerThreadSession != null) {
try {
System.out.println(String.format("Session is still valid. Attribute is: %s", innerThreadSession.getAttribute(COUNT).toString()));
if (i == iterations) {
System.out.println("Session should not still be valid!");
}
} catch (IllegalStateException e) {
if ((e instanceof IllegalStateException) && e.getMessage().startsWith("UT000010")) {
System.out.println(String.format("This is expected as session is not valid anymore: %s", e.getMessage()));
} else {
System.out.println(String.format("Unexpected exception while calling session.getAttribute(): %s", e.getMessage()));
}
}
}
}
}
};
Thread thread = new Thread(r);
thread.start();
}
// here the server is accessing one session attribute, so we're sure that the bumped timeout
// issue is being replicated and we can test for regression
Integer count = (Integer) session.getAttribute(COUNT);
exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
session.setAttribute(COUNT, ++count);
}
});
DefaultServer.setRootHandler(handler);
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
HttpResponse result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
Header[] header = result.getHeaders(COUNT);
Assert.assertEquals("0", header[0].getValue());
Thread.sleep(2 * 1000L);
// after 2 seconds from the last call, the session expiration timeout hasn't been bumped anymore,
// so now "COUNT" should be still set to 0 (zero)
get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
header = result.getHeaders(COUNT);
Assert.assertEquals("0", header[0].getValue());
} finally {
client.getConnectionManager().shutdown();
}
}
use of io.undertow.server.session.Session in project undertow by undertow-io.
the class InMemorySessionTestCase method inMemoryMaxSessionsTest.
@Test
public void inMemoryMaxSessionsTest() throws IOException {
TestHttpClient client1 = new TestHttpClient();
client1.setCookieStore(new BasicCookieStore());
TestHttpClient client2 = new TestHttpClient();
client2.setCookieStore(new BasicCookieStore());
try {
final SessionCookieConfig sessionConfig = new SessionCookieConfig();
final SessionAttachmentHandler handler = new SessionAttachmentHandler(new InMemorySessionManager("", 1, true), sessionConfig);
handler.setNext(new HttpHandler() {
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final SessionManager manager = exchange.getAttachment(SessionManager.ATTACHMENT_KEY);
Session session = manager.getSession(exchange, sessionConfig);
if (session == null) {
session = manager.createSession(exchange, sessionConfig);
session.setAttribute(COUNT, 0);
}
Integer count = (Integer) session.getAttribute(COUNT);
exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
session.setAttribute(COUNT, ++count);
}
});
DefaultServer.setRootHandler(handler);
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
HttpResponse result = client1.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
Header[] header = result.getHeaders(COUNT);
Assert.assertEquals("0", header[0].getValue());
get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
result = client1.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
header = result.getHeaders(COUNT);
Assert.assertEquals("1", header[0].getValue());
get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
result = client2.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
header = result.getHeaders(COUNT);
Assert.assertEquals("0", header[0].getValue());
get = new HttpGet(DefaultServer.getDefaultServerURL() + "/notamatchingpath");
result = client1.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
HttpClientUtils.readResponse(result);
header = result.getHeaders(COUNT);
Assert.assertEquals("0", header[0].getValue());
} finally {
client1.getConnectionManager().shutdown();
client2.getConnectionManager().shutdown();
}
}
Aggregations