Spring Cloud DataFlow and MySQL doesn't show the START_TIME and END_TIME of the Task - spring

I'm working on Spring batch and SCDF example. In this example I am reading CSV file and loading all the data to MySQL. I was able to successfully load the data into MySQL DB, but but UI doesn't show me START_TIME and END_TIME, even db doesn't holds any records.
I've uploaded my code here: https://github.com/JavaNeed/spring-cloud-dataflow-example1.git
spring-cloud-data-flow-server
SpringCloudDataFlowServerApplication.java
#EnableDataFlowServer
#SpringBootApplication(exclude = { CloudFoundryDeployerAutoConfiguration.class})
public class SpringCloudDataFlowServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudDataFlowServerApplication.class, args);
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.cloud.dataflow.features.streams-enabled=false
#spring.cloud.dataflow.rdbms.initialize.enable=false
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 https://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.2.6.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>spring-cloud-data-flow-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-cloud-data-flow-server</name>
<description>Demo project for Spring Boot</description>
<properties>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<spring-cloud-starter-dataflow-server.version>2.4.2.RELEASE</spring-cloud-starter-dataflow-server.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-dataflow-server</artifactId>
<version>${spring-cloud-starter-dataflow-server.version}</version>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>6.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
JobConfig.java
#Configuration
public class JobConfig {
#Autowired
private StepBuilderFactory stepBuilderFactory;
#Autowired
private JobBuilderFactory jobBuilderFactory;
#Autowired
private DataSource dataSource;
#Bean
public FlatFileItemReader<Customer> customerItemReader(){
FlatFileItemReader<Customer> reader = new FlatFileItemReader<>();
reader.setLinesToSkip(1);
reader.setResource(new ClassPathResource("/data/customer.csv"));
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
tokenizer.setNames(new String[] {"id", "firstName", "lastName", "birthdate"});
DefaultLineMapper<Customer> customerLineMapper = new DefaultLineMapper<>();
customerLineMapper.setLineTokenizer(tokenizer);
customerLineMapper.setFieldSetMapper(new CustomerFieldSetMapper());
customerLineMapper.afterPropertiesSet();
reader.setLineMapper(customerLineMapper);
return reader;
}
#Bean
public JdbcBatchItemWriter<Customer> customerItemWriter(){
JdbcBatchItemWriter<Customer> writer = new JdbcBatchItemWriter<>();
writer.setDataSource(this.dataSource);
writer.setSql("INSERT INTO CUSTOMER VALUES (:id, :firstName, :lastName, :birthdate)");
writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>());
writer.afterPropertiesSet();
return writer;
}
#Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.<Customer, Customer> chunk(10)
.reader(customerItemReader())
.writer(customerItemWriter())
.build();
}
#Bean
public Job job() {
return jobBuilderFactory.get("job")
.incrementer(new RunIdIncrementer())
.start(step1())
.build();
}
}
application.properties
# MYSQL DB Details
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.schema=org/springframework/batch/core/schema-mysql.sql
spring.batch.initialize-schema=ALWAYS
#spring.batch.schema=classpath:schema-mysql.sql

From a brief review of databaseOutput application, it appears you aren't using Spring Cloud Task.
Today, SCDF recognizes, resolves, and automates the orchestration of Spring Cloud Stream and Spring Cloud Task applications natively. While other workloads (including polyglot) are possible, only these two types of applications are treated with more care and automation.
In your case, in particular, even if your batch-job successfully did its thing, the transaction boundary is only governed if the batch-job application is wrapped as a Spring Cloud Task application, which is the reason why you don't see transactions recorded in SCDF's database. Likewise, the UI/Shell/API won't show such details either.
I would recommend reviewing the batch developer guide in entirety. Perhaps repeat the guide as-is first to get a feel of how things come together. Once when you get to see them in action (esp. spring-cloud-task boundaries), you will then be able to retrofit your app to comply with the foundational-level expectations.

Related

FF4J - Spring Boot - Custom Authorization Manager

