How to config MessageDispatcherServlet and ServletRegistration both by using spring annotaion - spring

I have configure MessageDispatcherServlet for soap services and ServletRegistration for web services but controller not call in case of web services.
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
// use MessageDispatcherServlet instead of standard DispatcherServlet for SOAP messages
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setContextClass(WebServiceWsConfig.class);
servlet.setApplicationContext(context);
servlet.setTransformWsdlLocations(true);
// register MessageDispatcherServlet as Web Service entry point
final ServletRegistration.Dynamic dispatcher = servletContext.addServlet("MessageDispatcherServlet",servlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/soapws/*");
dispatcher.addMapping("/");
}
}
My WebServicesConfig class is
#Configuration
#EnableWs
#EnableWebMvc
#ComponentScan(basePackages = "")
#PropertySource(value = {"classpath:config_local.properties"})
public class WebServiceConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment env;
#Bean(name = "pos")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema posSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("posPort");
wsdl11Definition.setLocationUri("/soapws");
wsdl11Definition.setTargetNamespace("http://---.---.in/soap");
wsdl11Definition.setSchema(posSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema studentsSchema() {
return new SimpleXsdSchema(new ClassPathResource("pos.xsd"));
}
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}

I solve my problem using Spring Boot configuration, This help me calling Soap services as well as Web services.
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter{
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "pos")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema posSchema)
{
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("posPort");
wsdl11Definition.setLocationUri("/soapws");
wsdl11Definition.setTargetNamespace("http://---.---.in/soap");
wsdl11Definition.setSchema(posSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema studentsSchema() {
return new SimpleXsdSchema(new ClassPathResource("pos.xsd"));
}

Related

NoSuchMethodException: org.springframework.boot.autoconfigure.http.HttpMessageConverters

I want to configure Spring application with Hibernate. I tried this:
Main start method:
#Configuration
#EnableWebMvc
public class WebConfig implements WebApplicationInitializer, WebMvcConfigurer {
private BasicAuthenticationInterceptor basicAuthenticationInterceptor;
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.removeIf(converter -> converter instanceof MappingJackson2XmlHttpMessageConverter);
converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
converters.add(new MappingJackson2XmlHttpMessageConverter(
((XmlMapper) createObjectMapper(Jackson2ObjectMapperBuilder.xml()))
.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION)));
converters.add(new MappingJackson2HttpMessageConverter(
createObjectMapper(Jackson2ObjectMapperBuilder.json())));
}
private ObjectMapper createObjectMapper(Jackson2ObjectMapperBuilder builder) {
builder.indentOutput(true);
builder.modules(new JaxbAnnotationModule());
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
builder.defaultUseWrapper(false);
return builder.build();
}
#Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(ContextDatasource.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
#Autowired
public void setBasicAuthenticationInterceptor(BasicAuthenticationInterceptor basicAuthenticationInterceptor) {
this.basicAuthenticationInterceptor = basicAuthenticationInterceptor;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(basicAuthenticationInterceptor);
}
}
Hibernate configuration called from rootContext.register(ContextDatasource.class);:
#SpringBootApplication
#Configuration
#EnableTransactionManagement
public class ContextDatasource {
#Bean
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
return new FastJsonHttpMessageConverter();
}
#Bean
#Autowired
public HttpMessageConverters convertersToBeUsed(FastJsonHttpMessageConverter converter) {
return new HttpMessageConverters(converter);
}
#Bean
public LocalSessionFactoryBean getSessionFactory() throws NamingException {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(getDataSource());
sessionFactory.setPackagesToScan(new String[] { "org.datalis.plugin.database.models" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource getDataSource() throws NamingException {
return (DataSource) new JndiTemplate().lookup("java:/global/production_gateway");
}
#Bean
public PlatformTransactionManager getHibernateTransactionManager() throws NamingException {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory().getObject());
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor getExceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MariaDBDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.format_sql", "true");
return hibernateProperties;
}
}
But when I deploy the WAR file I get error:
Caused by: java.lang.NoSuchMethodException: org.springframework.boot.autoconfigure.http.HttpMessageConverters$$EnhancerBySpringCGLIB$$1d90bff9.<init>()
at java.base/java.lang.Class.getConstructor0(Class.java:3302)
Full error stack:
https://pastebin.com/x30W2aws
Can you give advice where I'm wrong and how to fix the problem?
Do I need to implement the module startup with another configuration?
EDIT:
With Java 8 the code is working without above issue. With latest Java 10 I get the above exception. Do you know what configuration I need to do?
According to the Spring Boot release notes, Java 10 is supported by Spring Boot version 2.0.1 and up. Without a list of your dependencies it's impossible to know if this is the issue, but it does seem like a good place to start.
Are you running Boot v2.0.1 or higher?

Spring MVC Servlet when deploying war to tomcat

I have already deploy war spring MVC to tomcat9. it's already running but in spring I create getmapping("/tesget") but when I created the servlet, result getmapping is wrong.
controller:
#GetMapping("tesget")
#ResponseStatus(HttpStatus.OK)
public List getTes2() throws Exception {
return userService.getTes2();
}
servlet:
public class Servlet extends HttpServlet {
public void init() throws ServletException
{
// Do required initialization
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Servlet Testing</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Welcome to the Servlet Testing Center");
out.println("</BODY>");
out.println("</HTML>");
}
public void destroy()
{
// do nothing.
}
}
web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<servlet>
<servlet-name>Servlet</servlet-name>
<servlet-class>com.project.maven.config.Servlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Before I created servlet and war, I running usually and when I go to localhost:8080/SpringNew/tesget, the result is true, list JSON from database, but when I create servlet, the url localhost:8080/SpringNew/tesget is wrong. the result is:
Welcome to the Servlet Testing Center
how to fix this problem? Thanks.
Bobby
AppInitializer.java
public class AppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet(
"dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
HibernateConfiguration.java
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.project.maven." })
#PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.project.maven.entity" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
AppConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.project.maven")
public class AppConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
registry.addResourceHandler("**/**")
.addResourceLocations("classpath:/META-INF/resources/"); // harus ada folder resources di webapp/WEB-INF/
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
what about your other config !
send your controller class code
if you are sure about your config try with #GetMapping("/tesget")

Spring Boot + JSF static page configurations

am getting started with Spring Boot + JSF.
Spring documentation says:
Spring will automatically load and serve resources inside
/static (or /public or /resources or /META-INF/resources.
This is not working for me.
it is discouraged to use the "webapp" (src/main/webapp) folder.
But for my static content, it seem to be the only folder thats working with my JSF static page.
see Spring Boot static content.
I have tried these configuration:
#Configuration
public class JSFServletConfigs implements ServletContextInitializer// ,ServletContextAware
{
#Override // ServletContext initiallization parameters
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.setInitParameter("facelets.DEVELOPMENT", "false");
servletContext.setInitParameter("javax.faces.PROJECT_STAGE", "Development");
servletContext.setInitParameter("javax.faces.DEFAULT_SUFFIX", ".xhtml");
servletContext.setInitParameter("javax.faces.PARTIAL_STATE_SAVING_METHOD", "true");
servletContext.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD", "-1");
}
#Bean // Registering the FacesServlet.
public ServletRegistrationBean servletRegistrationBean() {
FacesServlet servlet = new FacesServlet();
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet) {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
FacesInitializer facesInitializer = new FacesInitializer();
Set<Class<?>> clazz = new HashSet<Class<?>>();
clazz.add(JSFServletConfigs.class);
facesInitializer.onStartup(clazz, servletContext);
}
};
servletRegistrationBean.addUrlMappings("*.xhtml", "*.jsf", "*.html");
return servletRegistrationBean;
}
#Bean
public InternalResourceViewResolver jsfViewResolving(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/<sub-folder of any LOCATION>/");
viewResolver.setSuffix(".xhtml");
return viewResolver;
}
}
Servlet pre-configs:
#Configuration
#EnableWebMvc
public class DefaultServletConfigs extends WebMvcConfigurerAdapter {
#Override // Enabling the default Servlet at path="/"
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
private final String[] LOCATIONS = {"<All my possible locations>"};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if(!registry.hasMappingForPattern("/**")){
registry.addResourceHandler("/**").addResourceLocations(LOCATIONS);
}
if(!registry.hasMappingForPattern("webjars")){
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
}
My Question are:
What am I missing here?
How do I get the flexibility to place my resources in any of the other folders above
(i.e. "/static", "/public", "/resources", "/META-INF/resources").

How to load ApplicationContext java-config in Junit

I am trying to move spring xml config to java config. Right now, I am able to make everything work, except one thing, that is to run junit on my services. The problem is that my junit test couldn't detect application context. Hence, how I can load application context java-based config in Junit? Since I can run my service on a browser, I assume that my integration is correct, meaning that my test configuration is not right, but I can't find where is my be wrong.
This is my junit config:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(
classes={Bootstrap.class, RootContextConfig.class
, WebServletContextConfig.class, PersistenceConfig.class })
#WebAppConfiguration
//#TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
public class BaseTest { ... }
Just in case, I include my application context configuration here also.
This is my bootstrap
public class Bootstrap implements WebApplicationInitializer
{
#Override
public void onStartup(ServletContext container)
throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootContextConfig.class);
container.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext servletContext = new AnnotationConfigWebApplicationContext();
servletContext.register(WebServletContextConfig.class);
ServletRegistration.Dynamic dispatcher = container.addServlet(
"SpringDispatcher", new DispatcherServlet(servletContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
My RootContext
#Configuration
#EnableScheduling
#EnableAsync(
mode=AdviceMode.PROXY, proxyTargetClass=false,
order=Ordered.HIGHEST_PRECEDENCE
)
#ComponentScan(
basePackages={"com.core", "com.common"},
excludeFilters=#ComponentScan.Filter(Controller.class)
)
#Import({PersistenceConfig.class})
public class RootContextConfig {...}
My WebServletContext
#Configuration
#EnableWebMvc
#ComponentScan(
basePackages = { "com.web" },
useDefaultFilters = false,
includeFilters = #ComponentScan.Filter({Controller.class, ControllerAdvice.class})
)
public class WebServletContextConfig extends WebMvcConfigurerAdapter {..}
My PersistentContext
#Configuration
#EnableTransactionManagement(
mode=AdviceMode.PROXY, proxyTargetClass=false
, order=Ordered.LOWEST_PRECEDENCE)
public class PersistenceConfig {
#Bean
public DataSource customerSupportDataSource() {
//JndiDataSourceLookup lookup = new JndiDataSourceLookup();\
BasicDataSource basic = new BasicDataSource();
basic.setDriverClassName(KEY_DRIVER_CLASS);
basic.setUrl(KEY_DB_URL);
basic.setUsername(KEY_DB_USERNAME);
basic.setPassword(KEY_DB_PASSWORD);
return basic;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
Map<String, Object> properties = new Hashtable<>();
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQLDialect");
adapter.setGenerateDdl(true);
adapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory =
new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(adapter);
factory.setDataSource(this.customerSupportDataSource());
factory.setPackagesToScan("com.common.model");
factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
factory.setValidationMode(ValidationMode.NONE);
factory.setJpaPropertyMap(properties);
return factory;
}
#Bean
public PlatformTransactionManager jpaTransactionManager()
{
return new JpaTransactionManager(
this.entityManagerFactoryBean().getObject()
);
}
}

