Rename package

This commit is contained in:
David Morley
2016-04-07 06:17:57 -05:00
parent 44eca5ba04
commit 9630170b03
30 changed files with 54 additions and 170 deletions
@@ -0,0 +1,54 @@
package com.baeldung.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;
@Component
@Aspect
public class LoggingAspect {
private static Logger logger = Logger.getLogger(LoggingAspect.class.getName());
private ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("[yyyy-mm-dd hh:mm:ss:SSS]");
}
};
@Pointcut("@target(org.springframework.stereotype.Repository)")
public void repositoryMethods() {
}
@Pointcut("@annotation(com.baeldung.aop.annotations.Loggable)")
public void loggableMethods() {
}
@Pointcut("@args(com.baeldung.aop.annotations.Entity)")
public void methodsAcceptingEntities() {
}
@Before("repositoryMethods()")
public void logMethodCall(JoinPoint jp) {
String methodName = jp.getSignature().getName();
logger.info(sdf.get().format(new Date()) + methodName);
}
@Before("loggableMethods()")
public void logMethod(JoinPoint jp) {
String methodName = jp.getSignature().getName();
logger.info("Executing method: " + methodName);
}
@Before("methodsAcceptingEntities()")
public void logMethodAcceptionEntityAnnotatedBean(JoinPoint jp) {
logger.info("Accepting beans with @Entity annotation: " + jp.getArgs()[0]);
}
}
@@ -0,0 +1,32 @@
package com.baeldung.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
@Aspect
@Component
public class PerformanceAspect {
private static Logger logger = Logger.getLogger(PerformanceAspect.class.getName());
@Pointcut("within(@org.springframework.stereotype.Repository *)")
public void repositoryClassMethods() {
}
@Around("repositoryClassMethods()")
public Object measureMethodExecutionTime(ProceedingJoinPoint pjp) throws Throwable {
long start = System.nanoTime();
Object retval = pjp.proceed();
long end = System.nanoTime();
String methodName = pjp.getSignature().getName();
logger.info("Execution of " + methodName + " took " + TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
return retval;
}
}
@@ -0,0 +1,39 @@
package com.baeldung.aop;
import com.baeldung.events.FooCreationEvent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class PublishingAspect {
private ApplicationEventPublisher eventPublisher;
@Autowired
public void setEventPublisher(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
@Pointcut("@target(org.springframework.stereotype.Repository)")
public void repositoryMethods() {
}
@Pointcut("execution(* *..create*(Long,..))")
public void firstLongParamMethods() {
}
@Pointcut("repositoryMethods() && firstLongParamMethods()")
public void entityCreationMethods() {
}
@AfterReturning(value = "entityCreationMethods()", returning = "entity")
public void logMethodCall(JoinPoint jp, Object entity) throws Throwable {
eventPublisher.publishEvent(new FooCreationEvent(entity));
}
}
@@ -0,0 +1,11 @@
package com.baeldung.aop.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Entity {
}
@@ -0,0 +1,11 @@
package com.baeldung.aop.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Loggable {
}
@@ -0,0 +1,22 @@
package com.baeldung.dao;
import com.baeldung.aop.annotations.Loggable;
import com.baeldung.model.Foo;
import org.springframework.stereotype.Repository;
@Repository
public class FooDao {
public String findById(Long id) {
return "Bazz";
}
@Loggable
public Foo create(Long id, String name) {
return new Foo(id, name);
}
public Foo merge(Foo foo) {
return foo;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.dialect;
import java.util.HashSet;
import java.util.Set;
import com.baeldung.processor.NameProcessor;
import org.thymeleaf.dialect.AbstractDialect;
import org.thymeleaf.processor.IProcessor;
public class CustomDialect extends AbstractDialect {
@Override
public String getPrefix() {
return "custom";
}
@Override
public Set<IProcessor> getProcessors() {
final Set<IProcessor> processors = new HashSet<IProcessor>();
processors.add(new NameProcessor());
return processors;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.events;
import org.springframework.context.ApplicationEvent;
public class FooCreationEvent extends ApplicationEvent {
public FooCreationEvent(Object source) {
super(source);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.events;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.util.logging.Logger;
@Component
public class FooCreationEventListener implements ApplicationListener<FooCreationEvent> {
private static Logger logger = Logger.getLogger(FooCreationEventListener.class.getName());
@Override
public void onApplicationEvent(FooCreationEvent event) {
logger.info("Created foo instance: " + event.getSource().toString());
}
}
@@ -0,0 +1,51 @@
package com.baeldung.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private long id;
private String name;
private String contactNumber;
public Employee() {
super();
}
public Employee(final long id, final String name, final String contactNumber) {
this.id = id;
this.name = name;
this.contactNumber = contactNumber;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(final String contactNumber) {
this.contactNumber = contactNumber;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", contactNumber=" + contactNumber + "]";
}
}
@@ -0,0 +1,19 @@
package com.baeldung.model;
import com.baeldung.aop.annotations.Entity;
@Entity
public class Foo {
private Long id;
private String name;
public Foo(Long id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Foo{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}
@@ -0,0 +1,32 @@
package com.baeldung.model;
public class User {
private String firstname;
private String lastname;
private String emailId;
public String getFirstname() {
return firstname;
}
public void setFirstname(final String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(final String lastname) {
this.lastname = lastname;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(final String emailId) {
this.emailId = emailId;
}
}
@@ -0,0 +1,23 @@
package com.baeldung.processor;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor;
public class NameProcessor extends AbstractTextChildModifierAttrProcessor {
public NameProcessor() {
super("name");
}
@Override
protected String getText(final Arguments arguements, final Element elements, final String attributeName) {
return "Hello, " + elements.getAttributeValue(attributeName) + "!";
}
@Override
public int getPrecedence() {
return 1000;
}
}
@@ -0,0 +1,93 @@
package com.baeldung.spring.web.config;
import java.util.HashSet;
import java.util.Set;
import com.baeldung.dialect.CustomDialect;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
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;
import org.springframework.web.servlet.view.JstlView;
import org.thymeleaf.dialect.IDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
@EnableWebMvc
@Configuration
public class ClientWebConfig extends WebMvcConfigurerAdapter {
public ClientWebConfig() {
super();
}
// API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver thymeleafViewResolver() {
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(1);
return viewResolver;
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
@Bean
@Description("Thymeleaf template resolver serving HTML 5")
public ServletContextTemplateResolver templateResolver() {
final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
}
@Bean
@Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
final Set<IDialect> dialects = new HashSet<>();
dialects.add(new CustomDialect());
templateEngine.setAdditionalDialects(dialects);
return templateEngine;
}
@Bean
@Description("Spring message resolver")
public MessageSource messageSource() {
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
@@ -0,0 +1,52 @@
package com.baeldung.spring.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
public class ContentManagementWebConfig extends WebMvcConfigurerAdapter {
public ContentManagementWebConfig() {
super();
}
// API
@Override
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false).
favorParameter(true).
parameterName("mediaType").
ignoreAcceptHeader(true).
useJaf(false).
defaultContentType(MediaType.APPLICATION_JSON).
mediaType("xml", MediaType.APPLICATION_XML).
mediaType("json", MediaType.APPLICATION_JSON);
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
}
@@ -0,0 +1,50 @@
package com.baeldung.spring.web.config;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class MainWebAppInitializer implements WebApplicationInitializer {
private static final String TMP_FOLDER = "C:/Users/ivan/Desktop/tmp";
private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB
/**
* Register and configure all Servlet container components necessary to power the web application.
*/
@Override
public void onStartup(final ServletContext sc) throws ServletException {
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.scan("com.baeldung.spring.web.config");
// root.getEnvironment().setDefaultProfiles("embedded");
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
// Handles requests into the application
final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
// final MultipartConfigElement multipartConfigElement = new
// MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE,
// MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2);
//
// appServlet.setMultipartConfig(multipartConfigElement);
final Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
}
}
}
@@ -0,0 +1,72 @@
package com.baeldung.spring.web.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
import org.springframework.web.servlet.view.XmlViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan("com.baeldung.web")
public class WebConfig extends WebMvcConfigurerAdapter {
public WebConfig() {
super();
}
// @Bean
// public StandardServletMultipartResolver multipartResolver() {
// return new StandardServletMultipartResolver();
// }
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
final CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(100000);
return multipartResolver;
}
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver internalResourceViewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
bean.setOrder(2);
return bean;
}
@Bean
public ViewResolver xmlViewResolver() {
final XmlViewResolver bean = new XmlViewResolver();
bean.setLocation(new ClassPathResource("views.xml"));
bean.setOrder(1);
return bean;
}
@Bean
public ViewResolver resourceBundleViewResolver() {
final ResourceBundleViewResolver bean = new ResourceBundleViewResolver();
bean.setBasename("views");
bean.setOrder(0);
return bean;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BeanA {
@Autowired
private BeanB b;
public BeanA() {
super();
}
}
@@ -0,0 +1,12 @@
package com.baeldung.web;
import org.springframework.stereotype.Component;
@Component
public class BeanB {
public BeanB() {
super();
}
}
@@ -0,0 +1,46 @@
package com.baeldung.web.controller;
import java.util.HashMap;
import java.util.Map;
import com.baeldung.model.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
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.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class EmployeeController {
Map<Long, Employee> employeeMap = new HashMap<>();
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("employeeHome", "employee", new Employee());
}
@RequestMapping(value = "/employee/{Id}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET)
public @ResponseBody Employee getEmployeeById(@PathVariable final long Id) {
return employeeMap.get(Id);
}
@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String submit(@ModelAttribute("employee") final Employee employee, final BindingResult result, final ModelMap model) {
if (result.hasErrors()) {
return "error";
}
model.addAttribute("name", employee.getName());
model.addAttribute("contactNumber", employee.getContactNumber());
model.addAttribute("id", employee.getId());
employeeMap.put(employee.getId(), employee);
return "employeeView";
}
}
@@ -0,0 +1,32 @@
package com.baeldung.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileUploadController {
@RequestMapping(value = "/fileUpload", method = RequestMethod.GET)
public String displayForm() {
return "fileUploadForm";
}
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String submit(@RequestParam("file") final MultipartFile file, final ModelMap modelMap) {
modelMap.addAttribute("file", file);
return "fileUploadView";
}
@RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST)
public String submit(@RequestParam("files") final MultipartFile[] files, final ModelMap modelMap) {
modelMap.addAttribute("files", files);
return "fileUploadView";
}
}
@@ -0,0 +1,31 @@
package com.baeldung.web.controller;
import com.baeldung.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/")
public class UserController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showForm(final Model model) {
final User user = new User();
user.setFirstname("John");
user.setLastname("Roy");
user.setEmailId("John.Roy@gmail.com");
model.addAttribute("user", user);
return "index";
}
@RequestMapping(value = "/processForm", method = RequestMethod.POST)
public String processForm(@ModelAttribute(value = "user") final User user, final Model model) {
// Insert User into DB
model.addAttribute("name", user.getFirstname() + " " + user.getLastname());
return "hello";
}
}