why spring WebApplicationInitializer StandardContext reload immediately after sever start? - spring

I am using spring WebApplicationInitializer instead of AbstractAnnotationConfigDispatcherServletInitializer with the following code.
public class ApplicationInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Register the Root application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
// Context loader listener
servletContext.addListener(new ContextLoaderListener(rootContext));
// Register the Web application context
AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
mvcContext.register(WebMvcConfig.class);
// Register the Spring dispatcher servlet
DispatcherServlet dispatcherServlet = new DispatcherServlet(mvcContext);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", new CharacterEncodingFilter());
encodingFilter.setInitParameter("encoding", "UTF-8");
encodingFilter.setInitParameter("forceEncoding","true");
encodingFilter.addMappingForUrlPatterns(null, false, "/*");
}
}
The application first start complete then it reload and start again with the following log.
INFO: Initializing Spring root WebApplicationContext
**************************false
Apr 11, 2016 2:58:56 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Apr 11, 2016 2:58:57 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Apr 11, 2016 2:58:57 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Apr 11, 2016 2:58:57 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 18577 ms
Apr 11, 2016 2:59:07 AM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/iamSystem] has started
Apr 11, 2016 2:59:07 AM org.apache.catalina.core.ApplicationContext log
INFO: Destroying Spring FrameworkServlet 'dispatcher'
Apr 11, 2016 2:59:07 AM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Apr 11, 2016 2:59:07 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
WARNING: The web application [iamSystem] registered the JDBC driver [net.sourceforge.jtds.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Apr 11, 2016 2:59:08 AM org.apache.catalina.loader.WebappClassLoaderBase checkStateForResourceLoading
Apr 11, 2016 2:59:12 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Apr 11, 2016 2:59:12 AM org.apache.catalina.core.ApplicationContext log
INFO: Spring WebApplicationInitializers detected on classpath: [com.egen.iamsystem.config.ApplicationInitializer#fd75714, com.egen.iamsystem.config.core.SpringSecurityInitializer#73113f1f]
Apr 11, 2016 2:59:13 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
**************************false
Apr 11, 2016 2:59:21 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Apr 11, 2016 2:59:22 AM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/iamSystem] is completed
if i use AbstractAnnotationConfigDispatcherServletInitializer
public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { AppConfig.class };
// return new Class[] { WebMvcConfig.class };
// return null;
}
// Since we have a single DispatcherServlet here, we can add the WebConfig
// to the root context and make the servlet context empty
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebMvcConfig.class };
// return new Class[] { };
// return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Filter[] getServletFilters() {
return new Filter[] { new DelegatingFilterProxy("springSecurityFilterChain"),
new OpenEntityManagerInViewFilter() };
}
// By default when the DispatcherServlet can't find a handler for a request
// it sends a 404 response. However if its property
// "throwExceptionIfNoHandlerFound" is set to true this exception is raised
// and may be handled with a configured HandlerExceptionResolver
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // ->
// true
if (!done)
throw new RuntimeException();
}
}
it is ok the server start success with only one time
What is the problem?

You are instantiating it twice , that's why it reloads twice :
// Register the Root application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
.
.
.
// Register the Web application context
AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
mvcContext.register(WebMvcConfig.class);

Related

Spring boot #Cron taking a long time(5 min) to start up

