Spring Boot Failure due to Transaction Management - spring

I am currently developing an application using spring boot with cassandra as the database.
I have written a class which initializes my cassandra cluster. The problem starts as soon as I start using #Transactional in my DAO Layer Query Methods. System doesn't allow me to use them at a below error message is thrown at runtime -
An exception has occured in method getMdoBean with msg: No qualifying bean of type 'org.springframework.transaction.PlatformTransactionManager' available.
I don't understand what is going wrong. My app works fine without spring boot with no issues related to Transaction Management.
I tried adding JPA Support along with H2 Database and it resolved my problem. I did my homework and read about H2 Database and its in-memory data storage mechanism. I am failing to understand how is TransactionManagement issue is getting fixed? Is it because of H2 Database drivers which are taking care of it?
Secondly, I don't need H2 Database hence this solution does not seems to be good for me. Backend is Cassandra for my application. Any leads would be helpful. Thanks!
POM
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.shc.sov</groupId>
<artifactId>SOV</artifactId>
<version>4.4.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SOV</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<org.springframework.version>4.1.4.RELEASE</org.springframework.version>
<jersey.version>1.14</jersey.version>
<maven.antrun.plugin.version>1.8</maven.antrun.plugin.version>
<java.version>1.8</java.version>
</properties>
<repositories>
<repository>
<id>shc-central</id>
<name>Sears Libraries</name>
<url>http://obuartifactoryvip.prod.ch3.s.com/artifactory/libs-release</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>shc-snapshots</id>
<name>Sears Snapshot Libraries</name>
<url>http://obuartifactoryvip.prod.ch3.s.com/artifactory/libs-snapshot</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<build>
<finalName>dpsserver</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>prod/*.*</exclude>
<exclude>qa/*.*</exclude>
<exclude>stress/*.*</exclude>
<exclude>dev/*.*</exclude>
<exclude>dev-spring-boot</exclude>
</excludes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>config</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptor>config.xml</descriptor>
<attach>true</attach>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<!-- Always download and attach dependencies source code -->
<downloadSources>true</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
<!-- Avoid type mvn eclipse:eclipse -Dwtpversion=2.0 -->
<wtpversion>2.0</wtpversion>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<Class-Path>config/</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.3.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Core utilities used by other modules. Define this if you use Spring
Utility APIs (org.springframework.core.*/org.springframework.util.*) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency> -->
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- In memory database used by spring-boot -->
<!-- <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency> -->
<dependency>
<groupId>com.searshc.dce.persistence</groupId>
<artifactId>DcePersistence</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<artifactId>jaxb-impl</artifactId>
<groupId>com.sun.xml.bind</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<!-- <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency> -->
<!-- https://mvnrepository.com/artifact/log4j/apache-log4j-extras -->
<dependency>
<groupId>log4j</groupId>
<artifactId>apache-log4j-extras</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- <dependency> <groupId>javax.ws.rs</groupId> <artifactId>jsr311-api</artifactId>
<version>1.1.1</version> </dependency> -->
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<artifactId>spring-aop</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.7-b41</version>
</dependency>
<!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId>
<version>2.5</version> <scope>provided</scope> </dependency> -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.2</version>
</dependency>
<!-- Unit test level dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency>
<!-- <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId>
<version>1.9.5</version> <scope>test</scope> </dependency> -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-cassandra</artifactId>
<version>1.4.6.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Compilation Level Dependencies -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>${maven.antrun.plugin.version}</version>
<scope>compile</scope>
</dependency>
<!-- DATASTAX -->
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>2.1.4</version>
</dependency>
<!-- DATASTAX -->
</dependencies>
</project>
Cassandra Configuration Class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.cassandra.config.CassandraClusterFactoryBean;
import org.springframework.data.cassandra.config.CassandraSessionFactoryBean;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.convert.CassandraConverter;
import org.springframework.data.cassandra.convert.MappingCassandraConverter;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.data.cassandra.core.CassandraTemplate;
import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext;
import org.springframework.data.cassandra.mapping.CassandraMappingContext;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;
import com.datastax.driver.core.PlainTextAuthProvider;
#Configuration
#ImportResource("application-context.xml")
#PropertySource(value = { "classpath:cassandra.properties" })
#EnableCassandraRepositories(basePackages = {"com.spring.sample"})
public class CassandraDsConfig {
#Autowired
private Environment env;
#Bean
public CassandraClusterFactoryBean configureCassandraCluster() {
CassandraClusterFactoryBean clusterFactory = new CassandraClusterFactoryBean();
clusterFactory.setContactPoints(env.getProperty("cassandra.Newcontactpoints"));
clusterFactory.setPort(Integer.parseInt(env.getProperty("cassandra.Newport")));
PlainTextAuthProvider plainTextAuthProvider = new PlainTextAuthProvider(env.getProperty("cassandra.username"),
env.getProperty("cassandra.password"));
clusterFactory.setAuthProvider(plainTextAuthProvider);
return clusterFactory;
}
#Bean
public CassandraMappingContext mappingContext() {
return new BasicCassandraMappingContext();
}
#Bean
public CassandraConverter converter() {
return new MappingCassandraConverter(mappingContext());
}
#Bean
public CassandraSessionFactoryBean session() throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(configureCassandraCluster().getObject());
session.setKeyspaceName(env.getProperty("cassandra.Newkeyspace"));
session.setConverter(converter());
session.setSchemaAction(SchemaAction.NONE);
return session;
}
#Primary
#Bean("cassandraNewTemplate")
public CassandraOperations cassandraNewTemplate() throws Exception {
return new CassandraTemplate(session().getObject());
}
}
Spring Boot Main Class
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
//import org.springframework.context.annotation.PropertySource;
import org.springframework.boot.Banner;
/**
* #author bnarula
*
*/
#SpringBootApplication
#ImportResource("application-context.xml")
#Import(CassandraDsConfig.class)
#PropertySource("dps.properties")
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
#ComponentScan(basePackages = "com.shc.marketplace.ias")
public class DPSMainModule extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return configureApplication(builder);
}
public static void main(String[] args) {
configureApplication(new SpringApplicationBuilder()).run(args);
}
private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) {
return builder.sources(DPSMainModule.class).bannerMode(Banner.Mode.OFF);
}
}
DAO Layer Class for Caching -
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.transaction.annotation.Transactional;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.core.querybuilder.Select;
import com.searshc.dce.persistence.DcePersistence.dao.beans.FreightAreaBean;
import com.searshc.dce.persistence.DcePersistence.dao.beans.FreightAreaPOJO;
import com.shc.scinventory.dps.server.dao.CacheBuilderDAO;
import com.shc.scinventory.dps.server.model.StoretoRRCPOJO;
import com.shc.scinventory.dps.server.model.ZiptoWarehousePOJO;
public class CacheBuilderDAOImpl implements CacheBuilderDAO {
private static Logger logger = Logger.getLogger(CacheBuilderDAOImpl.class);
private Map<String, String> storeToRRCMap = new HashMap<String, String>();
private Map<String, String> ziptoWarehouseMap = new HashMap<String, String>();
private Map<String, List<FreightAreaBean>> zipToFaMap = new HashMap<String, List<FreightAreaBean>>();
List<StoretoRRCPOJO> storeToRRCList = new ArrayList<StoretoRRCPOJO>();
public List<StoretoRRCPOJO> getStoreToRRCList() {
return storeToRRCList;
}
public void setStoreToRRCList(List<StoretoRRCPOJO> storeToRRCList) {
this.storeToRRCList = storeToRRCList;
for (StoretoRRCPOJO storetoRRCBean : storeToRRCList) {
storeToRRCMap.put(storetoRRCBean.getStore(), storetoRRCBean.getRrc());
}
}
#Autowired
private CassandraOperations cassandraOperations;
private String keyspace;
#Override
public void initStatements() {
logger.debug("CacheBuilderDAOImpl : Inside method init");
if (cassandraOperations == null) {
logger.error("Cassandra not available");
} else {
List<ZiptoWarehousePOJO> ziptoWarehouseList = getZiptoWarehouseMapping();
List<StoretoRRCPOJO> storetoRRCList = getStoretoRRCMapping();
for (ZiptoWarehousePOJO ziptoWarehouseBean : ziptoWarehouseList) {
ziptoWarehouseMap.put(ziptoWarehouseBean.getDestinationZip(), ziptoWarehouseBean.getDcUnit());
}
setStoreToRRCList(storetoRRCList);
refreshZipToFaMapping();
}
}
public void refreshZipToFaMapping() {
zipToFaMap = getZipToFAMapping();
}
#Transactional
public Map<String, List<FreightAreaBean>> getZipToFAMapping() {
logger.debug("Inside method getZipToFAMapping");
Map<String, List<FreightAreaBean>> result = new HashMap<String, List<FreightAreaBean>>();
try {
Select select = QueryBuilder.select().all().from("capacity", "freight_area");
List<FreightAreaPOJO> queryResult = cassandraOperations.select(select, FreightAreaPOJO.class);
for(FreightAreaPOJO faPOJO : queryResult) {
String zip = faPOJO.getGeocode_no();
if(!result.containsKey(zip)) {
result.put(zip, new LinkedList<FreightAreaBean>());
}
FreightAreaBean faBean = new FreightAreaBean();
BeanUtils.copyProperties(faPOJO, faBean);
result.get(zip).add(faBean);
}
} catch (Exception e) {
logger.error("getZipToFAMapping Error while fetch data from DB: " + e.getMessage());
e.printStackTrace();
}
logger.debug("Exiting method getZipToFAMapping");
return result;
}
public List<ZiptoWarehousePOJO> getZiptoWarehouseMapping() {
logger.debug("Inside method getZiptoWarehouseMapping");
List<ZiptoWarehousePOJO> result = null;
try {
Select select = QueryBuilder.select().all().from(getKeyspace(), "ziptowarehouse");
result = cassandraOperations.select(select, ZiptoWarehousePOJO.class);
} catch (Exception e) {
logger.error("getZiptoWarehouseMapping Error while fetch data from DB: " + e.getMessage());
}
logger.debug("Exiting method getZiptoWarehouseMapping");
return result;
}
public List<StoretoRRCPOJO> getStoretoRRCMapping() {
logger.debug("Inside method getStoretoRRCMapping");
List<StoretoRRCPOJO> result = null;
try {
Select select = QueryBuilder.select().all().from(getKeyspace(), "storetorrc");
result = cassandraOperations.select(select, StoretoRRCPOJO.class);
} catch (Exception e) {
logger.error("getStoretoRRCMapping Error while fetch data from DB: " + e.getMessage());
}
logger.debug("Exiting method getStoretoRRCMapping");
return result;
}
public String getKeyspace() {
return keyspace;
}
public void setKeyspace(String keyspace) {
this.keyspace = keyspace;
}
public Map<String, String> getStoreToRRCMap() {
return storeToRRCMap;
}
public void setStoreToRRCMap(Map<String, String> storeToRRCMap) {
this.storeToRRCMap = storeToRRCMap;
}
public Map<String, String> getZipToWarehouseMap() {
return ziptoWarehouseMap;
}
public void setZiptoWarehouseMap(Map<String, String> ziptoWarehouseMap) {
this.ziptoWarehouseMap = ziptoWarehouseMap;
}
public Map<String, List<FreightAreaBean>> getZipToFaMap() {
return zipToFaMap;
}
public void setZipToFaMap(Map<String, List<FreightAreaBean>> zipToFaMap) {
this.zipToFaMap = zipToFaMap;
}
}
If I use #Transactional in the above class at method level, it doesn't allow without adding H2 Support for JPA. It works fine after putting up below lines of code in POM.
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>

