Add hazelcast-spring Sample

Fixes gh-274
This commit is contained in:
Mark Anderson
2015-08-18 23:38:32 +01:00
committed by Rob Winch
parent 68ad464b67
commit e3414ef11e
19 changed files with 554 additions and 1 deletions

View File

@@ -68,6 +68,11 @@ If you are looking to get started with Spring Session, the best place to start i
| Demonstrates how to use Spring Session with Hazelcast.
| TBD
[[samples-hazelcast-spring]]
| {gh-samples-url}hazelcast-spring[Hazelcast Spring]
| Demonstrates how to use Spring Session and Hazelcast with an existing Spring Security application.
| TBD
|===
[[httpsession]]
@@ -580,9 +585,18 @@ include::{indexdoc-tests}[tags=new-mapsessionrepository]
==== Using Spring Session and Hazlecast
The <<samples,Hazelcast Sample>> is a complete application demonstrating using Spring Session with Hazelcast.
To run it use the following:
./gradlew :samples:hazelcast:tomcatRun
The <<samples,Hazelcast Spring Sample>> is a complete application demonstrating using Spring Session with Hazelcast and Spring Security.
It includes example Hazelcast `MapListener` implementations that support firing `SessionCreatedEvent`, `SessionDeletedEvent` and `SessionExpiredEvent`.
To run it use the following:
./gradlew :samples:hazelcast-spring:tomcatRun
[[community]]
== Spring Session Community

View File

@@ -12,4 +12,4 @@ servletApiVersion=3.0.1
spockVersion=0.7-groovy-2.0
commonsPoolVersion=2.2
springDataRedisVersion=1.4.2.RELEASE
hazelcastVersion=3.3.3
hazelcastVersion=3.5.1

View File

@@ -0,0 +1,22 @@
apply from: JAVA_GRADLE
apply from: TOMCAT_7_GRADLE
tasks.findByPath("artifactoryPublish")?.enabled = false
sonarRunner {
skipProject = true
}
dependencies {
compile project(':spring-session'),
"org.springframework:spring-web:$springVersion",
"org.springframework.security:spring-security-config:$springSecurityVersion",
"org.springframework.security:spring-security-web:$springSecurityVersion",
"com.hazelcast:hazelcast-client:$hazelcastVersion",
jstlDependencies
providedCompile "javax.servlet:javax.servlet-api:$servletApiVersion"
testCompile "junit:junit:$junitVersion"
integrationTestCompile gebDependencies
}

View File

