How to add file .properties to spring boot with maven (Build Jar)? - java

I'm developing a web app with spring boot, I built the project with Maven.
In the project I use files .properties and I gave the path of the project like this:
Properties FileProperties = FileUtils.getProperties("src\main\resources\file.properties");
Running the project with IntelliJ, all work.
But at the moment I built with maven in Jar, and I open the web app, don't find the file properties and give NullPointerException.
This is my pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
This is the project map.
https://m.imgur.com/gallery/zZzTzID
Thanks so much
I tried this, but dont work.
ConfigProperties.java
package bperTube.transfer.Utils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
#Configuration
#PropertySource("classpath:file.properties")
#ConfigurationProperties(prefix = "upload")
public class ConfigProperties {
private String dateFormat;
private String directoryPath;
private String videoDirectory;
private String imageDirectory;
public String getDateFormat() {
return dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public String getDirectoryPath() {
return directoryPath;
}
public void setDirectoryPath(String directoryPath) {
this.directoryPath = directoryPath;
}
public String getVideoDirectory() {
return videoDirectory;
}
public void setVideoDirectory(String videoDirectory) {
this.videoDirectory = videoDirectory;
}
public String getImageDirectory() {
return imageDirectory;
}
public void setImageDirectory(String imageDirectory) {
this.imageDirectory = imageDirectory;
}
}
file.properties
upload.dateFormat=dd-MM-yyyy
upload.directoryPath=/test/
upload.videoDirectory=swf/
upload.imageDirectory=poster/

Related

RequestBody is not returning username - SpringBoot

I'm making a POST request to authenticate the API that I'm implementing, but I have the following problem:
My username is not being returned:
however, my password is, and I'm not understanding why:
Below I will be sending my source code for better understanding...
Class: AuthController.java
#RestController
#RequestMapping("/auth")
public class AuthController {
#Autowired
AuthenticationManager authenticationManager;
#Autowired
JwtTokenProvider jwtTokenProvider;
#Autowired
UserRepository repository;
#ApiOperation(value = "Authenticate a user by credentials") //Swagger endpoint description
#PostMapping(value="/signin", produces = { "application/json", "application/xml", "application/x-yaml" }, consumes = {
"application/json", "application/xml", "application/x-yaml" })
public ResponseEntity singin(#RequestBody AccountCredentialsVO data) throws Exception {
try {
var username = data.getUserName();
var password = data.getPassword();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
var user = repository.findByUserName(username);
var token = "";
if(user != null) {
token = jwtTokenProvider.createToken(username, user.getRoles());
}else {
throw new UsernameNotFoundException("Username " + username + " not found!");
}
Map<Object, Object> model = new HashMap<>();
model.put("username", username);
model.put("token", token);
return ok(model);
} catch (Exception e) {
throw new BadCredentialsException("Invalid username/password supplied!");
}
}
}
Class: AccountCredentialsVO.java
public class AccountCredentialsVO implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "username")
private String username;
private String password;
public String getUserName() {
return username;
}
public void setUserName(String userName) {
this.username = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public int hashCode() {
return Objects.hash(password, username);
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AccountCredentialsVO other = (AccountCredentialsVO) obj;
return Objects.equals(password, other.password) && Objects.equals(username, other.username);
}
}
The 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>br.com.andrefilipeos</groupId>
<artifactId>rest-with-springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<description>Creating API RESTFul with Spring Boot 2.x</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
</properties>
<dependencies>
<!-- for Spring-boot Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- for Tests Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.dozermapper</groupId>
<artifactId>dozer-core</artifactId>
<version>6.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- for XML support-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<!-- for YML or YAML support-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<!-- for HATEOAS Support -->
<dependency>
<groupId>org.springframework.hateoas</groupId>
<artifactId>spring-hateoas</artifactId>
</dependency>
<!-- for Swagger Support -->
<!-- http://localhost:8080/v2/api-docs -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- it's format all API documentation organized -->
<!-- http://localhost:8080/swagger-ui.html -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- for Security Support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- for Tokens Support -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<!-- for Migration support $mvn flyway:migrate -->
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<configuration>
<url>jdbc:mysql://localhost:3306/rest_with_springboot?useTimezone=true&serverTimezone=UTC&useSSL=false</url>
<user>root</user>
<password>admin123</password>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
My POST request:
http://localhost:8080/auth/signin
With XML (application/xml):
<AccountCredentialsVO>
<username>leandro</username>
<password>admin123</password>
</AccountCredentialsVO>
With JSON (application/json):
{
"username":"leandro",
"password":"admin123"
}
And unfortunately with both requests I'm getting the same result of null username!

