SpringMVC project not started with out errors and strack trace - spring-mvc

Some body can tell me, where or what I do wrong?
Here is all project: GitHub
In project is used Spring 3.2.0.RELEASE
And Java configuration, with out XML config.
IDE run Tomcat and then write: artifact not deployed. See previous errors. But I've can't see errors.
Here is output of IntelliJ IDEA:
2014.5.2 09:56:26 org.apache.catalina.core.AprLifecycleListener init
INFO: Loaded APR based Apache Tomcat Native library 1.1.27 using APR version 1.4.6.
2014.5.2 09:56:26 org.apache.catalina.core.AprLifecycleListener init
INFO: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2014.5.2 09:56:26 org.apache.catalina.core.AprLifecycleListener initializeSSL
INFO: OpenSSL successfully initialized (OpenSSL 1.0.1d 5 Feb 2013)
2014.5.2 09:56:27 org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-apr-8080"]
2014.5.2 09:56:27 org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-apr-8009"]
2014.5.2 09:56:27 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1394 ms
2014.5.2 09:56:27 org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
2014.5.2 09:56:27 org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.37
2014.5.2 09:56:27 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-apr-8080"]
2014.5.2 09:56:27 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-apr-8009"]
2014.5.2 09:56:27 org.apache.catalina.startup.Catalina start
INFO: Server startup in 84 ms
Connected to server
[2014-02-05 09:56:27,627] Artifact web:war exploded: Artifact is being deployed, please wait...
2014.5.2 09:56:27 org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(C:\Users\Admin\Desktop\web\target\web\WEB-INF\lib\servlet-api-2.5.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
2014.5.2 09:56:29 org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
2014.5.2 09:56:29 org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [] startup failed due to previous errors
[2014-02-05 09:56:29,785] Artifact web:war exploded: Error during artifact deployment. See server log for details.
2014.5.2 09:56:37 org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory D:\apache-tomcat-7.0.37\webapps\manager
Tomcat Catalina log:
2014.5.2 09:56:26 org.apache.catalina.core.AprLifecycleListener init
SEVERE: Error listenerStart
2014.5.2 09:56:29 org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [] startup failed due to previous errors
2014.5.2 09:56:37 org.apache.catalina.startup.HostConfig deployDirectory
Here is configuration classes:
Initializer.java:
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Order(1)
public class Initializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebAppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
RootConfig.java:
package lv.intrade.web.init;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan("lv.intrade.web")
#PropertySource("classpath:application.properties")
#EnableJpaRepositories(basePackages = {"lv.intrade.web"})
public class RootConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
//
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
//
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
//
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan(new String[]{"lv.intrade.web"});
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
jpaProperties.put("hibernate.format_sql", true);
jpaProperties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
}
WebAppConfig.java:
package lv.intrade.web.init;
import lv.intrade.web.service.Dictionary;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import java.util.Locale;
#Configuration
#EnableWebMvc
#ComponentScan("lv.intrade")
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public MessageSource configureMessageSource() {
AbstractMessageSource messageSource = new Dictionary();
return messageSource;
}
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver lr = new SessionLocaleResolver();
lr.setDefaultLocale(Locale.ENGLISH);
return lr;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor localeChangeInterceptor=new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
// #Bean
// public HandlerMapping handlerMapping() {
// final LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
// interceptor.setParamName("lang");
//
// final DefaultAnnotationHandlerMapping ret = new DefaultAnnotationHandlerMapping();
// ret.setInterceptors(new Object[] { interceptor });
// return ret;
// }
}

Try this solution
Also check whether you have placed servlet-api-2.5.jar correctly.
Error log is not complete. Add complete log.

I found problem!
I have wrong path till application.properties file.
When I fix first problem, I found problem in my AbstractMessageSource class
End last problem, when I still have not comment back my jpaTransactionManager - #EnableJpaRepositories - not working.
Now all work fine!
Thank you for all for help and ideas! Many thanks for Orchid for good idea, but with servlet-api-2.5 all is ok! :)