@@ -0,0 +1,65 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample
import geb.spock.GebReportingSpec
import pages.*
import sample.pages.HomePage
import sample.pages.LoginPage
import spock.lang.Stepwise
/**
* Ensures that Spring Security and Session are working
*
* @author Rob Winch
*/
@Stepwise
class SecurityTests extends GebReportingSpec {
def 'Unauthenticated user sent to log in page'() {
when: 'unauthenticated user request protected page'
via HomePage
then: 'sent to the log in page'
at LoginPage
}
def 'Log in views home page'() {
when: 'log in successfully'
login()
then: 'sent to original page'
at HomePage
and: 'the username is displayed'
username == 'user'
and: 'Spring Session Management is being used'
driver.manage().cookies.find { it.name == 'SESSION' }
and: 'Standard Session is NOT being used'
!driver.manage().cookies.find { it.name == 'JSESSIONID' }
}
def 'Log out success'() {
when:
logout()
then:
at LoginPage
}
def 'Logged out user sent to log in page'() {
when: 'logged out user request protected page'
via HomePage
then: 'sent to the log in page'
at LoginPage
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.pages
import geb.Page
/**
* The home page
*
* @author Rob Winch
*/
class HomePage extends Page {
static url = ''
static at = { assert driver.title == 'Secured Content'; true}
static content = {
username { $('#un').text() }
logout(to:LoginPage) { $('input[type=submit]').click() }
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample.pages
import geb.Page
/**
* The Links Page
*
* @author Rob Winch
*/
class LoginPage extends Page {
static url = '/login'
static at = { assert driver.title == 'Login Page'; true}
static content = {
form { $('form') }
submit { $('input[type=submit]') }
login(required:false) { user='user', pass='password' ->
form.username = user
form.password = pass
submit.click(HomePage)
}
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.MapSessionRepository;
import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession;
import org.springframework.session.ExpiringSession;
import org.springframework.util.SocketUtils;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.config.SerializerConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
// tag::class[]
@EnableSpringHttpSession
@Configuration
public class Config {
private String sessionMapName = "spring:session:sessions";
@Autowired
private ApplicationEventPublisher eventPublisher;
@Bean(destroyMethod = "shutdown")
public HazelcastInstance hazelcastInstance() {
com.hazelcast.config.Config cfg = new com.hazelcast.config.Config();
NetworkConfig netConfig = new NetworkConfig();
netConfig.setPort(SocketUtils.findAvailableTcpPort());
cfg.setNetworkConfig(netConfig);
SerializerConfig serializer = new SerializerConfig().setTypeClass(
Object.class).setImplementation(new ObjectStreamSerializer());
cfg.getSerializationConfig().addSerializerConfig(serializer);
MapConfig mc = new MapConfig();
mc.setName(sessionMapName);
mc.setMaxIdleSeconds(60);
cfg.addMapConfig(mc);
return Hazelcast.newHazelcastInstance(cfg);
}
@Bean
public SessionRemovedListener removeListener() {
return new SessionRemovedListener(eventPublisher);
}
@Bean
public SessionEvictedListener evictListener() {
return new SessionEvictedListener(eventPublisher);
}
@Bean
public SessionCreatedListener addListener() {
return new SessionCreatedListener(eventPublisher);
}
@Bean
public MapSessionRepository sessionRepository(HazelcastInstance instance,
SessionRemovedListener removeListener, SessionEvictedListener evictListener,
SessionCreatedListener addListener) {
IMap<String, ExpiringSession> sessions = instance.getMap(sessionMapName);
sessions.addEntryListener(removeListener, true);
sessions.addEntryListener(evictListener, true);
sessions.addEntryListener(addListener, true);
return new MapSessionRepository(sessions);
}
}
// end::class[]

View File

@@ -0,0 +1,24 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
// tag::class[]
public class Initializer extends AbstractHttpSessionApplicationInitializer {
}
// end::class[]

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import java.io.*;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;
/**
* A {@link StreamSerializer} that uses Java serialization to persist the
* session. This is certainly not the most efficient way to persist sessions,
* but the example is intended to demonstrate using minimal dependencies. For
* better serialization methods try using <a
* href="https://github.com/EsotericSoftware/kryo">Kryo</a>.
*
* @author Rob Winch
*
*/
public class ObjectStreamSerializer implements StreamSerializer<Object> {
public int getTypeId() {
return 2;
}
public void write(ObjectDataOutput objectDataOutput, Object object)
throws IOException {
ObjectOutputStream out = new ObjectOutputStream((OutputStream) objectDataOutput);
out.writeObject(object);
out.flush();
}
public Object read(ObjectDataInput objectDataInput)
throws IOException {
ObjectInputStream in = new ObjectInputStream((InputStream) objectDataInput);
try {
return in.readObject();
} catch (ClassNotFoundException e) {
throw new IOException(e);
}
}
public void destroy() {
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package sample;
/**
* @author Rob Winch
*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@EnableWebSecurity
public class SecurityConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
// tag::class[]
public class SecurityInitializer extends
AbstractSecurityWebApplicationInitializer {
public SecurityInitializer() {
super(SecurityConfig.class, Config.class);
}
}
// end::class[]

View File

@@ -0,0 +1,24 @@
package sample;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.session.ExpiringSession;
import org.springframework.session.events.SessionCreatedEvent;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.map.listener.EntryAddedListener;
public class SessionCreatedListener
implements EntryAddedListener<String, ExpiringSession> {
private ApplicationEventPublisher eventPublisher;
public SessionCreatedListener(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void entryAdded(EntryEvent<String, ExpiringSession> event) {
System.out.println("Session added: " + event);
eventPublisher.publishEvent(new SessionCreatedEvent(this, event.getValue()));
}
}

View File

@@ -0,0 +1,25 @@
package sample;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.session.ExpiringSession;
import org.springframework.session.events.SessionExpiredEvent;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.map.listener.EntryEvictedListener;
public class SessionEvictedListener
implements EntryEvictedListener<String, ExpiringSession> {
private ApplicationEventPublisher eventPublisher;
public SessionEvictedListener(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void entryEvicted(EntryEvent<String, ExpiringSession> event) {
System.out.println("Session removed: " + event);
eventPublisher.publishEvent(new SessionExpiredEvent(this, event.getOldValue()));
}
}

View File

@@ -0,0 +1,25 @@
package sample;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.session.ExpiringSession;
import org.springframework.session.events.SessionDeletedEvent;
import com.hazelcast.core.EntryEvent;
import com.hazelcast.map.listener.EntryRemovedListener;
public class SessionRemovedListener
implements EntryRemovedListener<String, ExpiringSession> {
private ApplicationEventPublisher eventPublisher;
public SessionRemovedListener(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void entryRemoved(EntryEvent<String, ExpiringSession> event) {
System.out.println("Session removed: " + event);
eventPublisher.publishEvent(new SessionDeletedEvent(this, event.getOldValue()));
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sample;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/session")
public class SessionServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String attributeName = req.getParameter("attributeName");
String attributeValue = req.getParameter("attributeValue");
req.getSession().setAttribute(attributeName, attributeValue);
resp.sendRedirect(req.getContextPath() + "/");
}
private static final long serialVersionUID = 2878267318695777395L;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,32 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Secured Content</title>
<link rel="stylesheet" href="assets/bootstrap.min.css">
<style type="text/css">
body {
padding: 1em;
}
#un {
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h1>Description</h1>
<p>This demonstrates how Spring Session and Hazelcast can be combined with Spring Security. The important thing to ensure is that Spring Session's Filter is included before Spring Security's Filter.</p>
<h1>Logged in as</h1>
<p>You are currently logged in as <span id="un"><c:out value="${pageContext.request.remoteUser}"/></span>.</p>
<c:url value="/logout" var="logoutUrl"/>
<form action="${logoutUrl}" method="post">
<input type="submit" value="Log Out"/>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
</div>
</body>
</html>

View File

@@ -5,6 +5,7 @@ include 'docs'
include 'samples:boot'
include 'samples:findbyusername'
include 'samples:hazelcast'
include 'samples:hazelcast-spring'
include 'samples:httpsession'
include 'samples:httpsession-xml'
include 'samples:rest'