How to config #EnableConfigurationProperties, #ConfigurationProperties with WebApplicationInitializer?

I want to read application.properties using
#EnableConfigurationProperties and #ConfigurationProperties.
I am able to do that with the following codes:
Application.java
#SpringBootApplication
#EnableConfigurationProperties(ApplicationConfiguration.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
ApplicationConfiguration.java
#ConfigurationProperties(prefix = "server")
public class ApplicationConfiguration {
private String port;
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
}
TestController.java
#Controller
public class TestController {
#Autowired
ApplicationConfiguration applicationConfiguration;
#RequestMapping("/test")
#ResponseBody
public String test() {
if (applicationConfiguration != null) {
return applicationConfiguration.getPort();
}
return "1";
}
}
application.properties
server.port = 8085
Now I want to replace SpringBoot(Application.java) with WebApplicationInitializer so that I can use an external container. Here is my code:
CommonInitializer.java
public class CommonInitializer implements WebApplicationInitializer{
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
annotationConfigWebApplicationContext.register(WebConfiguration.class);
annotationConfigWebApplicationContext.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(annotationConfigWebApplicationContext));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
WebConfiguration.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "hello")
#EnableAutoConfiguration
#EnableConfigurationProperties(ApplicationConfiguration.class)
public class WebConfiguration {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
After doing this, I am not able to get the port(port is null, applicationConfiguration is not null) in application.proerties. Any idea? What am I missing?
Problem solved. I am missing property file location!!
#ConfigurationProperties(prefix = "server", locations = "classpath:application.properties")
Seems spring boot does that for you automatically.

Resources