Field required a bean which could not be found in springboot

I am creating a basic spring boot REST API. My project has the following structure:
com.anonreporting.springboot
--- SpringBootAnonReporting.java , config.java
com.anonreporting.springboot.controller -- userController.java
com.anonreporting.springboot.domain -- User.java
com.anonreporting.springboot.service -- UserService.java UserServiceImpl.java
com.anonreporting.springboot.repository -- userRepository.java
SpringBootAnonReporting.java
#SpringBootApplication
public class SpringBootAnonReporting {
public static void main(String[] args) throws ParseException {
ApplicationContext applicationContext = SpringApplication.run(SpringBootAnonReporting.class, args);
for (String name : applicationContext.getBeanDefinitionNames()) {
System.out.println(name);
}
}
}
User.java is a POJO class.
UserController
#Controller
public class UserController {
#Autowired
UserService userService;
#RequestMapping(value="/users",method=RequestMethod.GET)
ResponseEntity<Iterable<User>> listAllUsers()
{
return new ResponseEntity<Iterable<User>>(userService.listAllUsers(),HttpStatus.OK);
}
#RequestMapping(value="/newuser",method=RequestMethod.POST)
ResponseEntity registerUser(User user)
{
userService.saveUser(user);
return new ResponseEntity(HttpStatus.CREATED);
}
#RequestMapping(value="/get",method=RequestMethod.GET)
ResponseEntity<String> tryGet()
{
System.out.println("hihihih");
return new ResponseEntity<String>("HI",HttpStatus.OK);
}
}
UserService:
#Service
public interface UserService {
Iterable<User> listAllUsers();
User getUserById(String id);
User saveUser(User user);
void deleteUser(String id);
}
UserServiceImpl:
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Override
public Iterable<User> listAllUsers() {
// TODO Auto-generated method stub
return userRepository.findAll();
}
#Override
public User getUserById(String id) {
// TODO Auto-generated method stub
return userRepository.findOne(id);
}
#Override
public User saveUser(User user) {
// TODO Auto-generated method stub
return userRepository.save(user);
}
#Override
public void deleteUser(String id) {
// TODO Auto-generated method stub
userRepository.delete(id);
}
}
config.java
#Configurable
#Configuration
#EnableAutoConfiguration
#EnableTransactionManagement
public class Config {
public #Bean(destroyMethod = "close") AerospikeClient aerospikeClient() {
ClientPolicy policy = new ClientPolicy();
policy.failIfNotConnected = true;
policy.timeout = 2000;
return new AerospikeClient(policy, "172.28.128.3", 3000);
}
public #Bean AerospikeTemplate aerospikeTemplate() {
return new AerospikeTemplate(aerospikeClient(), "test");
}
}
UserRepository.java:
#Component
public interface UserRepository extends AerospikeRepository<User, String> {
}
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.example</groupId>
<artifactId>anonReporting</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>anonReporting</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aerospike/aerospike-client -->
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>aerospike-client</artifactId>
<version>4.1.9</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>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons-core -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons-core</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.0.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aerospike/spring-data-aerospike -->
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>spring-data-aerospike</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-keyvalue -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-keyvalue</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-cli/commons-cli -->
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
On running the code, the following error occurs:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userRepository in com.anonreporting.springboot.user.UserServiceImpl required a bean of type 'com.anonreporting.springboot.user.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.anonreporting.springboot.user.UserRepository' in your configuration.
What I have tried:
All other packages are a sub package of com.anonreporting.springboot, so i don't have to use component scan for them (correct me if i am wrong).
I have tried with componentScan as well with no success.
Moving everything in same package does help, but i want to structure it in this way only. I am using areospike with spring boot.
I have tried changing versions of dependencies also.
Any suggestions would be really helpful. Thank you
As far as I see you have not created UserRepository.java. Spring can not Autowire something that does not exist so you can try creating it in a package that is convenient for you. It should look something like this
#Repository
public interface UserRepository extends JpaRepository<User, Long>{}
You need to change annotation in your UserRepository.class from #Component to #Repository as spring-data is scanning for #Repository annotations.
The problem was with pom.xml only. I just replaced my pom with the following and everything worked.
<?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.example</groupId>
<artifactId>anonReporting</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>anonReporting</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.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-web</artifactId>
</dependency>
<dependency>
<groupId>com.aerospike</groupId>
<artifactId>spring-data-aerospike</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