I guess the reason is you excluded HibernateJpaAutoConfiguration, is there any reason to do so, otherwise I will suggest you to add it back, maybe also add #EnableTransactionManagement to your config class.

Related

Status 200, but JSP in Spring only displaying un-rendered code

Although my index.jsp opens in a browser with a Status 200 it only displays the JSP code.
I've read through what seem to be all related issues/solutions on this site, but none of the solutions have worked. e.g. adding jstl, jasper, etc. jars into my pom.xml and build path; mapping variations like "/", "/*", etc. No errors in the Spring log- just that JSPs aren't rendering or being "seen" as JSPs. My newest theories are that something is over-writing or conflicting, or that Spring needs something to "see" JSPs under the WEB-INF folder, but it's not easy to debug. Seems a stupid thing that a JSP doesn't render, so any insight would be helpful.
AppConfig
package mil.dfas.springmvc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
* #author David Higgins
*/
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"mil.dfas.springmvc.controller"})
public class AppConfig {
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
LMSInitializer
package mil.dfas.springmvc.config;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import mil.dfas.filters.LoginFilter;
import mil.dfas.filters.TimeoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* The Spring MVC DispatcherServlet needs to be declared and mapped for all request processing.
* In a Servlet 3.0+ environment, AbstractAnnotationConfigDispatcherServletInitializer class is used to register and initialize the DispatcherServlet programmatically.
*
* #author $Author: David Higgins $
* #version $Revision: 1.0 $ $Date: 2019/05/12 $
*/
public class LMSInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger(LMSInitializer.class);
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
FilterRegistration timeoutFilter = servletContext.addFilter("timeoutFilter", new TimeoutFilter());
timeoutFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "*.do");
super.onStartup(servletContext);
}
#Override
protected Filter[] getServletFilters() {
LOGGER.info("LMSInitializer: Configuring Servlet Filters" );
LoginFilter loginFilter = new LoginFilter();
return new Filter[] {new LoginFilter()};
}
#Override
protected Class <?> [] getRootConfigClasses() {
return null;
}
#Override
protected Class <?> [] getServletConfigClasses() {
return new Class[] {AppConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
LMSController
package mil.dfas.springmvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
* #author David Higgins
*/
#Controller
public class LMSSpringController {
#RequestMapping(value = "/index", method = RequestMethod.POST)
public ModelAndView forward(Model model) {
System.out.println("LMS Controller");
model.addAttribute("msg","Forward Handled");
return new ModelAndView("index");
}
}
WEB-INF/views/index.jsp
No error messages. JSPs just don't displays as JSPs.
The problem must be something with the pom.xml. It must be a conflict with dependencies. I've added jasper, jstl, and others, but no change. Status 200 and no log errors, but no jsp rendering.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version> <!-- 2.1.5.RELEASE ? -->
<relativePath />
</parent>
<groupId>mil.dfas.springmvc</groupId>
<artifactId>EmployeeDevelopment</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<failOnMissingWebXml>false</failOnMissingWebXml>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring-boot-starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- I think maybe including servlet dependencies is forcing servlet version
to 4.0 since no versions are included, so Spring Boot parent will provide
the defaults and maybe force latest version (?) A lot of this servlet stuff
should already be included in Tomcat bin (on build path) -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<!-- <scope>provided</scope> -->
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>com.keypoint</groupId>
<artifactId>png-encoder</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.8.2</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.14</version>
</dependency>
<dependency>
<groupId>jfree</groupId>
<artifactId>jcommon</artifactId>
<version>1.0.16</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>xalan</groupId>
<artifactId>xalan</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<!-- As Oracle JDBC drivers are not in public Maven repositories (legal
reasons) downloading the jar was the best available option. -->
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>12.2.0.1</version>
<scope>system</scope>
<systemPath>${basedir}/src/lib/ojdbc8.jar</systemPath>
</dependency>
<!-- Added 5/17/19 DJM, may want to get directly from Maven repo -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mailapi</artifactId>
<version>1.4.3</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<!-- <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source>
<target>1.8</target> </configuration> -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Package as an executable jar/war -->
</plugins>
</build>
</project>

Bean of type 'org.springframework.web.reactive.function.client.WebClient' that could not be found

I'm studying push notifications using the example of this manual https://golb.hplar.ch/2018/01/Sending-Web-push-messages-from-Spring-Boot-to-Browsers.html.
I am faced with the problem that when I run the application, I get the error
Parameter 1 of constructor in ru.stepanb.MetricPushingApplication.push.PushChuckJokeService required could not be found.
Consider defining a bean of type 'org.springframework.web.reactive.function.client.WebClient' in your configuration. "
.
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
#Service
public class PushChuckJokeService {
private final FcmClient fcmClient;
private final WebClient webClient;
private int seq = 0;
public PushChuckJokeService(FcmClient fcmClient, WebClient webClient) {
this.fcmClient = fcmClient;
this.webClient = webClient;
}
#Scheduled(fixedDelay = 30_000)
public void sendChuckQuotes() {
IcndbJoke joke =
this.webClient.get().uri("http://api.icndb.com/jokes/random")
.retrieve().bodyToMono(IcndbJoke.class).block();
try {
sendPushMessage(joke);
}
catch (InterruptedException | ExecutionException e) {
//Application.logger.error("send chuck joke", e);
}
}
void sendPushMessage(IcndbJoke joke) throws InterruptedException,
ExecutionException {
Map<String, String> data = new HashMap<>();
data.put("id", String.valueOf(joke.getValue().getId()));
data.put("joke", joke.getValue().getJoke());
data.put("seq", String.valueOf(this.seq++));
data.put("ts", String.valueOf(System.currentTimeMillis()));
System.out.println("Sending chuck joke...");
this.fcmClient.send(data);
}
}
Here is my pom.xml file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru.stepanb</groupId>
<artifactId>MetricPushingApplication</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MetricPushingApplication</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.8.1</version>
<exclusions>
<exclusion>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-gson</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client-gson</artifactId>
</exclusion>
<exclusion>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId>
</exclusion>
<exclusion>
<groupId>org.threeten</groupId>
<artifactId>threetenbp</artifactId>
</exclusion>
<exclusion>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-firestore</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-storage</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.api</groupId>
<artifactId>gax</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-storage</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<debug>true</debug>
<parameters>true</parameters>
<annotationProcessorPaths>
<path>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>2.1.5.RELEASE</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
And my controller
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
#RestController
#CrossOrigin
public class RegistryController {
private final FcmClient fcmClient;
public RegistryController(FcmClient fcmClient) {
this.fcmClient = fcmClient;
}
#PostMapping("/register")
#ResponseStatus(HttpStatus.NO_CONTENT)
public Mono<Void> register(#RequestBody Mono<String> token) {
return token.doOnNext(t -> this.fcmClient.subscribe("chuck", t)).then();
}
}
Could you also explain to me how the creation of a WebClient occurs at all when Spring application is created by this line?
SpringApplication.run(MetricPushingApplication.class, args);
There is no WebClient registered as bean.
You can simply use it like this:
WebClient.create().get().uri("http://api.icndb.com/jokes/random")
.retrieve().bodyToMono(IcndbJoke.class).block();
Or you use it like described in the Spring Boot Reference Manual
#Service
public class MyService {
private final WebClient webClient;
public MyService(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl("https://example.org").build();
}
public Mono<Details> someRestCall(String name) {
return this.webClient.get().uri("/{name}/details", name)
.retrieve().bodyToMono(Details.class);
}
}
See: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#io.rest-client.webclient
You should config the bean in the Configuration Class. For example:
#Configuration
class Configuration{
#Bean
WebClient webClient(WebClient.Builder builder) {
return builder.build();
}
}
And then you could use the webClient dependency in other class. For Example:
class otherClass{
private WebClient client;
//Your use
}
You should update the dependency to resolve the issue of 'org.springframework.web.reactive.function.client.WebClient' that could not be found
compile 'org.springframework.boot:spring-boot-starter-webflux:2.6.1'
Please see this answer already posted.

maven project using rest controller and gave a basic request and gives 404. url : http://localhost:8080/Spring4MVCHelloWorldRestServiceDemo/testrest

I created a maven project using rest controller and gave a basic request but it is not hitting the method and gives 404.i am new to the rest controller. So it would be great if someone try to narrow down the issue.
the url : http://localhost:8080/Spring4MVCHelloWorldRestServiceDemo/testrest
HelloController
package com.fis.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class HelloController {
#RequestMapping(value="/testrest", method = RequestMethod.GET)
public String welcome() {//Welcome page, non-rest
System.out.println("Test++++++++++++++");
return "Welcome to RestTemplate Example.";
}
/* #RequestMapping("/hello/{player}")
public Message message(#PathVariable String player) {//REST Endpoint.
Message msg = new Message(player, "Hello " + player);
return msg;
}*/
}
HelloInitialization
package com.fis.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class HelloInitialization extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { HelloConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
HelloConfiguration
package com.fis.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"com.fis.controller"})
public class HelloConfiguration {
}
http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.websystique.springmvc</groupId>
<artifactId>Spring4MVCHelloWorldRestServiceDemo</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>
<name>Spring4MVCHelloWorldRestServiceDemo Maven Webapp</name>
<properties>
<springframework.version>4.3.0.RELEASE</springframework.version>
<jackson.library>2.7.5</jackson.library>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.library}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.library}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>Spring4MVCHelloWorldRestServiceDemo</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>Spring4MVCHelloWorldRestServiceDemo</finalName>
</build>