I am trying to create a standalone feature flag server (centrally managed feature flag micro-service) backed by spring boot starters provided by FF4J. I was able to get it up and running with the web-console and REST API as well. I am now trying to just add the support of custom authorization manager as provided in the wiki, but based on the sample provided there, I am unclear as to how the authorization manager would be aware of the user context when it gets accessed from a different microservice which is implementing the feature. Below I have provided all the relevant code snippets. If you notice in CustomAuthorizationManager class, I have a currentUserThreadLocal variable, not sure how or who is going to set that at run time for FF4J to verify the user's role. Any help on this is really appreciated, as I having issues understanding how this works.
Also note, there is a toJson method in authorization manager that needs to be overridden, not sure what needs to go over there, any help with that is also appreciated.
Custom Authorization Manager
public class CustomAuthorizationManager implements AuthorizationsManager {
private static final Logger LOG = LoggerFactory.getLogger(FeatureFlagServerFeignTimeoutProperties.class);
private ThreadLocal<String> currentUserThreadLocal = new ThreadLocal<String>();
private List<UserRoleBean> userRoles;
#Autowired
private SecurityServiceFeignClient securityServiceFeignClient;
#PostConstruct
public void init() {
try {
userRoles = securityServiceFeignClient.fetchAllUserRoles();
} catch (Exception ex) {
LOG.error("Error while loading user roles", ex);
userRoles = new ArrayList<>();
}
}
#Override
public String getCurrentUserName() {
return currentUserThreadLocal.get();
}
#Override
public Set<String> getCurrentUserPermissions() {
String currentUser = getCurrentUserName();
Set<String> roles = new HashSet<>();
if (userRoles.size() != 0) {
roles = userRoles.stream().filter(userRole -> userRole.getUserLogin().equals(currentUser))
.map(userRole -> userRole.getRoleName()).collect(Collectors.toSet());
} else {
LOG.warn(
"No user roles available, check startup logs to check possible errors during loading of user roles, returning empty");
}
return roles;
}
#Override
public Set<String> listAllPermissions() {
Set<String> roles = new HashSet<>();
if (userRoles.size() != 0) {
roles = userRoles.stream().map(userRole -> userRole.getRoleName()).collect(Collectors.toSet());
} else {
LOG.warn(
"No user roles available, check startup logs to check possible errors during loading of user roles, returning empty");
}
return roles;
}
#Override
public String toJson() {
return null;
}
}
FF4J config
#Configuration
#ConditionalOnClass({ ConsoleServlet.class, FF4jDispatcherServlet.class })
public class Ff4jConfig extends SpringBootServletInitializer {
#Autowired
private DataSource dataSource;
#Bean
public ServletRegistrationBean<FF4jDispatcherServlet> ff4jDispatcherServletRegistrationBean(
FF4jDispatcherServlet ff4jDispatcherServlet) {
ServletRegistrationBean<FF4jDispatcherServlet> bean = new ServletRegistrationBean<FF4jDispatcherServlet>(
ff4jDispatcherServlet, "/feature-web-console/*");
bean.setName("ff4j-console");
bean.setLoadOnStartup(1);
return bean;
}
#Bean
#ConditionalOnMissingBean
public FF4jDispatcherServlet getFF4jDispatcherServlet() {
FF4jDispatcherServlet ff4jConsoleServlet = new FF4jDispatcherServlet();
ff4jConsoleServlet.setFf4j(getFF4j());
return ff4jConsoleServlet;
}
#Bean
public FF4j getFF4j() {
FF4j ff4j = new FF4j();
ff4j.setFeatureStore(new FeatureStoreSpringJdbc(dataSource));
ff4j.setPropertiesStore(new PropertyStoreSpringJdbc(dataSource));
ff4j.setEventRepository(new EventRepositorySpringJdbc(dataSource));
// Set authorization
CustomAuthorizationManager custAuthorizationManager = new CustomAuthorizationManager();
ff4j.setAuthorizationsManager(custAuthorizationManager);
// Enable audit mode
ff4j.audit(true);
return ff4j;
}
}
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>feature-flag-server</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>feature-flag-server</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.RC2</spring-cloud.version>
<ff4j.version>1.8.2</ff4j.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<exclusions>
<!-- resolve swagger dependency issue - start -->
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
<!-- resolve swagger dependency issue - end -->
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- FF4J dependencies - start -->
<dependency>
<groupId>org.ff4j</groupId>
<artifactId>ff4j-spring-boot-starter</artifactId>
<version>${ff4j.version}</version>
</dependency>
<dependency>
<groupId>org.ff4j</groupId>
<artifactId>ff4j-store-springjdbc</artifactId>
<version>${ff4j.version}</version>
</dependency>
<dependency>
<groupId>org.ff4j</groupId>
<artifactId>ff4j-web</artifactId>
<version>${ff4j.version}</version>
</dependency>
<!-- FF4J dependencies - end -->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Full disclosure I am the maintainer of the framework.
The documentation is not good on this part, improvements are in progress. But here is some explanation for a working project.
When using AuthorizationManager:
AuthorizationManager principle should be used only if you already enabled authentication in your application (LOGIN FORM, ROLES...). If not you can think about FlipStrategy to create your own predicates.
FF4j will rely on existing security frameworks to retrieve context of logged user, this is called the principal. As such this is unlikely for you to create your own custom implementation of AuthorizationManager except you are building your own authentication mechanism.
What to do:
You will use well known framework such as Spring Security of Apache Shiro to secure your applications and simply tell ff4j to rely on it.
How to do:
Here is working example using SPRING SECURITY:
https://github.com/ff4j/ff4j-samples/tree/master/spring-boot-2x/ff4j-sample-security-spring
Here is working example using APACHE SHIRO:
https://github.com/ff4j/ff4j-samples/tree/master/spring-boot-2x/ff4j-sample-security-shiro