How to get embedded Spring-Cloud-Server to read github properties file?

I am trying to embed a spring cloud server with git hub. Following this link right here.
Also following the following documentation
pom.xml
...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</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-security</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
...
</dependencies>
...
HelloWorldApplication.java
#SpringBootApplication
#EnableConfigServer
public class HelloWorldApplication {
public static void main(String[] args) {
SpringApplication.run(HelloWorldApplication.class, args);
}
}
HelloWorldController.java
#RestController
#RequestMapping("/hello")
#RefreshScope
public class HelloWorldController {
#Value("${prop1:default}") private String prop1;
#Value("${prop2:default}") private String prop2;
#RequestMapping(value = "/world", method = RequestMethod.GET)
public String getHelloWorld() {
return new StringBuilder()
.append("Message: ")
.append(prop1).append(" ")
.append(prop2).append("!")
.toString();
}
}
application.properties
server.port=8080
bootstrap.properties
spring.application.name=root-server
spring.cloud.config.server.bootstrap=true
spring.cloud.config.server.prefix=/config
spring.cloud.config.server.git.uri= www.githubrepo/config
spring.cloud.config.server.git.username = username
spring.cloud.config.server.git.password = password
Spring cloud GIT Repository file
${user.home}/Desktop/config/root-server.properties
prop1=Hello
prop2=World
Output
localhost:8080/hello/world
Message: default default!
It should be Message: Hello World!

Spring Cloud DataFlow - How to use a custom TCP encoder/decoder in TCP source

