SymetricWebServer not starting in embedded mode - java

I have a Spring boot maven project with SymetricDS. When I start the application in embedded mode, even if I have a Tomcat with Spring boot, it is looking for Jetty.
SymmetricWebServer node = new SymmetricWebServer("server.properties");
<dependency>
<groupId>org.jumpmind.symmetric</groupId>
<artifactId>symmetric-server</artifactId>
<version>3.5.19</version>
</dependency>
Exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/jetty/server/bio/SocketConnector
Why is this? Why are the dependencies not downloaded with symetric-server?

The maven dependency on Jetty is "provided" because symmetric-server can be built to be a war that can be deployed to any number of web servers. Here is the essence of how I would embed SymmetricDS in Spring Boot using Spring Boot's provided web container.
import org.jumpmind.symmetric.common.ParameterConstants;
import org.jumpmind.symmetric.web.ServerSymmetricEngine;
import org.jumpmind.symmetric.web.SymmetricEngineHolder;
import org.jumpmind.symmetric.web.SymmetricServlet;
import org.jumpmind.symmetric.web.WebConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletContext;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
public class SymDSModule implements ApplicationListener<ApplicationReadyEvent> {
#Autowired
ServletContext servletContext;
#Autowired
DataSource dataSource;
#Autowired
ApplicationContext applicationContext;
#Override
final public void onApplicationEvent(ApplicationReadyEvent event) {
SymmetricEngineHolder holder = new SymmetricEngineHolder();
Properties properties = new Properties();
properties.put(ParameterConstants.DATA_LOADER_IGNORE_MISSING_TABLES, "true");
properties.put(ParameterConstants.TRIGGER_CREATE_BEFORE_INITIAL_LOAD, "false");
properties.put(ParameterConstants.AUTO_RELOAD_ENABLED, "true");
properties.put(ParameterConstants.AUTO_REGISTER_ENABLED, "true");
ServerSymmetricEngine serverEngine = new ServerSymmetricEngine(dataSource, applicationContext, properties, false, holder);
holder.getEngines().put(properties.getProperty(ParameterConstants.EXTERNAL_ID), serverEngine);
holder.setAutoStart(false);
servletContext.setAttribute(WebConstants.ATTR_ENGINE_HOLDER, holder);
serverEngine.setup();
serverEngine.start();
}
#Bean
public ServletRegistrationBean<SymmetricServlet> symServlet() {
ServletRegistrationBean<SymmetricServlet> bean = new ServletRegistrationBean<>(new SymmetricServlet(), "/sync");
bean.setLoadOnStartup(1);
return bean;
}
}

Related

JSP/SpringMVC not finding the resources folder

I'm developing a webapp using Spring MVC/JSP with Java 11, and SpringMVC 5.2.0, which started with config files, but I wanted to give programatic config (through java) a try. I've got the Servlet running, and I've successfully made the login page to "intercept" any other .jsp view if the user is not logged... However, I haven't been able to get my resources from my resource folder.
Every resource that should be loaded from there (e.g.
<link type="image/png" rel="icon" href="${contextPath}/resources/img/icon.png">) I get a 404 response, and in my IDE (Netbeans 11) I get the following message in the Network Monitor:
Request URL: http://localhost:8080/icon.png
Method: GET
Status: 404
Note: The URL should be http://localhost:8080/dragonline/resources/img/icon.png (<c:set var="contextPath" value="${pageContext.request.contextPath}"/>)
Here's my config java file:
package com.midknightmunch.dragonline.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = {"com.midknightmunch.dragonline"})
public class WebConfig implements WebMvcConfigurer{
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
//registry.addResourceHandler("/img/**").addResourceLocations("/resources/img/");
//registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/");
//registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/");
//I've tried with and without these 3 (the commented ones)
}
#Bean
public ViewResolver internalViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
#Bean
public ViewResolver resourceBundleViewResolver() {
ResourceBundleViewResolver bean = new ResourceBundleViewResolver();
bean.setBasename("views");
bean.setOrder(1);
return bean;
}
#Bean("messageSource")
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource bean = new ReloadableResourceBundleMessageSource();
String[] basenames = {"classpath:validation"};
bean.setBasenames(basenames);
return bean;
}
}
And my project structure:
icon.png: dragonline/src/main/webapp/resources/img/icon.png
views(including the jsp trying to import this image): dragonline/src/main/webapp/WEB-INF/views/login.jsp
I've tried moving the resources folder everywhere, but everytime I get a 404.
Please, any help would be appreciated.
I figured it out. The problem was that I did not grant permission in my Spring Security config file to access the resources folder, so I solved it by adding:
http.authorizeRequests().antMatchers("/resources/**").permitAll()
in my WebSecurityAdapter's config() method