have a cron job class which is annotated with #Component.
when I am running the cron job its taking approx 5 min to start up.
the last logs are mentioned above
eligible.coupon.merchant.scheduler.cron=0 * * * * *
Sep 21, 2020 2:59:43 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.17.Final}
Sep 21, 2020 2:59:43 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 21, 2020 2:59:43 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Sep 21, 2020 2:59:44 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle12cDialect
Sep 21, 2020 2:59:45 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [byte[]] overrides previous : org.hibernate.type.BinaryType#1410d645
Sep 21, 2020 2:59:45 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [[B] overrides previous : org.hibernate.type.BinaryType#1410d645
Sep 21, 2020 2:59:45 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [Byte[]] overrides previous : org.hibernate.type.WrapperBinaryType#13908f9c
Sep 21, 2020 2:59:45 PM org.hibernate.type.BasicTypeRegistry register
#Component
public class EligibleMerchantController extends DigitalApiRestServiceBinding implements MerchantSchedulerService {
protected final Logger log = LoggerFactory.getLogger(EligibleMerchantController.class);
#Value("${eligible.coupon.merchant.pagesize}")
Integer defaultPagesize;
#Autowired
EligibleMerchantBusinessService service;
#Override
#Scheduled(cron = "${eligible.coupon.merchant.scheduler.cron}")
public void eligibleMerchantScheduler() {
// my cron job
}
}
#Bean
public TaskScheduler taskScheduler() {
return new ConcurrentTaskScheduler();
}
}
its taking more than 5 min which it shouldnt
removed a property
spring.jpa.hibernate.ddl-auto=update
this was taking a long time

Spring Social Twitter HTTP Status 405 - Request method 'POST' not supported