How to solveFailed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured

I am trying to run a SpringBootApplication in EC2, i have hosted the mysql in RDS. While i was trying in my local database it was working fine, but as soon as i shifted to Rds the application is giving me the error
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to auto-configure a DataSource: 'spring.datasource.url' is not
specified and no embedded datasource could be auto-configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
I have googled and tried to add some configuration in the application , but it is not working for me
Here i am posting the class which the application is mentioning
AppUserDAO
#Repository
#Transactional
public class AppUserDAO {
#Autowired
private EntityManager entityManager;
public AppUser findUserAccount(String userName) {
try {
String sql = "Select e from " + AppUser.class.getName() + " e " //
+ " Where e.userName = :userName ";
Query query = entityManager.createQuery(sql, AppUser.class);
query.setParameter("userName", userName);
return (AppUser) query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
}
AppRoleDAO
#Repository
#Transactional
public class AppRoleDAO {
#Autowired
private EntityManager entityManager;
public List<String> getRoleNames(Long userId) {
String sql = "Select ur.appRole.roleName from " + UserRole.class.getName() + " ur " //
+ " where ur.appUser.userId = :userId ";
Query query = this.entityManager.createQuery(sql, String.class);
query.setParameter("userId", userId);
return query.getResultList();
}
}
UserDetailsServiceImpl
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
private AppUserDAO appUserDAO;
#Autowired
private AppRoleDAO appRoleDAO;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
AppUser appUser=this.appUserDAO.findUserAccount(username);
if(appUser==null) {
System.out.println("User not found! "+username);
throw new UsernameNotFoundException("User "+username+" was not found in the database");
}
System.out.println("Found User :"+appUser);
List<String> roleNames=this.appRoleDAO.getRoleNames(appUser.getUserId());
List<GrantedAuthority> grantList = new ArrayList<GrantedAuthority>();
if(roleNames!=null) {
for(String role:roleNames){
GrantedAuthority authority = new SimpleGrantedAuthority(role);
grantList.add(authority);
}
}
UserDetails userDetails=(UserDetails)new User(appUser.getUserName(),appUser.getEncrytedPassword(),grantList);
return userDetails;
}
}
Application.properties
==============================
# DATABASE
# ===============================
spring.datasource.url=jdbc:mysql://myrdsinstance.ciswboatdreq.us-east-1.rds.amazonaws.com/rdsTest
pom.xml
<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>org.o7planning</groupId>
<artifactId>SpringBootSecurityJPA</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBootSecurityJPA</name>
<description>Spring Boot +Spring Security + JPA + Remember
Me</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</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-data-jpa</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>org.o7planning.sbsecurity.SpringBootSecurityJpaApplication</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Please help me to resolve this
Try this...
#PersistenceContext
private EntityManager entityManager;
EDIT
After Edits in Question
Failed to auto-configure a DataSource: 'spring.datasource.url' is notspecified and no embedded datasource could be auto-configured.
Reason: Failed to determine a suitable driver class
You have to mention the Driver of mysql in application.properties
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
(or)
spring.datasource.driverClassName=com.mysql.jdbc.Driver
Try to inject EntityManager dependency by constructor in your DAOs, not a field.
Moreover, you could also initialize your bean in your main Spring Boot application class, doing something like this:
#Bean
public EntityManager entityManager() {
return new EntityManager();
}