Make a java client to connect to spring boot websocket with spring security

I am trying to make a java websocket. Project is having Spring Security enabled. When I am trying to connect to websocket, I am getting following error
The HTTP response from the server [200] did not permit the HTTP upgrade to WebSocket
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>iot</groupId>
<artifactId>websocket</artifactId>
<version>0.1.0</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-messaging</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.azure.sdk.iot</groupId>
<artifactId>iot-device-client</artifactId>
<version>1.3.32</version>
</dependency>
<dependency>
<groupId>org.rxtx</groupId>
<artifactId>rxtx</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<!-- Joda-Time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<!-- To map JodaTime with database type -->
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>3.0.0.CR1</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
<dependency>
<groupId>com.neovisionaries</groupId>
<artifactId>nv-websocket-client</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- Added Last -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<!-- Azure -->
<dependency>
<groupId>com.microsoft.azure.sdk.iot</groupId>
<artifactId>iot-service-client</artifactId>
<version>1.7.23</version>
</dependency>
<dependency>
<groupId>com.microsoft.azure.sdk.iot</groupId>
<artifactId>iot-device-client</artifactId>
<version>1.3.32</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-servicebus</artifactId>
<version>0.9.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
Websocket Security Configuration
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry;
import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer;
#Configuration
public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
#Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.nullDestMatcher().authenticated()
.simpSubscribeDestMatchers("/datasocket","/ehmdatasocket").permitAll()
.anyMessage().permitAll();
}
#Override
protected boolean sameOriginDisabled() {
return true;
}
}
Websocket Server Configuration
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;
import com.ey.iotsphereeg.websocket.ServerWebSocketHandler;
#Configuration
#EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new ServerWebSocketHandler(), "/datasocket");
}
}
Websocket server handler
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
#Component
public class ServerWebSocketHandler extends TextWebSocketHandler {
public List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
#Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws InterruptedException, IOException {
//System.out.println(message.getPayload());
JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(message.getPayload());
} catch (ParseException e1) {
e1.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;
//int size = sessions.size();
if (!jsonObject.containsKey("test"))
sendAll(message);
}
#Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// the messages will be broadcasted to all users.
System.out.println(session.toString());
//test.session = session;
sessions.add(session);
int s = sessions.size();
System.out.println(s);
}
#Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// the messages will be broadcasted to all users.
sessions.remove(session);
}
#Override
public void handleTransportError(WebSocketSession session, Throwable exception)throws Exception {
// the messages will be broadcasted to all users.
sessions.remove(session);
}
public void sendAll(TextMessage message) {
try {
int size = sessions.size();
System.out.println(size);
ArrayList<WebSocketSession> closedSessions = new ArrayList<>();
for (WebSocketSession session : sessions) {
if (!session.isOpen()) {
System.err.println("Closed session: " + session.getId());
closedSessions.add(session);
} else {
System.out.println(message.getPayload());
session.sendMessage(message);
}
}
sessions.removeAll(closedSessions);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
Websocket Client
import javax.websocket.ClientEndpoint;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
#ClientEndpoint
public class MyClient {
#OnOpen
public void onOpen(Session session) {
System.out.println("##### Websocket Client Connected to endpoint: " + session.getAsyncRemote());
}
#OnMessage
public void onMessage(String message) {
// System.out.println(message);
}
#OnError
public void onError(Throwable t) {
t.printStackTrace();
}
}
Now when I am trying to connect without Spring Security enabled, It is working but when Spring boot Security is enable, I am not able to make handshake.
I tried reading documentations and tried to search on internet for long, but I didn't get proper solutions.

Spring Seccurity Java based Configuration not working. It will always show index.jsp page

I am converting my simple demo project from bean configuration to pure java based configuration. there small problem some where but i cannot find where it occurs please help me. I use this tutorial for build my project
Spring Security 4 Hello World Annotation+XML Example
but there small defferent between this project and my project that is project maven archetype my one is multi module maven project.
here is my project archetype
following files are the I used for do my configuration
This pom is the root pom and each module has there own poms. this pom is inside the sms module
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.geek</groupId>
<artifactId>sms</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>sms</name>
<properties>
<spring.version>4.2.0.RELEASE</spring.version>
<spring-security.version>4.0.2.RELEASE</spring-security.version>
<jstl.version>1.2</jstl.version>
<junit.version>3.8.1</junit.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
<defaultGoal>install</defaultGoal>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>webapp</warSourceDirectory>
<warName>sms-web</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>smsweb</finalName>
</build>
<modules>
<module>sms-core</module>
<module>sms-web</module>
</modules>
<dependencies>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.0</version>
</dependency>
<!-- Spring data mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-digester</groupId>
<artifactId>commons-digester</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
</project>
AppConfig.java
package com.geek.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = "com.geek.*" )
public class AppConfig {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
SecurityConfig.java
package com.geek.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");//dba have two roles.
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.and().formLogin()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
SpringMvcInitializer.java
package com.geek.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
SpringSecurityInitializer.java
package com.geek.config;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
LoginController.java
package com.geek.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LoginController {
#RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String homePage(ModelMap model) {
model.addAttribute("greeting", "Hi, Welcome to mysite. ");
return "welcome";
}
#RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(ModelMap model) {
model.addAttribute("user", getPrincipal());
return "admin";
}
#RequestMapping(value = "/db", method = RequestMethod.GET)
public String dbaPage(ModelMap model) {
model.addAttribute("user", getPrincipal());
return "dba";
}
#RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null){
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "welcome";
}
#RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
model.addAttribute("user", getPrincipal());
return "accessDenied";
}
private String getPrincipal(){
String userName = null;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
userName = ((UserDetails)principal).getUsername();
} else {
userName = principal.toString();
}
return userName;
}
}
what was i expected is when i am trying to log into my application using this
http://localhost:8080/sms-web I need redirect to the login.jsp page or something any other page but this will redirect to the index.jsp.
when i am trying to run this sms-web.war using external tomcat and put my war file into webapps folder it will end up with error like this
> uring scanning can improve startup time and JSP compilation time.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further
details.
11-Jun-2017 14:18:55.435 SEVERE [localhost-startStop-1]
org.apache.catalina.core.ContainerBase.addChildInternal
ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component
[StandardEngine[Catalina].StandardHost[localhost].StandardContext[/sms-web]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NoSuchMethodError:
org.springframework.core.annotation.AnnotationAwareOrderComparator.sort(Ljava/util/List;)V
at
org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:171)
at
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5178
)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 10 more
11-Jun-2017 14:18:55.435 SEVERE [localhost-startStop-1]
org.apache.catalina.startup.HostConfig.deployWAR Error deploying web
application archive F:\Pe
rsonal\Cingle Eve\Server\apache-tomcat-8.5.9\webapps\sms-web.war
java.lang.IllegalStateException: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: Failed to start component
[StandardEngine[Cat
alina].StandardHost[localhost].StandardContext[/sms-web]]
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:756)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:952)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1823)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
11-Jun-2017 14:18:55.455 INFO [localhost-startStop-1]
org.apache.catalina.startup.HostConfig.deployWAR Deployment of web
application archive F:\Person
al\Cingle Eve\Server\apache-tomcat-8.5.9\webapps\sms-web.war has finished in
3,913 ms
What's wrong I did please help me to the find the answer...
Looks like you have a mess in your dependencies mixing different spring versions. Try using dependencies below:
<dependencies>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring-security.version}</version>
</dependency>
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>${mongo-driver.version}</version>
</dependency>
<!-- Spring data mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring-data.version}</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>${cglib.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>${servlet-jsp-api.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-digester3</artifactId>
<version>${commons-digester.version}</version>
</dependency>
</dependencies>
With following properties:
<properties>
<spring.version>4.3.9.RELEASE</spring.version>
<spring-security.version>4.2.3.RELEASE</spring-security.version>
<mongo-driver.version>3.4.2</mongo-driver.version>
<spring-data.version>1.10.4.RELEASE</spring-data.version>
<cglib.version>3.2.5</cglib.version>
<servlet-api.version>3.1.0</servlet-api.version>
<servlet-jsp-api.version>2.3.1</servlet-jsp-api.version>
<commons-digester.version>3.2</commons-digester.version>
<jstl.version>1.2</jstl.version>
<junit.version>4.12</junit.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
I've used latest spring version and updated few other dependencies.
Also in order to redirect to login page from index do the following:
.antMatchers("/", "/home").access("hasRole('ADMIN')")

Resources