Spaces to tabs and license cleanup

This commit is contained in:
Rob Winch
2015-04-02 15:57:00 -05:00
parent 93b8856a20
commit 4dedb4d10a
143 changed files with 8270 additions and 7654 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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
@@ -28,7 +28,7 @@ import org.springframework.context.annotation.Configuration;
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@@ -1,3 +1,18 @@
/*
* 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.config;
import javax.sql.DataSource;
@@ -11,14 +26,14 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2).build();
}
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2).build();
}
@Bean
public JedisConnectionFactory connectionFactory() throws Exception {
return new JedisConnectionFactory();
}
@Bean
public JedisConnectionFactory connectionFactory() throws Exception {
return new JedisConnectionFactory();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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
@@ -33,36 +33,34 @@ import redis.embedded.RedisServer;
@Configuration
public class EmbeddedRedisConfig {
@Bean
public static RedisServerBean redisServer() {
return new RedisServerBean();
}
@Bean
public static RedisServerBean redisServer() {
return new RedisServerBean();
}
/**
* Implements BeanDefinitionRegistryPostProcessor to ensure this Bean
* is initialized before any other Beans. Specifically, we want to ensure
* that the Redis Server is started before RedisHttpSessionConfiguration
* attempts to enable Keyspace notifications.
*/
static class RedisServerBean implements InitializingBean, DisposableBean, BeanDefinitionRegistryPostProcessor {
private RedisServer redisServer;
/**
* Implements BeanDefinitionRegistryPostProcessor to ensure this Bean
* is initialized before any other Beans. Specifically, we want to ensure
* that the Redis Server is started before RedisHttpSessionConfiguration
* attempts to enable Keyspace notifications.
*/
static class RedisServerBean implements InitializingBean, DisposableBean, BeanDefinitionRegistryPostProcessor {
private RedisServer redisServer;
public void afterPropertiesSet() throws Exception {
redisServer = new RedisServer(Protocol.DEFAULT_PORT);
redisServer.start();
}
public void afterPropertiesSet() throws Exception {
redisServer = new RedisServer(Protocol.DEFAULT_PORT);
redisServer.start();
}
public void destroy() throws Exception {
if(redisServer != null) {
redisServer.stop();
}
}
public void destroy() throws Exception {
if(redisServer != null) {
redisServer.stop();
}
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {}
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {}
}
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@@ -32,7 +32,7 @@ public class H2Initializer {
@Bean
public ServletRegistrationBean h2Servlet() {
ServletRegistrationBean servletBean = new ServletRegistrationBean();
servletBean.addUrlMappings("/h2/*");
servletBean.addUrlMappings("/h2/*");
servletBean.setServlet(new WebServlet());
return servletBean;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@@ -34,31 +34,34 @@ import org.springframework.session.data.redis.config.annotation.web.http.EnableR
// tag::enable-redis-httpsession[]
@EnableRedisHttpSession//(maxInactiveIntervalInSeconds = 60)
public class WebSecurityConfig
extends WebSecurityConfigurerAdapter {
extends WebSecurityConfigurerAdapter {
// end::enable-redis-httpsession[]
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout()
.permitAll();
}
// @formatter:on
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout()
.permitAll();
}
// @formatter:off
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService userDetailsService) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
// @formatter:on
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService userDetailsService) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* 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
@@ -15,7 +15,6 @@
*/
package sample.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.annotation.EnableScheduling;
@@ -29,16 +28,16 @@ import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfig
extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> { // <1>
extends AbstractSessionWebSocketMessageBrokerConfigurer<ExpiringSession> { // <1>
protected void configureStompEndpoints(StompEndpointRegistry registry) { // <2>
registry.addEndpoint("/messages")
.withSockJS();
}
protected void configureStompEndpoints(StompEndpointRegistry registry) { // <2>
registry.addEndpoint("/messages")
.withSockJS();
}
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue/", "/topic/");
registry.setApplicationDestinationPrefixes("/app");
}
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue/", "/topic/");
registry.setApplicationDestinationPrefixes("/app");
}
}
// end::class[]

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* 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
@@ -31,13 +31,13 @@ import sample.websocket.WebSocketDisconnectHandler;
@Configuration
public class WebSocketHandlersConfig<S extends ExpiringSession> {
@Bean
public WebSocketConnectHandler<S> webSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) {
return new WebSocketConnectHandler<S>(messagingTemplate, repository);
}
@Bean
public WebSocketConnectHandler<S> webSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) {
return new WebSocketConnectHandler<S>(messagingTemplate, repository);
}
@Bean
public WebSocketDisconnectHandler<S> webSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) {
return new WebSocketDisconnectHandler<S>(messagingTemplate, repository);
}
@Bean
public WebSocketDisconnectHandler<S> webSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) {
return new WebSocketDisconnectHandler<S>(messagingTemplate, repository);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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
@@ -26,11 +26,13 @@ import org.springframework.security.config.annotation.web.socket.AbstractSecurit
@Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.antMatchers(SimpMessageType.MESSAGE,"/queue/**","/topic/**").denyAll()
.antMatchers(SimpMessageType.SUBSCRIBE, "/queue/**/*-user*","/topic/**/*-user*").denyAll()
.anyMessage().authenticated();
}
// @formatter:off
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.antMatchers(SimpMessageType.MESSAGE,"/queue/**","/topic/**").denyAll()
.antMatchers(SimpMessageType.SUBSCRIBE, "/queue/**/*-user*","/topic/**/*-user*").denyAll()
.anyMessage().authenticated();
}
// @formatter:on
}