Related

No mapping found for HTTP request in DispatcherServlet

I tried to reach my jsp page and for some reason i got the error message
Hibernate: select person0_.pid as pid1_0_, person0_.age as age2_0_, person0_.city as city3_0_, person0_.gender as gender4_0_, person0_.password as password5_0_, person0_.username as username6_0_ from person person0_ order by person0_.pid
2016-10-04 13:49:53.090 WARN 13276 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound : No mapping found for HTTP request with URI [/WEB-INF/view/personform.jsp] in DispatcherServlet with name 'dispatcherServlet'
'
PersonController:
#Controller
public class PersonController {
#Autowired
private IPersonService personService;
#Autowired
private MessageSource messageSource;
#Autowired
private LocaleResolver localeResolver;
//#RequestMapping(value="personform")
public ModelAndView user(){
ModelAndView mv = new ModelAndView("personform","person",new Person());
setPageData(mv.getModelMap());
return mv;
}
Appconfig.java:
package App.config;
import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#ComponentScan("App")
#Import(DBConfig.class)
#EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("/WEB-INF/i18/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleResolver localeResolver(){
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setDefaultLocale(new Locale("en"));
resolver.setCookieName("myLocaleCookie");
resolver.setCookieMaxAge(4800);
return resolver;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("mylocale");
registry.addInterceptor(interceptor);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/app-resources/**").addResourceLocations("/resources/");
}
}
just in case, if it needed - build.gradle:
group 'mbti'
version '1.0-SNAPSHOT'
buildscript {
repositories {
maven { url "http://repo.spring.io/libs-snapshot" }
mavenLocal()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.0.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'
sourceCompatibility = 1.8
repositories {
mavenCentral()
maven { url "http://repo.spring.io/libs-snapshot" }
}
dependencies {
compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.3.3.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.3.3.RELEASE'
compile group: 'mysql', name: 'mysql-connector-java', version: '5.1.31'
compile group: 'org.apache.commons', name: 'commons-dbcp2', version: '2.1.1'
compile group: 'jstl', name: 'jstl', version: '1.2'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: '1.3.3.RELEASE'
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-el', version: '8.0.32'
testCompile group: 'junit', name: 'junit', version: '4.11'
}
task wrapper(type: Wrapper) {
gradleVersion = '1.11'
}
In your controller, uncomment the #requestMapping annotation and set the value like this:
#RequestMapping(value="/personform")
Your view resolver cannot find a correct mapping without the above #requestMapping annotation.
Note that jsp page under WEB-INF directory cannot be directly accessed by typing the uri in the browser, you have to use controller or servlet (in your case it is controller) to access it.

WebApplicationContextUtils.getWebApplicationContext(ServletContext) returns NULL from ServletContextListener

I am unable to get WebApplicationContext inside ServletContextListener. I searched for solution but non of them are working for me. I would appreciate if any one can help. Thanks in advance.
Below are code snippets-
My AppConfig class:
package in.andonsystem.config;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
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.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"in.andonsystem"})
public class AppConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean
public MessageSource messageSource(){
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
}
My AppInitializer Class.
package in.andonsystem.config;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class Appinitializer implements WebApplicationInitializer{
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
rootContext.setServletContext(servletContext);
// Manage the lifecycle of the root application context
servletContext.addListener(new ContextLoaderListener(rootContext));
rootContext.refresh();
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
My ContextListener Class:
package in.andonsystem.config;
import com.mysql.jdbc.AbandonedConnectionCleanupThread;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
#WebListener
public class ContextListener implements ServletContextListener{
private Logger logger = Logger.getLogger("ContextListener");
#Override
public void contextInitialized(ServletContextEvent sce) {
logger.info("contextInitialized()");
WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
System.out.println("Is rootContext null:" + (rootContext == null));
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
stdout output is always coming true.
What am I missing?
Finally came up with the solution. The problem was that ServletContextListener was being loaded before ContextLoaderListener and Therefore a WebApplicationContext returned was null because ContextLoaderListener must be loaded before ServletContextListener in order to get the rootContext.
I removed #WebListener annotation from my ContextListener and added this Listener Programatically in onStartup method of AppInitializer after Adding ContextLoaderListener.
Now my ContextListener without #WebListener annotation is:
public class ContextListener implements ServletContextListener{
private Logger logger = Logger.getLogger("ContextListener");
#Override
public void contextInitialized(ServletContextEvent sce) {
logger.info("contextInitialized()");
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
System.out.println("Is rootContext null:" + (rootContext == null));
}
#Override
public void contextDestroyed(ServletContextEvent sce) {
logger.info("contextDestroyed()");
}
}
and AppInitializer is :
public class Appinitializer implements WebApplicationInitializer{
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
rootContext.setServletContext(servletContext);
// Manage the lifecycle of the root application context
servletContext.addListener(new ContextLoaderListener(rootContext));
//ContextListener must be added after ContextLoaderListener
servletContext.addListener(ContextListener.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher =
servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
Looks basically correct, but I think you should remove the following 2 lines from your initializer class:
rootContext.setServletContext(servletContext);
and
rootContext.refresh();

How configure spring multiple profiles databases javaconfig

How to start a project with spring MVC with profiles, multiple connections to the database .. and run tests with gradle?
Some time ago I'm trying to make these settings and I'm not getting what I'm doing wrong?
(Sorry for my english I'm using google translate.)
Here are my settings
Dev Settings
db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost:5432/nextinfoerp
db.username=myuser
db.password=mypass
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.format_sql =true
entitymanager.packages.to.scan=br.com.nextinfo.erp
Test Settings
#Test properties:
db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost:5432/nextinfoerptestdb
db.username=myuser
db.password=mypass
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.format_sql =true
entitymanager.packages.to.scan=br.com.nextinfo.erp
Gradle Settings
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse-wtp'
apply plugin: 'jetty'
sourceCompatibility = 1.8
targetCompatibility = 1.8
ext.springVersion= '4.1.7.RELEASE'
ext.jacksondataTypeHibernate4 ='2.5.3'
ext.easycriteriaVersion ='3.0.0'
ext.hibernateCoreVersion ='4.3.10.Final'
ext.hibernateValidadeVersion ='5.1.3.Final'
ext.springDataVersion ='1.8.0.RELEASE'
ext.mysqlConnectionVersion= '5.1.6'
ext.servletApiVersion ='2.5'
dependencies {
testCompile 'junit:junit:4.12'
compile project(':utils')
compile"javax.servlet:jstl:1.2"
compile "org.thymeleaf:thymeleaf-spring4:2.1.2.RELEASE"
compile group: 'javax.servlet', name: 'servlet-api', version: servletApiVersion
compile group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '1.2.9'
compile group: 'org.springframework.security', name: 'spring-security-web', version: '4.0.2.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-core', version: '4.0.2.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-config', version: '4.0.2.RELEASE'
compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity4:2.1.2.RELEASE'
compile group: 'org.springframework', name: 'spring-context', version: springVersion
compile group: 'org.springframework', name: 'spring-web', version: springVersion
compile group: 'org.springframework', name: 'spring-test', version: springVersion
compile group: 'org.springframework', name: 'spring-webmvc', version: springVersion
compile group: 'org.springframework.data', name: 'spring-data-jpa', version:springDataVersion
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate4', version: jacksondataTypeHibernate4
compile "org.postgresql:postgresql:9.3-1100-jdbc4"
compile group: 'uaihebert.com', name: 'EasyCriteria', version: easycriteriaVersion
compile group: 'org.hibernate', name: 'hibernate-validator', version: hibernateValidadeVersion
compile group: 'org.hibernate', name: 'hibernate-core', version: hibernateCoreVersion
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: hibernateCoreVersion
}
class for database configuration
package br.com.nextinfo.erp.web.config;
import java.util.Properties;
import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#Profile("dev")
#EnableJpaRepositories("br.com.nextinfo.erp.web.dao")
#PropertySource("classpath:dev.properties")
public class DevProfileDatabase extends AbstractDatabaseConfig implements PerfilDataBase {
private static final Logger log = LoggerFactory.getLogger(DevProfileDatabase.class);
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
log.warn("settings data Source "+this.getClass().getCanonicalName());
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
protected Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
return properties;
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
txManager.getEntityManagerFactory().getMetamodel().getEntities();
return txManager;
}
#Bean
public EntityManagerFactory entityManagerFactory() {
log.warn("settings data entity manager "+this.getClass().getCanonicalName());
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
}
My class incializer
import javax.servlet.Filter;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Order(1)
public class Inicializer extends AbstractAnnotationConfigDispatcherServletInitializer implements WebApplicationInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {ThymeleafConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ThymeleafConfig.class,ProdProfileDatabase.class,DevProfileDatabase.class,TestProfileDatabase.class};
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Filter[] getServletFilters() {
return new Filter[] { };
}
#Override
protected WebApplicationContext createRootApplicationContext() {
WebApplicationContext context =
(WebApplicationContext)super.createRootApplicationContext();
((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles("dev");
return context;
}
I'm using spring-data
the error
Servlet.init() for servlet dispatcher threw exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [br/com/nextinfo/erp/web/config/ProdProfileDatabase.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.PlatformTransactionManager]: Factory method 'transactionManager' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [br/com/nextinfo/erp/web/config/ProdProfileDatabase.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:664)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:536)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:490)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
If I remove the annotation profiles and classes that use the annotation inicializer function normally,
How do I solve this?
I solved the problem by moving the database configuration classes to load along with the root settings
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {ThymeleafConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ThymeleafConfig.class,ProdProfileDatabase.class,DevProfileDatabase.class,TestPr ofileDatabase.class};
}
I did this exchange
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {ProdProfileDatabase.class,DevProfileDatabase.class,TestPr ofileDatabase.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ThymeleafConfig.class};
}

Asynchronous Servlet with Embedded Jetty

I want to build a real simple example for invoking a asynchronous servlet in an embedded Jetty server. When I try to start a Runnable from the AsyncContext of the Request, I get a NullPointerException.
This is the server code:
public static void main(String[] args) throws Exception {
Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
ServletHolder holder = handler.addServletWithMapping(AsyncServlet.class, "/*");
holder.setAsyncSupported(true);
server.start();
server.join();
}
This is the servlet code:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
final AsyncContext ctxt = req.startAsync();
ctxt.start(() -> {
ctxt.complete();
});
}
And this is the error with stack trace:
java.lang.NullPointerException
at org.eclipse.jetty.server.AsyncContextState$2.run(AsyncContextState.java:168)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:620)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:540)
at java.lang.Thread.run(Thread.java:745)
Maybe the server needs any additional configuration. Any suggestions?
Addition: The same servlet runs without any change in an embedded tomcat.
Don't use ServletHandler directly, that's an internal class that ServletContextHandler creates / uses / manages.
Here's a modification of your example, that sets up the servlet context properly.
package jetty;
import java.io.IOException;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class EmbeddedAsyncServer
{
public static class EmbeddedAsyncServlet extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
final AsyncContext ctxt = req.startAsync();
ctxt.start(new Runnable()
{
#Override
public void run()
{
System.err.println("In AsyncContext / Start / Runnable / run");
ctxt.complete();
}
});
}
}
public static void main(String[] args) throws Exception
{
Server server = new Server(9090);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
ServletHolder asyncHolder = context.addServlet(EmbeddedAsyncServlet.class,"/async");
asyncHolder.setAsyncSupported(true);
server.setHandler(context);
server.start();
server.join();
}
}
Access http://localhost:9090/async and you'll see the following output
2014-12-29 13:18:57.075:INFO::main: Logging initialized #69ms
2014-12-29 13:18:57.131:INFO:oejs.Server:main: jetty-9.2.6.v20141205
2014-12-29 13:18:57.156:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler#65123c41{/,null,AVAILABLE}
2014-12-29 13:18:57.169:INFO:oejs.ServerConnector:main: Started ServerConnector#722b302{HTTP/1.1}{0.0.0.0:9090}
2014-12-29 13:18:57.169:INFO:oejs.Server:main: Started #166ms
In AsyncContext / Start / Runnable / run

Not able to call ejb on same machine using client class

I am new to EJB. I tried an example from java_for_web_with_servlets_jsp_and_ejb book. The following code creates an session been called Adder which adds two integers:
Adder.java:
package com.brainysoftware.ejb;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
public interface Adder extends EJBObject{
public int add(int a,int b) throws RemoteException;
}
AdderBean.java
package com.brainysoftware.ejb;
import java.rmi.RemoteException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
public class AdderBean implements SessionBean{
public int add(int a, int b){
System.out.println("From AdderBean");
return (a+b);
}
#Override
public void ejbActivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void ejbPassivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void ejbRemove() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void setSessionContext(SessionContext arg0) throws EJBException,
RemoteException {
// TODO Auto-generated method stub
}
}
AdderHome.java
package com.brainysoftware.ejb;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface AdderHome extends EJBHome{
Adder create() throws RemoteException, CreateException;
}
The deployment descriptor is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar version="3.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd">
<description>Your first EJB application</description>
<display-name>Adder Application</display-name>
<enterprise-beans>
<session>
<ejb-name>Adder</ejb-name>
<home>com.brainysoftware.ejb.AdderHome</home>
<remote>com.brainysoftware.ejb.Adder</remote>
<ejb-class>com.brainysoftware.ejb.AdderBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
I created a jar file of this project and placed the jar in the tomcat's lib.
Now, for the client I created a dynamic web project having the class BeanClient.java that uses the Adder bean:
import java.rmi.RemoteException;
import java.util.Properties;
import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.brainysoftware.ejb.Adder;
import com.brainysoftware.ejb.AdderHome;
import javax.rmi.PortableRemoteObject;
public class BeanClient {
public static void main(String[] args){
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.PROVIDER_URL, "localhost:1099");
try{
InitialContext jnic = new InitialContext(props);
System.out.println("Get context");
Object ref = jnic.lookup("Adder");
System.out.println("Got reference");
AdderHome home = (AdderHome) PortableRemoteObject.narrow(ref,AdderHome.class);
Adder adder = home.create();
System.out.println("Adding 2 and 5:"+adder.add(2,5));
} catch(NamingException e){
System.out.println(e.toString());
} catch(CreateException e){
System.out.println(e.toString());
} catch (RemoteException e) {
System.out.println(e.toString());
}
}
}
On executing this class in eclipse, I get the following error:
Get context
javax.naming.CommunicationException: Could not obtain connection to any of these urls: localhost:1099 and discovery failed with error: javax.naming.CommunicationException: Receive timed out [Root exception is java.net.SocketTimeoutException: Receive timed out] [Root exception is javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]]
Could you please help me out with this?
to look up and ejb firstbale :
you must have an interface and it's implementation.
you have to annotate your interface (#Local ou #Remote)
The implementation must be annotated #statless ou #statful
You have to add on you project a jndi.properties.
your ejb project must be deployed on your server to be easy to look up it.
i have for you an example with jboss here :
https://www.youtube.com/watch?v=mBwgHuBg96g
i hope that my answer is useful pour you

Resources