When Spring boot project war deployed in tomcat 8 server not working for serving images

Web config for static resources
#Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("/**").addResourceLocations("file:///C:/test/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Project 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.test</groupId>
<artifactId>test</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>project</name>
<description>test.</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<jersey.version>2.7</jersey.version>
<guava.version>18.0</guava.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</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-security</artifactId>
</dependency>
<!-- Dependencies for GuavaCacheManager -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<!-- Dependencies for Unit Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.11</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application configuration
#Configuration
#SpringBootApplication
#EnableTransactionManagement
#EnableCaching
#EnableAsync
#EnableAutoConfiguration
#EnableScheduling
#ComponentScan
public class Application {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Entry point for the application.
*
* #param args
* Command line arguments.
* #throws Exception
* Thrown when an unexpected Exception is thrown from the
* application.
*/
public static void main(final String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
/**
* Create a CacheManager implementation class to be used by Spring where
*
<code>#Cacheable</code> annotations are applied.
*
* #return A CacheManager instance.
*/
#Bean
public CacheManager cacheManager() {
final GuavaCacheManager cacheManager = new GuavaCacheManager("greetings");
return cacheManager;
}
/**
* Supplies a PasswordEncoder instance to the Spring ApplicationContext. The
* PasswordEncoder is used by the AuthenticationProvider to perform one-way
* hash operations on passwords for credential comparison.
*
* #return A PasswordEncoder.
*/
#Bean
public PasswordEncoder passwordEncoder() {
this.logger.info("passwordEncoder");
return new BCryptPasswordEncoder();
}
public #Bean MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(new MongoClient("127.0.0.1"), "test");
return mongoTemplate;
}
}
In eclipse if I start spring boot application, then application serving images for this url
http://localhost:8080///////images//profile//APM1184//originalImage_7a7zke527_.jpeg
If I deploy war file of this project in local tomcat 8 and start. This URL is not working saying 404 not found.
I have posted my code. please correct me where I went wrong.
Having hard coded resource locations and mongo hosts is going to make it hard for you to manage your application. I would recommend moving those values into a configuration file. At the same time I would recommend using relative or root directory locations for resources instead of having the C:\ in the path as that won't work for deployments to Linux or other environments where the resource isn't on the C:\. My guess is that Tomcat isn't allowing the application to read from that external location due to some security constraints on the Tomcat installation.
I would recommend reading this Getting Started Guide on serving static content: https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot

Where I should place the jsp files in a spring-boot project