View File

@@ -1,6 +1,20 @@
/*
* 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.data;
import java.util.Calendar;
import javax.persistence.Entity;
@@ -10,13 +24,13 @@ import javax.persistence.Id;
public class ActiveWebSocketUser {
@Id
private String id;
private String username;
private Calendar connectionTime;
public ActiveWebSocketUser() {}
public ActiveWebSocketUser(String id, String username, Calendar connectionTime) {
super();
this.id = id;
@@ -39,6 +53,6 @@ public class ActiveWebSocketUser {
public void setConnectionTime(Calendar connectionTime) {
this.connectionTime = connectionTime;
}
}

View File

@@ -1,3 +1,18 @@
/*
* 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.data;
import java.util.List;

View File

@@ -1,14 +1,29 @@
/*
* 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.data;
import java.util.Calendar;
public class InstantMessage {
private String to;
private String from;
private String message;
private Calendar created = Calendar.getInstance();
public String getTo() {
@@ -42,7 +57,7 @@ public class InstantMessage {
public void setCreated(Calendar created) {
this.created = created;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@@ -40,73 +40,73 @@ import org.springframework.security.crypto.password.PasswordEncoder;
@Entity
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotEmpty(message = "First name is required.")
private String firstName;
@NotEmpty(message = "First name is required.")
private String firstName;
@NotEmpty(message = "Last name is required.")
private String lastName;
@NotEmpty(message = "Last name is required.")
private String lastName;
@Email(message = "Please provide a valid email address.")
@NotEmpty(message = "Email is required.")
@Column(unique=true, nullable = false)
private String email;
@Email(message = "Please provide a valid email address.")
@NotEmpty(message = "Email is required.")
@Column(unique=true, nullable = false)
private String email;
@NotEmpty(message = "Password is required.")
private String password;
@NotEmpty(message = "Password is required.")
private String password;
public User() {}
public User() {}
public User(User user) {
this.id = user.id;
this.firstName = user.firstName;
this.lastName = user.lastName;
this.email = user.email;
this.password = user.password;
}
public User(User user) {
this.id = user.id;
this.firstName = user.firstName;
this.lastName = user.lastName;
this.email = user.email;
this.password = user.password;
}
public String getPassword() {
return password;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getId() {
return id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setEmail(String email) {
this.email = email;
}
private static final long serialVersionUID = 2738859149330833739L;
private static final long serialVersionUID = 2738859149330833739L;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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
@@ -25,5 +25,5 @@ import org.springframework.data.repository.CrudRepository;
*/
public interface UserRepository extends CrudRepository<User, Long> {
User findByEmail(String email);
User findByEmail(String email);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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
@@ -22,7 +22,6 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -40,29 +39,29 @@ import sample.security.CurrentUser;
@Controller
@RequestMapping("/")
public class MessageController {
private SimpMessageSendingOperations messagingTemplate;
private ActiveWebSocketUserRepository activeUserRepository;
private SimpMessageSendingOperations messagingTemplate;
private ActiveWebSocketUserRepository activeUserRepository;
@Autowired
public MessageController(ActiveWebSocketUserRepository activeUserRepository,SimpMessageSendingOperations messagingTemplate) {
this.activeUserRepository = activeUserRepository;
this.messagingTemplate = messagingTemplate;
}
@Autowired
public MessageController(ActiveWebSocketUserRepository activeUserRepository,SimpMessageSendingOperations messagingTemplate) {
this.activeUserRepository = activeUserRepository;
this.messagingTemplate = messagingTemplate;
}
@RequestMapping("/")
public String im() {
return "index";
}
@RequestMapping("/")
public String im() {
return "index";
}
@MessageMapping("/im")
public void im(InstantMessage im, @CurrentUser User currentUser) {
im.setFrom(currentUser.getEmail());
messagingTemplate.convertAndSendToUser(im.getTo(),"/queue/messages",im);
messagingTemplate.convertAndSendToUser(im.getFrom(),"/queue/messages",im);
}
@MessageMapping("/im")
public void im(InstantMessage im, @CurrentUser User currentUser) {
im.setFrom(currentUser.getEmail());
messagingTemplate.convertAndSendToUser(im.getTo(),"/queue/messages",im);
messagingTemplate.convertAndSendToUser(im.getFrom(),"/queue/messages",im);
}
@SubscribeMapping("/users")
public List<String> subscribeMessages() throws Exception {
return activeUserRepository.findAllActiveUsers();
}
@SubscribeMapping("/users")
public List<String> subscribeMessages() throws Exception {
return activeUserRepository.findAllActiveUsers();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@@ -33,55 +33,55 @@ import org.springframework.stereotype.Service;
*/
@Service
public class UserRepositoryUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
private final UserRepository userRepository;
@Autowired
public UserRepositoryUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Autowired
public UserRepositoryUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
/* (non-Javadoc)
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
*/
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
User user = userRepository.findByEmail(username);
if(user == null) {
throw new UsernameNotFoundException("Could not find user " + username);
}
return new CustomUserDetails(user);
}
/* (non-Javadoc)
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
*/
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
User user = userRepository.findByEmail(username);
if(user == null) {
throw new UsernameNotFoundException("Could not find user " + username);
}
return new CustomUserDetails(user);
}
private final static class CustomUserDetails extends User implements UserDetails {
private final static class CustomUserDetails extends User implements UserDetails {
private CustomUserDetails(User user) {
super(user);
}
private CustomUserDetails(User user) {
super(user);
}
public Collection<? extends GrantedAuthority> getAuthorities() {
return AuthorityUtils.createAuthorityList("ROLE_USER");
}
public Collection<? extends GrantedAuthority> getAuthorities() {
return AuthorityUtils.createAuthorityList("ROLE_USER");
}
public String getUsername() {
return getEmail();
}
public String getUsername() {
return getEmail();
}
public boolean isAccountNonExpired() {
return true;
}
public boolean isAccountNonExpired() {
return true;
}
public boolean isAccountNonLocked() {
return true;
}
public boolean isAccountNonLocked() {
return true;
}
public boolean isCredentialsNonExpired() {
return true;
}
public boolean isCredentialsNonExpired() {
return true;
}
public boolean isEnabled() {
return true;
}
public boolean isEnabled() {
return true;
}
private static final long serialVersionUID = 5639683223516504866L;
}
private static final long serialVersionUID = 5639683223516504866L;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@@ -29,23 +29,23 @@ import sample.data.ActiveWebSocketUser;
import sample.data.ActiveWebSocketUserRepository;
public class WebSocketConnectHandler<S> implements ApplicationListener<SessionConnectEvent> {
private ActiveWebSocketUserRepository repository;
private SimpMessageSendingOperations messagingTemplate;
private ActiveWebSocketUserRepository repository;
private SimpMessageSendingOperations messagingTemplate;
public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) {
super();
this.messagingTemplate = messagingTemplate;
this.repository = repository;
}
public WebSocketConnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) {
super();
this.messagingTemplate = messagingTemplate;
this.repository = repository;
}
public void onApplicationEvent(SessionConnectEvent event) {
MessageHeaders headers = event.getMessage().getHeaders();
Principal user = SimpMessageHeaderAccessor.getUser(headers);
if(user == null) {
return;
}
String id = SimpMessageHeaderAccessor.getSessionId(headers);
repository.save(new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance()));
messagingTemplate.convertAndSend("/topic/friends/signin", Arrays.asList(user.getName()));
}
public void onApplicationEvent(SessionConnectEvent event) {
MessageHeaders headers = event.getMessage().getHeaders();
Principal user = SimpMessageHeaderAccessor.getUser(headers);
if(user == null) {
return;
}
String id = SimpMessageHeaderAccessor.getSessionId(headers);
repository.save(new ActiveWebSocketUser(id, user.getName(), Calendar.getInstance()));
messagingTemplate.convertAndSend("/topic/friends/signin", Arrays.asList(user.getName()));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* 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.
@@ -25,27 +25,27 @@ import sample.data.ActiveWebSocketUser;
import sample.data.ActiveWebSocketUserRepository;
public class WebSocketDisconnectHandler<S> implements ApplicationListener<SessionDisconnectEvent> {
private ActiveWebSocketUserRepository repository;
private SimpMessageSendingOperations messagingTemplate;
private ActiveWebSocketUserRepository repository;
private SimpMessageSendingOperations messagingTemplate;
public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) {
super();
this.messagingTemplate = messagingTemplate;
this.repository = repository;
}
public WebSocketDisconnectHandler(SimpMessageSendingOperations messagingTemplate, ActiveWebSocketUserRepository repository) {
super();
this.messagingTemplate = messagingTemplate;
this.repository = repository;
}
public void onApplicationEvent(SessionDisconnectEvent event) {
String id = event.getSessionId();
if(id == null) {
return;
}
ActiveWebSocketUser user = repository.findOne(id);
if(user == null) {
return;
}
public void onApplicationEvent(SessionDisconnectEvent event) {
String id = event.getSessionId();
if(id == null) {
return;
}
ActiveWebSocketUser user = repository.findOne(id);
if(user == null) {
return;
}
repository.delete(id);
messagingTemplate.convertAndSend("/topic/friends/signout", Arrays.asList(user.getUsername()));
repository.delete(id);
messagingTemplate.convertAndSend("/topic/friends/signout", Arrays.asList(user.getUsername()));
}
}
}