Spring Boot application endpoint returns 403

I'm new to Spring Boot and currently stuck. I followed this (https://github.com/AppDirect/service-integration-sdk/wiki) Tutorial, as I want to implement an application that integrates itself into AppDirect. In the log I can see that the endpoints get created and mapped:
2018-10-29 16:32:48.898 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/v1/integration/processEvent],methods=[GET],produces=[application/json]}" onto public org.springframework.http.ResponseEntity<com.appdirect.sdk.appmarket.events.APIResult> com.appdirect.sdk.appmarket.events.AppmarketEventController.processEvent(javax.servlet.http.HttpServletRequest,java.lang.String)
But when I try to access the endpoint (http://localhost:8080/api/v1/integration/processEvent) with Browser or Http-Requester I get the following response:
{timestamp":"2018-10-29T08:50:13.252+0000","status":403,"error":"Forbidden","message":"Access Denied","path":"/api/v1/integration/processEvent"}
My application.yml looks like this:
connector.allowed.credentials: very-secure:password
server:
use-forward-headers: true
tomcat:
remote_ip_header: x-forwarded-for
endpoints:
enabled: true
info:
enabled: true
sensitive: false
health:
enabled: true
sensitive: false
time-to-live: 5000
info:
build:
name: #project.name#
description: #project.description#
version: #project.version#
This is my Application.java:
package de.....;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.http.MediaType;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
public class Application extends WebMvcConfigurerAdapter {
public static void main(String... args) {
SpringApplication.run(RootConfiguration.class, args);
}
/**
* Hack to make Spring Boot #Controller annotated classed to recognize the 'x-www-form-urlencoded' media type
*
* #param converters
*/
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FormHttpMessageConverter converter = new FormHttpMessageConverter();
MediaType mediaType = new MediaType("application", "x-www-form-urlencoded", Charset.forName("UTF-8"));
converter.setSupportedMediaTypes(Collections.singletonList(mediaType));
converters.add(converter);
super.configureMessageConverters(converters);
}
}
And this is the RootConfiguration.java:
package de.....;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import com.appdirect.sdk.ConnectorSdkConfiguration;
import com.appdirect.sdk.appmarket.DeveloperSpecificAppmarketCredentialsSupplier;
import com.appdirect.sdk.credentials.StringBackedCredentialsSupplier;
import de.....;
#Configuration
#Import({
ConnectorSdkConfiguration.class,
EventHandlersConfiguration.class
})
#EnableAutoConfiguration
public class RootConfiguration {
#Bean
public DeveloperSpecificAppmarketCredentialsSupplier environmentCredentialsSupplier(#Value("${connector.allowed.credentials}") String allowedCredentials) {
return new StringBackedCredentialsSupplier(allowedCredentials);
}
}
Any help is appreciated as intensive googleing didn't help.
Thanks in advance.
Adding the following class and registering it in Application.java solved my problem:
package de.......;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
#Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/").permitAll();
}
}

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in "package name"

