SEC-2194: Add Java Config samples

This commit is contained in:
Rob Winch
2013-08-01 14:14:18 -05:00
parent 36418b964d
commit 388a4dd9db
435 changed files with 71210 additions and 51 deletions

View File

@@ -0,0 +1,3 @@
Manifest-Version: 1.0
Class-Path:

View File

@@ -0,0 +1,48 @@
package org.springframework.security.samples.config;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.security.samples.data.Message;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
@EnableJpaRepositories("org.springframework.security.samples.data")
public class DataConfiguration {
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.HSQL).build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.HSQL);
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(Message.class.getPackage().getName());
factory.setDataSource(dataSource());
return factory;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright 2002-2013 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 org.springframework.security.samples.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
/**
* No customizations of {@link AbstractSecurityWebApplicationInitializer} are necessary.
*
* @author Rob Winch
*/
public class MessageSecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}

View File

@@ -0,0 +1,34 @@
package org.springframework.security.samples.config;
import javax.servlet.Filter;
import org.springframework.core.annotation.Order;
import org.springframework.security.samples.mvc.config.WebMvcConfiguration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.opensymphony.sitemesh.webapp.SiteMeshFilter;
@Order(1)
public class MessageWebApplicationInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebMvcConfiguration.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {
return new Filter[] { new SiteMeshFilter() };
}
}

View File

@@ -0,0 +1,12 @@
package org.springframework.security.samples.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
@Configuration
@ComponentScan(value = "org.springframework.security.samples.config", excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, value = RootConfiguration.class))
public class RootConfiguration {
}

View File

@@ -0,0 +1,59 @@
package org.springframework.security.samples.data;
import java.util.Calendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Version;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotEmpty(message = "Message is required.")
private String text;
@NotEmpty(message = "Summary is required.")
private String summary;
@Version
private Calendar created = Calendar.getInstance();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Calendar getCreated() {
return created;
}
public void setCreated(Calendar created) {
this.created = created;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}

View File

@@ -0,0 +1,12 @@
package org.springframework.security.samples.data;
import org.springframework.data.repository.CrudRepository;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
public interface MessageRepository extends CrudRepository<Message, Long> {
@Transactional
@PreAuthorize("hasRole('ROLE_ADMIN')")
<S extends Message> S save(S entity);
}

View File

@@ -0,0 +1,13 @@
package org.springframework.security.samples.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class DefaultController {
@RequestMapping("/**")
public String notFound() {
return "errors/404";
}
}

View File

@@ -0,0 +1,52 @@
package org.springframework.security.samples.mvc;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.samples.data.Message;
import org.springframework.security.samples.data.MessageRepository;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/")
public class MessageController {
private MessageRepository messageRepository;
@Autowired
public MessageController(MessageRepository messageRepository) {
this.messageRepository = messageRepository;
}
@RequestMapping
public ModelAndView list() {
Iterable<Message> messages = messageRepository.findAll();
return new ModelAndView("messages/inbox", "messages", messages);
}
@RequestMapping("{id}")
public ModelAndView view(@PathVariable("id") Message message) {
return new ModelAndView("messages/show", "message", message);
}
@RequestMapping(params="form", method=RequestMethod.GET)
public String createForm(@ModelAttribute Message message) {
return "messages/compose";
}
@RequestMapping(method=RequestMethod.POST)
public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) {
if(result.hasErrors()) {
return new ModelAndView("messages/compose");
}
message = messageRepository.save(message);
redirect.addFlashAttribute("globalMessage", "Successfully created a new message");
return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
}
}

View File

@@ -0,0 +1,49 @@
package org.springframework.security.samples.mvc.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.Ordered;
import org.springframework.data.repository.support.DomainClassConverter;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@EnableWebMvc
@ComponentScan("org.springframework.security.samples.mvc")
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Autowired
private FormattingConversionService mvcConversionService;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/login").setViewName("login");
registry.addViewController("/errors/404").setViewName("errors/404");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);
}
@Bean
public InternalResourceViewResolver jspxViewResolver() {
InternalResourceViewResolver result = new InternalResourceViewResolver();
result.setPrefix("/WEB-INF/views/");
result.setSuffix(".jspx");
return result;
}
@Bean
public DomainClassConverter<?> domainClassConverter() {
return new DomainClassConverter<FormattingConversionService>(mvcConversionService);
}
}