View File

@@ -1,139 +1,139 @@
function ApplicationModel(stompClient) {
var self = this;
var self = this;
self.friends = ko.observableArray();
self.username = ko.observable();
self.conversation = ko.observable(new ImConversationModel(stompClient,this.username));
self.notifications = ko.observableArray();
self.friends = ko.observableArray();
self.username = ko.observable();
self.conversation = ko.observable(new ImConversationModel(stompClient,this.username));
self.notifications = ko.observableArray();
self.connect = function() {
stompClient.connect({}, function(frame) {
self.connect = function() {
stompClient.connect({}, function(frame) {
console.log('Connected ' + frame);
self.username(frame.headers['user-name']);
console.log('Connected ' + frame);
self.username(frame.headers['user-name']);
// self.friendSignin({"username": "luke"});
stompClient.subscribe("/user/queue/errors", function(message) {
self.pushNotification("Error " + message.body);
});
stompClient.subscribe("/app/users", function(message) {
var friends = JSON.parse(message.body);
stompClient.subscribe("/user/queue/errors", function(message) {
self.pushNotification("Error " + message.body);
});
stompClient.subscribe("/app/users", function(message) {
var friends = JSON.parse(message.body);
for(var i=0;i<friends.length;i++) {
self.friendSignin({"username": friends[i]});
}
});
stompClient.subscribe("/topic/friends/signin", function(message) {
var friends = JSON.parse(message.body);
for(var i=0;i<friends.length;i++) {
self.friendSignin({"username": friends[i]});
}
});
stompClient.subscribe("/topic/friends/signin", function(message) {
var friends = JSON.parse(message.body);
for(var i=0;i<friends.length;i++) {
self.friendSignin(new ImFriend({"username": friends[i]}));
}
});
stompClient.subscribe("/topic/friends/signout", function(message) {
var friends = JSON.parse(message.body);
for(var i=0;i<friends.length;i++) {
self.friendSignin(new ImFriend({"username": friends[i]}));
}
});
stompClient.subscribe("/topic/friends/signout", function(message) {
var friends = JSON.parse(message.body);
for(var i=0;i<friends.length;i++) {
self.friendSignout(new ImFriend({"username": friends[i]}));
}
});
stompClient.subscribe("/user/queue/messages", function(message) {
self.conversation().receiveMessage(JSON.parse(message.body));
});
}, function(error) {
self.pushNotification(error)
console.log("STOMP protocol error " + error);
});
}
for(var i=0;i<friends.length;i++) {
self.friendSignout(new ImFriend({"username": friends[i]}));
}
});
stompClient.subscribe("/user/queue/messages", function(message) {
self.conversation().receiveMessage(JSON.parse(message.body));
});
}, function(error) {
self.pushNotification(error)
console.log("STOMP protocol error " + error);
});
}
self.pushNotification = function(text) {
self.notifications.push({notification: text});
if (self.notifications().length > 5) {
self.notifications.shift();
}
}
self.pushNotification = function(text) {
self.notifications.push({notification: text});
if (self.notifications().length > 5) {
self.notifications.shift();
}
}
self.logout = function() {
stompClient.disconnect();
window.location.href = "../logout.html";
}
self.logout = function() {
stompClient.disconnect();
window.location.href = "../logout.html";
}
self.friendSignin = function(friend) {
self.friends.push(friend);
}
self.friendSignin = function(friend) {
self.friends.push(friend);
}
self.friendSignout = function(friend) {
var r = self.friends.remove(
function(item) {
item.username == friend.username
}
);
self.friends(r);
}
self.friendSignout = function(friend) {
var r = self.friends.remove(
function(item) {
item.username == friend.username
}
);
self.friends(r);
}
}
function ImFriend(data) {
var self = this;
var self = this;
self.username = data.username;
self.username = data.username;
}
function ImConversationModel(stompClient,from) {
var self = this;
self.stompClient = stompClient;
self.from = from;
self.to = ko.observable(new ImFriend('null'));
self.draft = ko.observable('')
var self = this;
self.stompClient = stompClient;
self.from = from;
self.to = ko.observable(new ImFriend('null'));
self.draft = ko.observable('')
self.messages = ko.observableArray();
self.messages = ko.observableArray();
self.receiveMessage = function(message) {
var elem = $('#chat');
var isFromSelf = self.from() == message.from;
var isFromTo = self.to().username == message.from;
if(!(isFromTo || isFromSelf)) {
self.chat(new ImFriend({"username":message.from}))
}
self.receiveMessage = function(message) {
var elem = $('#chat');
var isFromSelf = self.from() == message.from;
var isFromTo = self.to().username == message.from;
if(!(isFromTo || isFromSelf)) {
self.chat(new ImFriend({"username":message.from}))
}
var atBottom = (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight());
var atBottom = (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight());
self.messages.push(new ImModel(message));
self.messages.push(new ImModel(message));
if (atBottom)
elem.scrollTop(elem[0].scrollHeight);
};
if (atBottom)
elem.scrollTop(elem[0].scrollHeight);
};
self.chat = function(to) {
self.to(to);
self.draft('');
self.messages.removeAll()
$('#trade-dialog').modal();
}
self.chat = function(to) {
self.to(to);
self.draft('');
self.messages.removeAll()
$('#trade-dialog').modal();
}
self.send = function() {
var data = {
"created" : new Date(),
"from" : self.from(),
"to" : self.to().username,
"message" : self.draft()
};
var destination = "/app/im"; // /queue/messages-user1
stompClient.send(destination, {}, JSON.stringify(data));
self.draft('');
}
self.send = function() {
var data = {
"created" : new Date(),
"from" : self.from(),
"to" : self.to().username,
"message" : self.draft()
};
var destination = "/app/im"; // /queue/messages-user1
stompClient.send(destination, {}, JSON.stringify(data));
self.draft('');
}
};
function ImModel(data) {
var self = this;
var self = this;
self.created = new Date(data.created);
self.to = data.to;
self.message = data.message;
self.from = data.from;
self.messageFormatted = ko.computed(function() {
return self.created.getHours() + ":" + self.created.getMinutes() + ":" + self.created.getSeconds() + " - " + self.from + " - " + self.message;
})
self.created = new Date(data.created);
self.to = data.to;
self.message = data.message;
self.from = data.from;
self.messageFormatted = ko.computed(function() {
return self.created.getHours() + ":" + self.created.getMinutes() + ":" + self.created.getSeconds() + " - " + self.from + " - " + self.message;
})
};