I am new to spring and hibernate as well as to stackoverflow
A developing ecommerce project using spring hibernate maven
creating two file one for frontend and 2nd for backend after creating two file i am adding dependency of backend into frontend pom.ml file
I am using java to create sessionfactory ,datasource and transaction manager
here is the code I dont understand what mistake i am doing
package com.ecom.Config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import
org.springframework.transaction.annotation.EnableTransactionManagement;
import com.ecom.Model.CustomerRegistration;
#Configuration
#ComponentScan("com.ecom")
#EnableTransactionManagement
public class AnnotationConfigApplicationContext {
#Bean(name = "dataSource")
public DataSource getH2DataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:h2:tcp://localhost/~/Ecommerce");
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "create");
return properties;
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new
LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.addAnnotatedClass(CustomerRegistration.class);
return sessionBuilder.buildSessionFactory();
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory
sessionFactory) {
HibernateTransactionManager transactionManager = new
HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
Contoller
package com.ecom.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ecom.DAO.CustomerRegDAO;
import com.ecom.Model.CustomerRegistration;
#Controller
public class CustomerRegController
{
#Autowired
private CustomerRegDAO customerRegDAO ;
#RequestMapping("/registrationForm")
public String Registration(Model theModel)
{
CustomerRegistration theCustomerRegistration = new
CustomerRegistration();
theModel.addAttribute("customer", theCustomerRegistration);
return "registration-form";
}
#RequestMapping("/saveCustomer")
public String saveCustomer(#ModelAttribute("customer")
CustomerRegistration theCustomerRegistration)
{
customerRegDAO.saveCustomer(theCustomerRegistration);
return "index";
}
}
DAO
package com.ecom.DAOImplementation;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import com.ecom.DAO.CustomerRegDAO;
import com.ecom.Model.CustomerRegistration;
#Repository("CustomerRegDAO")
#Transactional
public class CustomerRegDAOImpl implements CustomerRegDAO {
private SessionFactory sessionFactory;
#Transactional
public void saveCustomer(CustomerRegistration theCustomerRegistration) {
Session currentsession = sessionFactory.getCurrentSession();
currentsession.saveOrUpdate(theCustomerRegistration);
}
}
Error:
Type Exception Report
Message Servlet.init() for servlet [spring] threw exception
Description The server encountered an unexpected condition that prevented
it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet.init() for servlet [spring] threw
exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase
.java:475)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogVa
lve.java:651)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)
Root cause
org.springframework.beans.factory.BeanCreationException: Error creating
bean
with name 'sessionFactory' defined in
com.ecom.Config.AnnotationConfigApplicationContext: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw
exception; nested exception is java.lang.NoClassDefFoundError: Could not
initialize class
org.hibernate.annotations.common.reflection.java.JavaReflectionManager
java.lang.NoClassDefFoundError: Could not initialize class
org.hibernate.annotations.common.reflection.java.JavaReflectionManager
The exception is indicating that the class JavaReflectionManager is not found. This class is present in hibernate-commons-annotations jar file. Can you add this in your pom.xml and try running it again?
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.2.Final</version>
</dependency>

Spring MVC with hibernate in an ear application using only annotation is not working

I have created ear project with one web module and one EJB module.
I'm using web module for Spring MVC view and controller. Model, service and repository are maintained in ejb module. (tried in JAR module as well).
I'm getting exception like, [springframework.web.servlet.DispatcherServlet] (ServerService Thread Pool -- 168) Context initialization failed: java.lang.IllegalStateException: Cannot load configuration class: com.sakthi.core.config.HibernateConfiguration Exception.
My HibernateConfiguration class is,
package com.sakthi.core.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class HibernateConfiguration {
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.sakthi.core.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
My Complete project is copied in github URL: https://github.com/newway86/Spring4MVCHibernateEAR/tree/master/myapp
Please help me... I'm trying for 2 months. Not yet getting the sollution.
This actual program has been taken from this URL: http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/
If I try the above example in web project, its working fine. But not working while I create it as a ear project and moved the core logics to the ejb module.

spring web-mvc 4 java config doesn't work

I'm trying to run elementary spring-4 web-mvc application without xml configuration at all. I've looked spring documentation and examples, but it didn't work for me.
My controller:
package com.nikolay.exam.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class HomeController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
#ResponseBody
public String home() {
return "Hello world!";
}
}
AppConfig:
package com.nikolay.exam.config;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AppConfig {
}
WebConfig:
package com.nikolay.exam.config;
import com.nikolay.exam.controller.HomeController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public HomeController homeController() {
return new HomeController();
}
}
And WebInitializer:
package com.nikolay.exam.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.setConfigLocation("com.nikolay.exam.config");
servletContext.addListener(new ContextLoaderListener(root));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(root));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}
But when I run my application on tomcat I receive an error:
14-Feb-2015 11:35:29.825 WARNING [http-nio-8080-exec-1] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/home/] in DispatcherServlet with name 'dispatcher'
14-Feb-2015 11:35:32.766 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /home/nikolay/apache-tomcat-8.0.9/webapps/manager
14-Feb-2015 11:35:32.904 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /home/nikolay/apache-tomcat-8.0.9/webapps/manager has finished in 136 ms
14-Feb-2015 11:35:34.888 WARNING [http-nio-8080-exec-3] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/home/] in DispatcherServlet with name 'dispatcher'
I think it's the way you register your config class that is not correct.
Try using the AnnotationConfigWebApplicationContext#register instead.
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(WebConfig.class);
Probably you need to change
dispatcher.addMapping("/*");
to
dispatcher.addMapping("/");

Categories