Recently, I start to work with the spring-boot, and I am trying convert my old spring projects, all of them being web applications, to use this. I manage to compile, package and run the application, but when I try access them in the browser, I can't reach out my views.
First, I try put the jsp pages in the usual folder src/main/webapp/WEB-INF/jsp, but after read this article from official documentation:
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-spring-mvc-static-content
I try put them in the folder src/main/resources. None of this works. Anyone can tell me where I should put this files to allow them be acessible when the application is running?
My pom.xml is this:
<?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.spring</groupId>
<artifactId>app</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.8.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<start-class>com.spring.app.Application</start-class>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I have this controller to map the views:
#Controller
public class AcessoController {
#RequestMapping(value = "/signin")
public String signin(Model model) {
return "acesso/signin";
}
#RequestMapping(value = "/admin")
public String admin(Model model) {
return "private/admin";
}
#RequestMapping(value = "/index")
public String index(Model model) {
return "public/index";
}
}
and this configuration classes:
WebAppConfig.java
#EnableWebMvc
#Configuration
#ComponentScan(value="com.spring.app")
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
WebAppInitializer.java
#Order(value=1)
public class WebAppInitializer implements WebApplicationInitializer {
#SuppressWarnings("resource")
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebAppConfig.class);
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext jspContext = new AnnotationConfigWebApplicationContext();
jspContext.register(DispatcherConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(jspContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
DispatcherConfig.java
#Configuration
#Import(WebAppConfig.class)
public class DispatcherConfig {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
If using Jetty or Tomcat as embedded servlet container just change your packaging from jar to war, and launch it with java -jar ...

Spring Boot with JNDI Data Source

I have a new Spring Boot web application that I want to connect to a JNDI data source (a MySQL database defined in Tomcat's context.xml).
However when I attempt this, I always get the following exception;
org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database url for database type NONE. If you want an embedded database please put a supported on on the classpath.
This is despite my pom.xml containing the MySQL connector
<?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>org.test</groupId>
<artifactId>twojndi</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Two JNDI Data Sources</name>
<description>Two JNDI Data Sources Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.1.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</exclusion>
<exclusion>
<artifactId>tomcat-jdbc</artifactId>
<groupId>org.apache.tomcat</groupId>
</exclusion>
</exclusions>
</dependency>
<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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>org.test.twojndi.Application</start-class>
<java.version>1.7</java.version>
</properties>
<build>
<finalName>${artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I have defined my application.properties as follows to use the jndi-name property.
spring.datasource.jndi-name=java:comp/env/jdbc/twojndi_ds1
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
However despite that it seems Spring believes that an in-memory database should be used.
I am able to connect to the MySQL database if I define my application.properties as so
spring.datasource.url=jdbc:mysql://localhost:3306/twojndi_ds1
spring.datasource.username=twojndi
spring.datasource.password=twojndi
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
Can anyone help me connect to JNDI with Spring Boot?
As commented by M. Deinum, JDNI lookup is implemented in Spring Boot 1.2, current version is 1.2.0.M2.
If you want to do it with Spring Boot 1.1, you can define a bean like this:
#Bean
public DataSource dataSource() {
JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiName("jdbc/jndidatasource");
try {
jndiObjectFactoryBean.afterPropertiesSet();
} catch (NamingException e) {
LOGGER.error("Error while retrieving datasource with JNDI name jdbc/jndidatasource", e);
}
return (DataSource) jndiObjectFactoryBean.getObject();
}
For me it worked the following configuration, guided by the recipe exposed in this link, but as they said before the same work with versions of spring boot 1.2 or more
public class DomainAndPersistenceJndi {
private JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(true);
hibernateJpaVendorAdapter.setDatabase(Database.INFORMIX);
hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate...");
return hibernateJpaVendorAdapter;
}
#Bean(name = "dataSourcejndi")
public DataSource dataSourcejndi() throws NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:jboss/datasources/..." );
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
return (DataSource) bean.getObject();
}
#Bean(name = "entityManagerFactoryJndi")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryJndi(#Qualifier("dataSourcejndi") DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource( dataSource);
em.setPackagesToScan(EntidadBase.class.getPackage().getName());
em.setJpaVendorAdapter(jpaVendorAdapter());
em.setPersistenceUnitName("BaseDSjdni");
em.afterPropertiesSet();
return em;
}
}

Resources