I have already asked this question for Spring XD. I am now trying to migrate to Spring CDF.
I found this link and I tried to reuse the code there and change the encoding with mine.
I created the following 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.example</groupId>
<artifactId>tcp-ber-source</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>TCP Ber Source</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.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>
<tcp-app-starters-common.version>1.1.0.RELEASE</tcp-app-starters-common.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud.stream.app</groupId>
<artifactId>tcp-app-starters-common</artifactId>
<version>${tcp-app-starters-common.version}</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>ber-byte-array-serializers</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Configuration:
#EnableBinding(Source.class)
#EnableConfigurationProperties(TcpBerSourceProperties.class)
public class TcpBerSourceConfiguration {
private final Source channels;
private final TcpBerSourceProperties properties;
#Autowired
public TcpSourceConfiguration(final TcpBerSourceProperties properties, final Source channels) {
this.properties = properties;
this.channels = channels;
}
#Bean
public TcpReceivingChannelAdapter adapter(#Qualifier("tcpBerSourceConnectionFactory") final AbstractConnectionFactory connectionFactory) {
final TcpReceivingChannelAdapter adapter = new TcpReceivingChannelAdapter();
adapter.setConnectionFactory(connectionFactory);
adapter.setOutputChannel(this.channels.output());
return adapter;
}
#Bean
public TcpConnectionFactoryFactoryBean tcpBerSourceConnectionFactory(#Qualifier("tcpBerSourceDecoder") final AbstractByteArraySerializer decoder) throws Exception {
final TcpConnectionFactoryFactoryBean factoryBean = new TcpConnectionFactoryFactoryBean();
factoryBean.setType("server");
factoryBean.setPort(this.properties.getPort());
factoryBean.setUsingNio(this.properties.isNio());
factoryBean.setUsingDirectBuffers(this.properties.isUseDirectBuffers());
factoryBean.setLookupHost(this.properties.isReverseLookup());
factoryBean.setDeserializer(decoder);
factoryBean.setSoTimeout(this.properties.getSocketTimeout());
return factoryBean;
}
#Bean
public BerEncoderDecoderFactoryBean tcpBerSourceDecoder() {
final BerEncoderDecoderFactoryBean factoryBean = new BerEncoderDecoderFactoryBean(this.properties.getDecoder());
factoryBean.setMaxMessageSize(this.properties.getBufferSize());
return factoryBean;
}
}
And this FactoryBean:
public class BerEncoderDecoderFactoryBean extends AbstractFactoryBean<AbstractByteArraySerializer> implements ApplicationEventPublisherAware {
private final BerEncoding encoding;
private ApplicationEventPublisher applicationEventPublisher;
private Integer maxMessageSize;
public BerEncoderDecoderFactoryBean(final BerEncoding encoding) {
Assert.notNull(encoding, "'encoding' cannot be null");
this.encoding = encoding;
}
#Override
public void setApplicationEventPublisher(final ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
/**
* The maximum message size allowed when decoding.
* #param maxMessageSize the maximum message size.
*/
public void setMaxMessageSize(final int maxMessageSize) {
this.maxMessageSize = maxMessageSize;
}
#Override
protected AbstractByteArraySerializer createInstance() throws Exception {
final AbstractByteArraySerializer codec;
switch (this.encoding) {
case SPLIT:
codec = new ByteArrayBerSplitSerializer();
break;
case EXTRACT:
codec = new ByteArrayBerExtractSerializer();
break;
default:
throw new IllegalArgumentException("Invalid encoding: " + this.encoding);
}
codec.setApplicationEventPublisher(this.applicationEventPublisher);
if (this.maxMessageSize != null) {
codec.setMaxMessageSize(this.maxMessageSize);
}
return codec;
}
#Override
public Class<?> getObjectType() {
return AbstractByteArraySerializer.class;
}
}
BerEncoding is a simple enum, and TcpBerSourceProperties are pretty straightforward.
Is this the right approach?
If it is, how can I run this? I can't see #SpringBootApplication anywhere on the tcp stream app starters I found on the mentioned link to run as Spring Boot standalone applications?
You have to create your own Spring Boot App class and import the configuration class; see the documentation about creating custom apps.
We generate a standard app (for rabbit and kafka binders) from the starters as explained here.

Spring Executable jar not saving in DB, It works with Eclipse

I have a SpringBoot App, that works as expected when I run it with Eclipse. I create a runnable jar and test it. Everything works expect one thing: it does not save anything on the DB, there is no log or exception to check. I assume there has to be something with the export, because it does not store anything,
not even running it locally.
I have two projects, one depending from the other.
The project 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>BatchCare</groupId>
<artifactId>BatchCare</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.4.2.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.simpleframework</groupId>
<artifactId>simple-xml</artifactId>
<version>2.6.9</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.1.0.7.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
<!-- <version>1.3.2</version> -->
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>CareLibrary</groupId>
<artifactId>CareLibrary</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.156</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>local-repo</id>
<name>Local Project Repo</name>
<url>file://${basedir}/lib/</url>
<layout>default</layout>
</repository>
</repositories>
Classes:
#ComponentScan({"ar.com.tr.latam.care.utils", "ar.com.tr.latam.care.unification.process", "ar.com.tr.latam.care.repository"})
#EnableJpaRepositories
//#Component
#Repository
public class RequestLoggerImpl implements RequestLogger {
/**
* Log.
*/
private static final Logger LOG = LoggerFactory.getLogger(RequestLoggerImpl.class);
#Autowired
private RequestLogDao requestLogDao;
#Override
public void log() {
RequestLog requestLog = new RequestLog();
requestLog.setDate(new Date());
requestLog.setSource("jar");
try {
requestLogDao.save(requestLog);
} catch (Exception ex) {
System.out.println("-------------ERROR-------------------");
ex.printStackTrace();
}
}
}
RequestLogDAO
public interface RequestLogDao extends CrudRepository<RequestLog, Integer> {
}
RquestLog
#Entity
#Table(name = "REQUEST_LOG")
public class RequestLog {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "RequestLogSeq")
#SequenceGenerator(name = "RequestLogSeq", sequenceName = "REQUEST_LOG_SEQ")
private Integer id;
#Column
#NotNull
private Date date;
#NotNull
private String source;
public void setDate(Date date) {
this.date = date;
}
public void setSource(String source) {
this.source = source;
}
}
}
My main Class:
#ComponentScan({"ar.com.tr.latam.care", "ar.com.tr.latam.care.repository", "ar.com.tr.latam.care.filtro"})
#EnableJpaRepositories
#SpringBootApplication
public class InitBatch implements CommandLineRunner {
#Autowired
private Batch batch;
#Override
public void run(String... args) throws Exception {
batch.processFiles();
}
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
SpringApplication.run(InitBatch.class, args).close();
System.out.println(String.format("Total process time (%s) seconds",(System.nanoTime() - startTime) / 1000000000));
}
}
How do I export the project? First, I do a mvn clean install for the Library project . After this I go to my Project and do mvn clean package.
This creates a Runnable jar that works, expect for this problem that can't save anyhing on the DB.
Also, the RequestLogDao is made with JPA.
Any help? Thanks in advance!

Categories