Friends I am using Spring Mvc 4.2.5, Spring Security 4.0.4 , Spring Social 1.1.2 to integrate with twitter api.everything is fine upto connectcontroller handling get /connect/twitter,/connect . but when i send post request from twitterConnect.jsp its giving 405 error
here is my SocialConfiguration code
#Configuration
#EnableSocial
#PropertySource(value = { "classpath:twitter.properties" })
public class SpringSocialConfig implements SocialConfigurer {
static final Logger logger = Logger.getLogger(SpringSocialConfig.class);
#Autowired
private DataSource dataSource;
//
// SocialConfigurer implementation methods
//
#Override
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
logger.info("at addconnectionFactory adding consumerkey");
System.out.println("at add Connection FActory");
cfConfig.addConnectionFactory(new TwitterConnectionFactory(env.getProperty("twitter.consumerKey"), env.getProperty("twitter.consumerSecret")));
}
#Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
logger.info("crateing jdbcuserconnection repository");
return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
}
// API Binding Beans
//
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public Twitter twitter(ConnectionRepository repository) {
Connection<Twitter> connection = repository.findPrimaryConnection(Twitter.class);
logger.info("crateing connection Twitter");
return connection != null ? connection.getApi() : null;
}
//
// Web Controller and Filter Beans
//
#Bean
public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
ConnectController connectController = new ConnectController(connectionFactoryLocator, connectionRepository);
logger.info("At connect Controller");
System.out.println("hi iam running");
return connectController;
}
#Bean
public ReconnectFilter apiExceptionHandler(UsersConnectionRepository usersConnectionRepository, UserIdSource userIdSource) {
return new ReconnectFilter(usersConnectionRepository, userIdSource);
}
#Override
public UserIdSource getUserIdSource() {
return new UserIdSource() {
#Override
public String getUserId() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return authentication.getName();
}
};
}
}
This is my SecurityConfiguration
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
#Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
#Autowired
PersistentTokenRepository tokenRepository;
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/signup/**").anonymous()
.antMatchers("/dashboard/**","/add_t_accounts/**").access("hasRole('USER')")
.and().formLogin().loginPage("/login").loginProcessingUrl("/login").defaultSuccessUrl("/dashboard")
.usernameParameter("userName").passwordParameter("password").and()
.rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
.tokenValiditySeconds(86400).and().csrf()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
#Bean
public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
"remember-me", userDetailsService, tokenRepository);
return tokenBasedservice;
}
#Bean
public AuthenticationTrustResolver getAuthenticationTrustResolver() {
return new AuthenticationTrustResolverImpl();
}
#Bean(name="authenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
Im getting this on console
enter code hereo
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Thu Nov 24 05:04:03 IST 2016]; root of context hierarchy
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Registering annotated classes: [class org.springframework.social.showcase.config.MainConfig,class org.springframework.social.showcase.config.WebMvcConfig,class org.springframework.social.showcase.config.SecurityConfig,class org.springframework.social.showcase.config.SocialConfig]
WARN : org.springframework.context.annotation.ConfigurationClassEnhancer - #Bean method MainConfig.propertyPlaceHolderConfigurer is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as #Autowired, #Resource and #PostConstruct within the method's declaring #Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see #Bean javadoc for complete details
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Detected #ExceptionHandler methods in exceptionHandlingControllerAdvice
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: Root WebApplicationContext: startup date [Thu Nov 24 05:04:03 IST 2016]; root of context hierarchy
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.HomeController.home(java.security.Principal,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public void org.springframework.social.showcase.signin.SigninController.signin()
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signup],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.social.showcase.signup.SignupForm org.springframework.social.showcase.signup.SignupController.signupForm(org.springframework.web.context.request.WebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signup],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.signup.SignupController.signup(org.springframework.social.showcase.signup.SignupForm,org.springframework.validation.BindingResult,org.springframework.web.context.request.WebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/friends],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterFriendsController.friends(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/followers],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterFriendsController.followers(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/messages],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterMessageController.sent(org.springframework.social.showcase.twitter.MessageForm)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/messages/sent],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterMessageController.sent(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/messages],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterMessageController.inbox(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterProfileController.home(java.security.Principal,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/revoked],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public void org.springframework.social.showcase.twitter.TwitterRevokedToken.simulateExpiredToken()
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/search],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterSearchController.showTrends(java.lang.String,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/timeline/{timelineType}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTimelineController.showTimeline(java.lang.String,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/timeline],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTimelineController.showTimeline(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/tweet],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTimelineController.postTweet(java.lang.String)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/trends],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTrendsController.showTrends(org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.signIn(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[oauth_token],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.oauth1Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[error],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.oauth2ErrorCallback(java.lang.String,java.lang.String,java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[code],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.oauth2Callback(java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.canceledAuthorizationCallback()
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.connect(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[oauth_token],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth1Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[error],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2ErrorCallback(java.lang.String,java.lang.String,java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.connect.web.ConnectController.connectionStatus(org.springframework.web.context.request.NativeWebRequest,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.connect.web.ConnectController.connectionStatus(java.lang.String,org.springframework.web.context.request.NativeWebRequest,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[code],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}/{providerUserId}],methods=[DELETE],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.removeConnection(java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[DELETE],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.removeConnections(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
INFO : org.springframework.security.web.DefaultSecurityFilterChain - Creating filter chain: Ant [pattern='/resources/**'], []
INFO : org.springframework.security.web.DefaultSecurityFilterChain - Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#70012279, org.springframework.security.web.context.SecurityContextPersistenceFilter#69061fc0, org.springframework.security.web.header.HeaderWriterFilter#12139505, org.springframework.security.web.csrf.CsrfFilter#5a005b47, org.springframework.security.web.authentication.logout.LogoutFilter#3170938b, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#4946d531, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#5a45ee51, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#27698887, org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter#61a3002, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#5a7e6f61, org.springframework.security.web.session.SessionManagementFilter#58c11f65, org.springframework.security.web.access.ExceptionTranslationFilter#18b43f5, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#4986e68]
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 4999 ms
Nov 24, 2016 5:04:08 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization started
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Thu Nov 24 05:04:08 IST 2016]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization completed in 212 ms
Nov 24, 2016 5:04:08 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8090"]
Nov 24, 2016 5:04:08 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8099"]
Nov 24, 2016 5:04:08 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 23694 ms
I had the same problem like you have. Now, I found the cause. You are including csrf token control in spring security configuration. That's why, you need to add csrf token as input in your connectTwitter view file.

i am getting issue while start tomcat server

I am new to jersey multi part. While i am starting the tomcat server getting issue.
#POST
#Path("/uploadImagesUsingJersey")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("text/plain")
public Response uploadImages(#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) throws IOException{
String uploadedFileLocation = (String) session.getServletContext().getAttribute("ProfilePhotoPath");
uploadedFileLocation=uploadedFileLocation+236+"/"+fileDetail.getName();
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
employeeVO=new EmployeeInformationVO();
employeeVO=(EmployeeInformationVO) CacheAction.getById(EmployeeInformationVO.class,236);
employeeVO.setPhotoPath(236+"/"+fileDetail.getFileName());
int result=CacheAction.commonAddOrUpdate(employeeVO);
return Response.status(200).entity(result).build();
}
I am using this kind Of jar:
1)jersey-multipart-1.8-ea03.jar
2)mimepull-1.8-sources.jar
3)jersey-server-1.8.jar
4)jersey-bundle-1.8.jar
And i am getting this kind of issue:
INFO: Provider classes found:
class com.owlike.genson.ext.jaxrs.GensonJsonConverter
Nov 13, 2016 10:45:15 PM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.8 06/24/2011 12:39 PM'
Nov 13, 2016 10:45:17 PM com.sun.jersey.spi.inject.Errors processErrorMessages
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for method public javax.ws.rs.core.Response com.hrm.jersey.action.MyServiceAction.uploadImages(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) throws java.io.IOException at parameter at index 0
SEVERE: Missing dependency for method public javax.ws.rs.core.Response com.hrm.jersey.action.MyServiceAction.uploadImages(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) throws java.io.IOException at parameter at index 1
SEVERE: Method, public javax.ws.rs.core.Response com.hrm.jersey.action.MyServiceAction.uploadImages(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) throws java.io.IOException, annotated with POST of resource, class com.hrm.jersey.action.MyServiceAction, is not recognized as valid resource method.
Nov 13, 2016 10:45:17 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
com.sun.jersey.spi.inject.Errors$ErrorMessagesException

Spring, JPA,JSF - null pointer exception on the access to data

I write web application with spring, jpa and jsf support. In my xhtml web page is table(primefaces) and button, which refresh database. When I try click the button i get this:
gru 23, 2014 10:01:10 PM org.apache.catalina.core.AprLifecycleListenerinit INFO: The APR based Apache Tomcat Native library which allowsoptimal performance in production environments was not found on thejava.library.path: C:\ProgramFiles\Java\jdk1.7.0_45\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\oraclexe\app\oracle\product\11.2.0\server\bin;;C:\ProgramFiles (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLSClient\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\ProgramFiles (x86)\Windows Live\Shared;C:\Program Files\Intel\Intel(R)Management Engine Components\DAL;C:\Program Files\Intel\Intel(R)Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R)Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R)Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCLSDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCLSDK\2.0\bin\x64;D:\maven\bin;.
gru 23, 2014 10:01:10 PM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING:[SetPropertiesRule]{Server/Service/Engine/Host/Context} Settingproperty 'source' to 'org.eclipse.jst.jee.server:SJM' did not find amatching property.
gru 23, 2014 10:01:11 PM org.apache.coyote.AbstractProtocol init INFO: InitializingProtocolHandler ["http-bio-8081"]
gru 23, 2014 10:01:11 PM org.apache.coyote.AbstractProtocol init INFO: InitializingProtocolHandler ["ajp-bio-8010"]
gru 23, 2014 10:01:11 PM org.apache.catalina.startup.Catalina load INFO: Initializationprocessed in 1193 ms
gru 23, 2014 10:01:11 PM org.apache.catalina.core.StandardService startInternal INFO: Startingservice Catalina
gru 23, 2014 10:01:11 PM org.apache.catalina.core.StandardEngine startInternal INFO: StartingServlet Engine: Apache Tomcat/7.0.56
gru 23, 2014 10:01:16 PM org.apache.catalina.core.ApplicationContext log INFO: No SpringWebApplicationInitializer types detected on classpath
gru 23, 2014 10:01:16 PM org.apache.catalina.core.ApplicationContext log INFO:Initializing Spring root WebApplicationContext
22:01:21,254 DEBUG FlowDefinitionRegistryImpl:100 - Registering flow definition'ServletContext resource [/WEB-INF/flows/main/main-flow.xml]' under id'main'
22:01:21,280 DEBUG ConditionalFlowExecutionListenerLoader:59 -Adding flow execution listenerorg.springframework.webflow.persistence.JpaFlowExecutionListener#16495871with criteria *
22:01:21,282 DEBUGConditionalFlowExecutionListenerLoader:59 - Adding flow executionlistenerorg.springframework.faces.webflow.FlowFacesContextLifecycleListener#294d6e25with criteria *
gru 23, 2014 10:01:21 PM com.sun.faces.config.ConfigureListener contextInitialized INFO:Initializing Mojarra 2.1.10 (-SNAPSHOT 20120625-1354) for context'/SJM'
gru 23, 2014 10:01:22 PM com.sun.faces.spi.InjectionProviderFactory createInstance INFO:JSF1048: PostConstruct/PreDestroy annotations present. ManagedBeansmethods marked with these annotations will have said annotationsprocessed.
gru 23, 2014 10:01:24 PM org.primefaces.webapp.PostConstructApplicationEventListenerprocessEvent INFO: Running on PrimeFaces 3.4
gru 23, 2014 10:01:24 PM org.apache.catalina.core.ApplicationContext log INFO: InitializingSpring FrameworkServlet 'Spring MVC Dispatcher Servlet'
gru 23, 2014 10:01:24 PM org.apache.coyote.AbstractProtocol start INFO: StartingProtocolHandler ["http-bio-8081"]
gru 23, 2014 10:01:24 PM org.apache.coyote.AbstractProtocol start INFO: StartingProtocolHandler ["ajp-bio-8010"]
gru 23, 2014 10:01:24 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 13692 ms
22:01:25,527 DEBUG FlowHandlerMapping:108 - Mapping requestwith URI '/SJM/app/main' to flow with id 'main'
22:01:25,539 DEBUGFlowExecutorImpl:135 - Launching new execution of flow 'main' withinput null
22:01:25,539 DEBUG FlowDefinitionRegistryImpl:59 - GettingFlowDefinition with id 'main'
22:01:25,555 DEBUG DefaultFlowHolder:83- Assembling the flow for the first time
22:01:25,664 DEBUG FlowExecutionImplFactory:78 - Creating new execution of 'main'
22:01:25,680 DEBUG ConditionalFlowExecutionListenerLoader:87 - Loaded[2] of possible 2 listeners for this execution request for flow'main', the listeners to attach are list[org.springframework.webflow.persistence.JpaFlowExecutionListener#16495871,org.springframework.faces.webflow.FlowFacesContextLifecycleListener#294d6e25]
22:01:25,680 DEBUG FlowExecutionImpl:215 - Starting in org.springframework.webflow.mvc.servlet.MvcExternalContext#6f98bf1with input null
22:01:25,758 DEBUG ViewState:189 - Entering state'welcome' of flow 'main' 22:01:25,774 DEBUGSessionBindingConversationManager:78 - Putting conversation attribute'name' with value main
22:01:25,774 DEBUG SessionBindingConversationManager:78 - Putting conversation attribute'caption' with value null
22:01:25,774 DEBUG SessionBindingConversationManager:78 - Putting conversation attribute'description' with value null
22:01:25,774 DEBUG SessionBindingConversationManager:78 - Putting conversation attribute'flowExecutionSnapshotGroup' with value org.springframework.webflow.execution.repository.impl.SimpleFlowExecutionSnapshotGroup#67079bb1
22:01:25,774 DEBUG FlowExecutionImpl:419 - Assigned key e1s1
22:01:25,774 DEBUG SessionBindingConversationManager:67 - Lockingconversation 1
22:01:25,774 DEBUG DefaultFlowExecutionRepository:121 -Putting flow execution '[FlowExecutionImpl#277b5201 flow = 'main',flowSessions = list[[FlowSessionImpl#1144d3e7 flow = 'main', state ='welcome', scope = map['viewScope' -map[[empty]]]]]]' intorepository
22:01:25,789 DEBUG DefaultFlowExecutionRepository:128 -Adding snapshot to group with id 1
22:01:25,789 DEBUG SessionBindingConversationManager:78 - Putting conversation attribute'scope' with value map['flashScope' -map['messagesMemento' ->map[[null] -list[[empty]]]]]
22:01:25,789 DEBUG SessionBindingConversationManager:99 - Unlocking conversation 1
22:01:25,789 DEBUG FlowHandlerAdapter:367 - Sending flow executionredirect to '/SJM/app/main?execution=e1s1'
22:01:25,961 DEBUG FlowHandlerMapping:108 - Mapping request with URI '/SJM/app/main' toflow with id 'main'
22:01:25,961 DEBUG FlowExecutorImpl:161 - Resumingflow execution with key 'e1s1 22:01:25,961 DEBUGSessionBindingConversationManager:67 - Locking conversation 1
22:01:25,961 DEBUG DefaultFlowExecutionRepository:106 - Getting flowexecution with key 'e1s1'
22:01:25,961 DEBUG FlowDefinitionRegistryImpl:59 - Getting FlowDefinition with id 'main'
22:01:25,961 DEBUG ConditionalFlowExecutionListenerLoader:87 - Loaded[2] of possible 2 listeners for this execution request for flow'main', the listeners to attach arelist[org.springframework.webflow.persistence.JpaFlowExecutionListener#16495871,org.springframework.faces.webflow.FlowFacesContextLifecycleListener#294d6e25]
22:01:25,961 DEBUG FlowExecutionImpl:249 - Resuming inorg.springframework.webflow.mvc.servlet.MvcExternalContext#21d18342
22:01:26,519 DEBUG ViewState:289 - Rendering + [JSFView ='/WEB-INF/flows/main/welcome.xhtml']
22:01:26,519 DEBUG ViewState:290- Flash scope = map[[empty]]
22:01:26,520 DEBUG ViewState:291 - Messages = [DefaultMessageContext#60573326 sourceMessages = map[[null]-list[[empty]]]]
22:01:26,631 DEBUG DefaultFlowExecutionRepository:121 - Putting flow execution'[FlowExecutionImpl#3fcc8fc7 flow = 'main', flowSessions =list[[FlowSessionImpl#ef3728a flow = 'main', state = 'welcome', scope= map['viewScope' -map['flowSerializedViewState' -[FlowSerializedView#10e4c9b1 viewId ='/WEB-INF/flows/main/welcome.xhtml']]]]]]' into repository
22:01:26,636 DEBUG DefaultFlowExecutionRepository:128 - Addingsnapshot to group with id 1
22:01:26,636 DEBUG SessionBindingConversationManager:78 - Putting conversation attribute'scope' with value map['flashScope' -map['messagesMemento' ->map[[empty]]]] 22:01:26,637 DEBUG SessionBindingConversationManager:99- Unlocking conversation 1
22:01:28,327 DEBUG FlowHandlerMapping:108 - Mapping request with URI '/SJM/app/main' to flow with id 'main'
22:01:28,327 DEBUG FlowExecutorImpl:161 - Resuming flow execution withkey 'e1s1
22:01:28,327 DEBUG SessionBindingConversationManager:67 -Locking conversation 1
22:01:28,343 DEBUG DefaultFlowExecutionRepository:106 - Getting flow execution with key'e1s1'
22:01:28,343 DEBUG FlowDefinitionRegistryImpl:59 - GettingFlowDefinition with id 'main'
22:01:28,345 DEBUG ConditionalFlowExecutionListenerLoader:87 - Loaded [2] of possible 2listeners for this execution request for flow 'main', the listeners to attach are list [org.springframework.webflow.persistence.JpaFlowExecutionListener#16495871,org.springframework.faces.webflow.FlowFacesContextLifecycleListener#294d6e25]
22:01:28,345 DEBUG FlowExecutionImpl:249 - Resuming inorg.springframework.webflow.mvc.servlet.MvcExternalContext#19f6d704
22:01:28,360 DEBUG FlowExecutionImpl:590 - Attempting to handle[org.springframework.webflow.execution.FlowExecutionException:Exception thrown in state 'welcome' of flow 'main'] with root cause[java.lang.NullPointerException]
22:01:28,360 DEBUGFlowExecutionImpl:611 - Rethrowing unhandled flow execution exception22:01:28,360 DEBUG SessionBindingConversationManager:99 - Unlockingconversation 1
gru 23, 2014 10:01:28 PMorg.apache.catalina.core.StandardWrapperValve invoke SEVERE:Servlet.service() for servlet [Spring MVC Dispatcher Servlet] incontext with path [/SJM] threw exception [Request processing failed;nested exception isorg.springframework.webflow.execution.FlowExecutionException:Exception thrown in state 'welcome' of flow 'main'] with root causejava.lang.NullPointerException
at com.sjm.dao.ModelDao.findByStartTime(ModelDao.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at org.springframework.faces.webflow.FlowActionListener.processAction(FlowActionListener.java:81)
at org.springframework.faces.model.SelectionTrackingActionListener.processAction(SelectionTrackingActionListener.java:55)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at org.springframework.faces.webflow.FlowLifecycle.invokePhase(FlowLifecycle.java:127)
at org.springframework.faces.webflow.FlowLifecycle.execute(FlowLifecycle.java:70)
at org.springframework.faces.webflow.JsfView.processUserEvent(JsfView.java:120)
at org.springframework.webflow.engine.ViewState.handleEvent(ViewState.java:226)
at org.springframework.webflow.engine.ViewState.resume(ViewState.java:196)
at org.springframework.webflow.engine.Flow.resume(Flow.java:545)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:258)
at org.springframework.webflow.executor.FlowExecutorImpl.resumeExecution(FlowExecutorImpl.java:169)
at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:183)
at org.springframework.faces.webflow.JsfFlowHandlerAdapter.handle(JsfFlowHandlerAdapter.java:48)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$Wrappingrunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:744)
NawNeHier.java
package com.sjm.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="NAW_NE_HIER")
public class NawNeHier implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int hierId;
private int parentHierId;
private String type;
private String name;
private String display_name;
public NawNeHier() {
}
public int getHierId() {
return hierId;
}
public void setHierId(int hierId) {
this.hierId = hierId;
}
public int getParentHierId() {
return parentHierId;
}
public void setParentHierId(int parentHierId) {
this.parentHierId = parentHierId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDisplay_name() {
return display_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
}
ModelDao.java
package com.sjm.dao;
import javax.faces.bean.ManagedBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.sjm.model.NawNeHier;
#ManagedBean(name="modelDao")
public class ModelDao {
#PersistenceContext
private EntityManager entityManager;
private NawNeHier nawNeHier;
public ModelDao () {}
public NawNeHier getNawNeHier() {
return nawNeHier;
}
public void setNawNeHier(NawNeHier nawNeHier) {
this.nawNeHier = nawNeHier;
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void findByStartTime() {
String jpql = "SELECT n FROM NAW_NE_HIER n";
this.nawNeHier = entityManager.createQuery(jpql, NawNeHier.class).getSingleResult();
}
}
index.xhtml
<h:form id="myform">
<p:commandButton value="Count" action="#{modelDao.findByStartTime}" update="dataTable"/>
<p:dataTable id="dataTable" var="nawNeHier" value="#{modelDao.nawNeHier}">
<p:column headerText="hierId">
<h:outputText value="#{nawNeHier.hierId}" />
</p:column>
<p:column headerText="parentHierId">
<h:outputText value="#{nawNeHier.parentHierId}" />
</p:column>
<p:column headerText="type">
<h:outputText value="#{nawNeHier.type}" />
</p:column>
<p:column headerText="name">
<h:outputText value="#{nawNeHier.name}" />
</p:column>
<p:column headerText="display_name">
<h:outputText value="#{nawNeHier.display_name}" />
</p:column>
</p:dataTable>
</h:form>

Using Grizzly as the test container for dropwizard resources

I am trying to get this GrizzlyResourceTest.javaworking with dropwizard v0.6.1. The reason I want to use grizzly as the test container is because InMemoryTestContainer does not support Resource with injectable constructor, see this issue in details InMemoryTestContainer does not support Resource with injectable constructor
Since com.yammer.dropwizard.json.Json and com.yammer.dropwizard.bundles.JavaBundle are not in v0.6.1 anymore, I simply just comment out the lines related to these class.
#Before
public void setUpJersey() throws Exception {
setUpResources();
this.test = new JerseyTest(new GrizzlyWebTestContainerFactory()) {
#Override
protected AppDescriptor configure() {
ClientConfig config = new DefaultClientConfig();
// taken from DropwizardResourceConfig
config.getFeatures().put(ResourceConfig.FEATURE_DISABLE_WADL, Boolean.TRUE);
config.getSingletons().add(new LoggingExceptionMapper<Throwable>() { }); // create a subclass to pin it to Throwable
config.getClasses().add(InstrumentedResourceMethodDispatchAdapter.class);
config.getClasses().add(CacheControlledResourceMethodDispatchAdapter.class);
for (Class<?> provider : providers) {
config.getClasses().add(provider);
}
config.getSingletons().addAll(singletons);
return new WebAppDescriptor.Builder("com.example.helloworld.resources").clientConfig(config).build();
}
};
test.setUp();
}
My case is more complex since I have HttpServletRequest injected to my resource class like myMethod(#Context HttpServletRequest request). So here I just use PersonResource under dropwizard-example.
QuickTest.java looks like:
public class QuickTest extends GrizzlyResourceTest{
#Test
public void testGrizzly() throws Exception {
ClientResponse rsp = client()
.resource("http://localhost:9998/people").get(ClientResponse.class);
Assert.assertEquals(200, rsp.getStatus());
}
#Override
protected void setUpResources() throws Exception {
}
}
When I run QuickTest, The error I am getting from Console is this:
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
Mar 14, 2013 7:14:11 PM com.sun.jersey.test.framework.spi.container.grizzly2.web.GrizzlyWebTestContainerFactory$GrizzlyWebTestContainer <init>
INFO: Creating Grizzly2 Web Container configured at the base URI http://localhost:9998/
Mar 14, 2013 7:14:11 PM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:9998]
Mar 14, 2013 7:14:11 PM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
Mar 14, 2013 7:14:11 PM org.glassfish.grizzly.servlet.WebappContext deploy
INFO: Starting application [TestContext] ...
Mar 14, 2013 7:14:11 PM org.glassfish.grizzly.servlet.WebappContext initServlets
INFO: [TestContext] Servlet [com.sun.jersey.spi.container.servlet.ServletContainer] registered for url pattern(s) [[/*]].
Mar 14, 2013 7:14:11 PM org.glassfish.grizzly.servlet.WebappContext deploy
INFO: Application [TestContext] is ready to service requests. Root: [].
Mar 14, 2013 7:14:11 PM com.sun.jersey.spi.inject.Errors processErrorMessages
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for field: private javax.servlet.http.HttpServletRequest com.yammer.dropwizard.jersey.LoggingExceptionMapper.request
Any ideas?

Resources