View File

@@ -1,74 +1,74 @@
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="layout">
<head>
<title>View All</title>
</head>
<body>
<div layout:fragment="content">
<div class="container">
<div id="heading" class="masthead">
<h3 class="muted">Chat Application</h3>
</div>
<div id="main-content">
<table class="table table-striped">
<thead>
<tr>
<th>User</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: friends()">
<tr>
<td data-bind="text: username"></td>
<td class="trade-buttons">
<button class="btn btn-primary" data-bind="click: $root.conversation().chat">Chat</button>
</td>
</tr>
</tbody>
</table>
<head>
<title>View All</title>
</head>
<body>
<div layout:fragment="content">
<div class="container">
<div id="heading" class="masthead">
<h3 class="muted">Chat Application</h3>
</div>
<div id="main-content">
<table class="table table-striped">
<thead>
<tr>
<th>User</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: friends()">
<tr>
<td data-bind="text: username"></td>
<td class="trade-buttons">
<button class="btn btn-primary" data-bind="click: $root.conversation().chat">Chat</button>
</td>
</tr>
</tbody>
</table>
<div id="trade-dialog" class="modal hide fade" tabindex="-1">
<div class="modal-body">
<div>Chat with <span data-bind="text: conversation().to().username"></span></div>
<div id="chat" style="height: 5em;max-height: 200px;overflow:scroll" data-bind="foreach: conversation().messages()">
<div data-bind="text: messageFormatted"></div>
</div>
<form class="form-horizontal" data-bind="submit: conversation().send">
<textarea data-bind="value: conversation().draft"></textarea>
<button class="btn btn-primary" type="submit">Send</button>
</form>
</div>
</div>
<div class="alert alert-warning">
<h5>Notifications</h5>
<ul data-bind="foreach: notifications">
<li data-bind="text: notification"></li>
</ul>
</div>
</div>
</div>
<div id="trade-dialog" class="modal hide fade" tabindex="-1">
<div class="modal-body">
<div>Chat with <span data-bind="text: conversation().to().username"></span></div>
<div id="chat" style="height: 5em;max-height: 200px;overflow:scroll" data-bind="foreach: conversation().messages()">
<div data-bind="text: messageFormatted"></div>
</div>
<form class="form-horizontal" data-bind="submit: conversation().send">
<textarea data-bind="value: conversation().draft"></textarea>
<button class="btn btn-primary" type="submit">Send</button>
</form>
</div>
</div>
<div class="alert alert-warning">
<h5>Notifications</h5>
<ul data-bind="foreach: notifications">
<li data-bind="text: notification"></li>
</ul>
</div>
</div>
</div>
<!-- 3rd party -->
<script src="resources/js/jquery/jquery.js"></script>
<script src="resources/js/bootstrap/js/bootstrap.js"></script>
<script src="resources/js/knockout/knockout.js"></script>
<script src="resources/js/sockjs/sockjs.js"></script>
<script src="resources/js/stomp/lib/stomp.js"></script>
<!-- 3rd party -->
<script src="resources/js/jquery/jquery.js"></script>
<script src="resources/js/bootstrap/js/bootstrap.js"></script>
<script src="resources/js/knockout/knockout.js"></script>
<script src="resources/js/sockjs/sockjs.js"></script>
<script src="resources/js/stomp/lib/stomp.js"></script>
<!-- application -->
<script src="resources/js/message.js"></script>
<script type="text/javascript">
(function() {
var socket = new SockJS('/messages');
var stompClient = Stomp.over(socket);
<!-- application -->
<script src="resources/js/message.js"></script>
<script type="text/javascript">
(function() {
var socket = new SockJS('/messages');
var stompClient = Stomp.over(socket);
var appModel = new ApplicationModel(stompClient);
ko.applyBindings(appModel);
var appModel = new ApplicationModel(stompClient);
ko.applyBindings(appModel);
appModel.connect();
appModel.connect();
})();
</script>
</div>
</body>
})();
</script>
</div>
</body>
</html>

View File

@@ -1,124 +1,124 @@
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-3.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title layout:title-pattern="$DECORATOR_TITLE - $CONTENT_TITLE">SecureMail</title>
<link rel="icon" type="image/x-icon" th:href="@{/resources/img/favicon.ico}" href="../static/img/favicon.ico"/>
<link th:href="@{/resources/css/bootstrap.css}" href="../static/css/bootstrap.css" rel="stylesheet"></link>
<style type="text/css">
/* Sticky footer styles
-------------------------------------------------- */
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title layout:title-pattern="$DECORATOR_TITLE - $CONTENT_TITLE">SecureMail</title>
<link rel="icon" type="image/x-icon" th:href="@{/resources/img/favicon.ico}" href="../static/img/favicon.ico"/>
<link th:href="@{/resources/css/bootstrap.css}" href="../static/css/bootstrap.css" rel="stylesheet"></link>
<style type="text/css">
/* Sticky footer styles
-------------------------------------------------- */
html,
body {
height: 100%;
/* The html and body elements cannot have any padding or margin. */
}
html,
body {
height: 100%;
/* The html and body elements cannot have any padding or margin. */
}
/* Wrapper for page content to push down footer */
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
/* Negative indent footer by it's height */
margin: 0 auto -60px;
}
/* Wrapper for page content to push down footer */
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
/* Negative indent footer by it's height */
margin: 0 auto -60px;
}
/* Set the fixed height of the footer here */
#push,
#footer {
height: 60px;
}
#footer {
background-color: #f5f5f5;
}
/* Set the fixed height of the footer here */
#push,
#footer {
height: 60px;
}
#footer {
background-color: #f5f5f5;
}
/* Lastly, apply responsive CSS fixes as necessary */
@media (max-width: 767px) {
#footer {
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
}
/* Lastly, apply responsive CSS fixes as necessary */
@media (max-width: 767px) {
#footer {
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
}
/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */
/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */
.container {
width: auto;
max-width: 680px;
}
.container .credit {
margin: 20px 0;
text-align: center;
}
a {
color: green;
}
.navbar-form {
margin-left: 1em;
}
</style>
<link th:href="@{resources/css/bootstrap-responsive.css}" href="/static/css/bootstrap-responsive.css" rel="stylesheet"></link>
.container {
width: auto;
max-width: 680px;
}
.container .credit {
margin: 20px 0;
text-align: center;
}
a {
color: green;
}
.navbar-form {
margin-left: 1em;
}
</style>
<link th:href="@{resources/css/bootstrap-responsive.css}" href="/static/css/bootstrap-responsive.css" rel="stylesheet"></link>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div id="wrap">
<div class="navbar navbar-inverse navbar-static-top">
<div class="navbar-inner">
<div class="container">
<a class="brand" th:href="@{/}"><img th:src="@{/resources/img/logo.png}" alt="Spring Security Sample"/></a>
<body>
<div id="wrap">
<div class="navbar navbar-inverse navbar-static-top">
<div class="navbar-inner">
<div class="container">
<a class="brand" th:href="@{/}"><img th:src="@{/resources/img/logo.png}" alt="Spring Security Sample"/></a>
<div class="nav-collapse collapse"
th:with="currentUser=${#httpServletRequest.userPrincipal?.principal}">
<div th:if="${currentUser != null}">
<form class="navbar-form pull-right" th:action="@{/logout}" method="post">
<input type="submit" value="Log out" />
</form>
<p class="navbar-text pull-right" th:text="${currentUser.firstName}">
sample_user
</p>
</div>
<ul class="nav">
<li><a th:href="@{/}">IM</a></li>
<li><a th:href="@{/h2/}">H2</a></li>
</ul>
th:with="currentUser=${#httpServletRequest.userPrincipal?.principal}">
<div th:if="${currentUser != null}">
<form class="navbar-form pull-right" th:action="@{/logout}" method="post">
<input type="submit" value="Log out" />
</form>
<p class="navbar-text pull-right" th:text="${currentUser.firstName}">
sample_user
</p>
</div>
<ul class="nav">
<li><a th:href="@{/}">IM</a></li>
<li><a th:href="@{/h2/}">H2</a></li>
</ul>
</div>
</div>
</div>
</div>
<!-- Begin page content -->
<div class="container">
<div class="alert alert-success"
th:if="${globalMessage}"
th:text="${globalMessage}">
Some Success message
</div>
<div layout:fragment="content">
Fake content
</div>
</div>
</div>
</div>
</div>
<!-- Begin page content -->
<div class="container">
<div class="alert alert-success"
th:if="${globalMessage}"
th:text="${globalMessage}">
Some Success message
</div>
<div layout:fragment="content">
Fake content
</div>
</div>
<div id="push"><!-- --></div>
</div>
<div id="push"><!-- --></div>
</div>
<div id="footer">
<div class="container">
<p class="muted credit">Visit the <a href="http://spring.io/spring-security">Spring Security</a> site for more <a href="https://github.com/spring-projects/spring-security/blob/master/samples/">samples</a>.</p>
</div>
</div>
</body>
<div id="footer">
<div class="container">
<p class="muted credit">Visit the <a href="http://spring.io/spring-security">Spring Security</a> site for more <a href="https://github.com/spring-projects/spring-security/blob/master/samples/">samples</a>.</p>
</div>
</div>
</body>
</html>