i cant connect springboot and sqlite - java

I can't connect SQLite database with spring boot. I read a lot about it and learned that a dialect should be written for SQLite. I write the dialect, but when I write registerColumnType, it gives me an error: Cannot resolve method 'registerColumnType' in 'SQLiteDialect'. please help me
my 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>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.examDemo</groupId>
<artifactId>exam</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>exam</name>
<description>exam Demo project for Spring Boot</description>
<properties>
<java.version>19</java.version>
</properties>
<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-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.github.gwenn</groupId>-->
<!-- <artifactId>sqlite-dialect</artifactId>-->
<!-- <version>0.1.0</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.16.1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-community-dialects</artifactId>
<version>6.1.6.Final</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
my SQLiteDialect :
package com.examDemo.exam.dialect;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.function.StandardSQLFunction;
import java.sql.*;
public class SQLiteDialect extends Dialect {
public SQLiteDialect() {
registerColumnType(Types.BIT, "integer");
registerColumnType(Types.TINYINT, "tinyint");
registerColumnType(Types.SMALLINT, "smallint");
registerColumnType(Types.INTEGER, "integer");
registerColumnType(Types.BIGINT, "bigint");
registerColumnType(Types.FLOAT, "float");
registerColumnType(Types.REAL, "real");
registerColumnType(Types.DOUBLE, "double");
registerColumnType(Types.NUMERIC, "numeric");
registerColumnType(Types.DECIMAL, "decimal");
registerColumnType(Types.CHAR, "char");
registerColumnType(Types.VARCHAR, "varchar");
registerColumnType(Types.LONGVARCHAR, "longvarchar");
registerColumnType(Types.DATE, "date");
registerColumnType(Types.TIME, "time");
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.BINARY, "blob");
registerColumnType(Types.VARBINARY, "blob");
registerColumnType(Types.LONGVARBINARY, "blob");
// registerColumnType(Types.NULL, "null");
registerColumnType(Types.BLOB, "blob");
registerColumnType(Types.CLOB, "clob");
registerColumnType(Types.BOOLEAN, "integer");
registerKeyword("concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", ""));
registerKeyword("mod", new SQLFunctionTemplate(StringType.INSTANCE, "?1 % ?2"));
registerKeyword("substr", new StandardSQLFunction("substr", StringType.INSTANCE));
registerKeyword("substring", new StandardSQLFunction("substr", StringType.INSTANCE));
}
public boolean supportsIdentityColumns() {
return true;
}
public boolean hasDataTypeInIdentityColumn() {
return false; // As specify in NHibernate dialect
}
public String getIdentityColumnString() {
// return "integer primary key autoincrement";
return "integer";
}
public String getIdentitySelectString() {
return "select last_insert_rowid()";
}
public boolean supportsLimit() {
return true;
}
protected String getLimitString(String query, boolean hasOffset) {
return new StringBuffer(query.length() + 20).append(query).append(hasOffset ? " limit ? offset ?" : " limit ?")
.toString();
}
public boolean supportsTemporaryTables() {
return true;
}
public String getCreateTemporaryTableString() {
return "create temporary table if not exists";
}
public boolean dropTemporaryTableAfterUse() {
return false;
}
public boolean supportsCurrentTimestampSelection() {
return true;
}
public boolean isCurrentTimestampSelectStringCallable() {
return false;
}
public String getCurrentTimestampSelectString() {
return "select current_timestamp";
}
public boolean supportsUnionAll() {
return true;
}
public boolean hasAlterTable() {
return false; // As specify in NHibernate dialect
}
public boolean dropConstraints() {
return false;
}
public String getAddColumnString() {
return "add column";
}
public String getForUpdateString() {
return "";
}
public boolean supportsOuterJoinForUpdate() {
return false;
}
public String getDropForeignKeyString() {
throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
}
public String getAddForeignKeyConstraintString(String constraintName, String[] foreignKey, String referencedTable,
String[] primaryKey, boolean referencesPrimaryKey) {
throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
}
public String getAddPrimaryKeyConstraintString(String constraintName) {
throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
}
public boolean supportsIfExistsBeforeTableName() {
return true;
}
public boolean supportsCascadeDelete() {
return false;
}
}
I checked many things. and I have watched many videos but no one has encountered this problem unfortunately

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!

Defining a bean of type OAuth2AuthorizedClientService in your configuration consider. Parameter 0 of constructor in LoginController required a Bean

I encounter a
No qualifying bean of type security.oauth2.client.OAuth2AuthorizedClientService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Don't understand what it expected. It's a dependancy.
Here's the LoginController :
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.security.RolesAllowed;
import java.security.Principal;
import java.util.Map;
#RestController
public class LoginController {
private OAuth2AuthorizedClientService authorizedClientService;
public LoginController(OAuth2AuthorizedClientService authorizedClientService) {
this.authorizedClientService = authorizedClientService;
}
#RequestMapping("/**")
#RolesAllowed("USER")
public String getUser(){
return "dashboard";
}
#RequestMapping("/admin")
#RolesAllowed("ADMIN")
public String getAdmin(){
return "Welcome, Admin";
}
#RequestMapping("/*")
public String getUserInfos(Principal activeUser){
StringBuffer userInfos = new StringBuffer();
if (activeUser instanceof UsernamePasswordAuthenticationToken){
userInfos.append(getUsernamePasswordPasswordLoginInfo(activeUser));
} else if (activeUser instanceof OAuth2AuthenticationToken){
userInfos.append(getOAuth2LoginInfo(activeUser));
}
return userInfos.toString();
}
private StringBuffer getOAuth2LoginInfo(Principal activeUser) {
StringBuffer protectedInfo = new StringBuffer();
OAuth2AuthenticationToken authToken = (OAuth2AuthenticationToken) activeUser;
OAuth2User principal = ((OAuth2AuthenticationToken)activeUser).getPrincipal();
OAuth2AuthorizedClient authClient = this.authorizedClientService
.loadAuthorizedClient(authToken.getAuthorizedClientRegistrationId(), authToken.getName());
Map<String, Object> userDetails = ((DefaultOAuth2User) authToken.getPrincipal()).getAttributes();
String userToken = authClient.getAccessToken().getTokenValue();
protectedInfo.append("Welcome, " + userDetails.get("name") + "<br><br>");
protectedInfo.append("email: " + userDetails.get("email") + "<br><br>");
protectedInfo.append("Access Token: " + userToken + "<br><br>");
OidcIdToken idToken = getIdToken(principal);
if(idToken != null){
protectedInfo.append("Token value: " + idToken.getTokenValue() + "<br><br>");
protectedInfo.append("Token mapped values <br><br>");
Map<String, Object> claims = idToken.getClaims();
for (String key : claims.keySet()) {
protectedInfo.append(" " + key + ": " + claims.get(key) + "<br>");
}
}
return protectedInfo;
}
private StringBuffer getUsernamePasswordPasswordLoginInfo(Principal activeUser) {
StringBuffer usernameInfo = new StringBuffer();
UsernamePasswordAuthenticationToken token = ((UsernamePasswordAuthenticationToken) activeUser);
if (token.isAuthenticated()){
User u = (User) token.getPrincipal();
usernameInfo.append("Welcome, " + u.getUsername());
} else {
usernameInfo.append("NA");
}
return usernameInfo;
}
private OidcIdToken getIdToken(OAuth2User principal){
if(principal instanceof DefaultOidcUser) {
DefaultOidcUser oidcUser = (DefaultOidcUser)principal;
return oidcUser.getIdToken();
}
return null;
}
}
Here's the pom.xml... maybe it's a dependancy import problem:
<properties>
<java.version>17</java.version>
<pebble.version>3.1.5</pebble.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>2.6.2</version>
<scope>runtime</scope>
<optional>true</optional>
</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>5.1.3</version>
</dependency>
<dependency>
<groupId>io.pebbletemplates</groupId>
<artifactId>pebble-spring-boot-2-starter</artifactId>
<version>3.0.10</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
Ok.
The problem was the application.properties
The openId was badly configured... it couldn't instanciate the bean... that's what written in the terminal... can't say was crystal clear but was written

Why my Log File is Not Been Created In The Local Explorer?

I only want to log my Exceptions which I get at the time of Run Time. I have An Application_Logger.class, Application.properties,log4j2. properties file. and of course the main class. Can anyone help me creating a log file?
App_Logger.Class
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ApplicationLogger {
transient static Logger cat = (Logger) LogManager.getLogger(ApplicationLogger.class);
public static final boolean TRACE_EMPTY_EXCEPTION_CALL = true;
/**
* Logs the message
*/
public static void log(String message){
cat.debug(message);
}
public static void log(String message, UserDTO loginUser) {
cat.debug(getLoginUserDetails(loginUser) + message);
}
/**
* Logs the message and the exception
*/
public static void log(String message, Exception e){
log(message, e, null);
}
public static void log(String message, Exception e, UserDTO loginUser) {
if(e != null)
cat.error(getLoginUserDetails(loginUser) + message, e);
else {
if(TRACE_EMPTY_EXCEPTION_CALL) {
try {
throw new Exception("Empty exception encountered");
}catch(Exception ex) {
log(message, ex, loginUser);
}
}
else
cat.debug(getLoginUserDetails(loginUser) + message);
}
}
/** logs the message as an error
*
* #param message
*/
public static void logError(String message){
logError(message, null);
}
public static void logError(String message, UserDTO loginUser){
cat.error(getLoginUserDetails(loginUser) + message);
}
public static void log(String empNo, String operation, String operand){
cat.debug(empNo + ":" + operation + ":" + operand);
}
public static String getLoginUserDetails(UserDTO loginUser) {
if(loginUser == null)
return "";
return "[" + loginUser.getEmpId() + ", " + loginUser.getTenantId() + "] ";
}
}
Application.properties File
log4j2.debug=true
InitApplication.class
#SpringBootApplication
#CrossOrigin("http://localhost:3000")
public class InitApplication implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(InitApplication.class, args);
}
}
It was just an error in pom.xml file.
Earlier it was like,
<?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.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xyz</groupId>
<artifactId>ABC</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ABC</name>
<description>LOG4j2</description>
<properties>
<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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180813</version>
</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>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Then I added these lines, basically, I excluded Spring boot default starter logger and added log4j2 logger by adding its dependencies.
Like This.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

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

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/

Spring Data Neo4j - findById method throws an invalid query exception after upgrading to Spring Boot 2

I have been working on a micro-service created using Spring Boot with Neo4j as the database. The two relevant entities within it Product and AccessoryRelation are thus:
#NodeEntity
#QueryEntity
public class Product extends AbstractNeo4jEntity {
#Index(primary = true, unique = true)
private String productId;
#Transient
private String market;
#JsonIgnore
#Relationship(type = "HAS_ACCESSORY")
private Set<AccessoryRelation> relations = new HashSet<>();
public Product() {
}
public Product(final String productId) {
this.productId = productId;
}
public String getProductId() {
return productId;
}
public String getMarket() {
return market;
}
public void setMarket(final String market) {
this.market = market;
}
public Set<AccessoryRelation> getRelations() {
return new HashSet<>(relations);
}
public void addAccessory(final Product accessory) {
Assert.notNull(accessory, "Accessory product can not be null");
Assert.hasText(accessory.getProductId(),
"Accessory product should have a valid identifier");
Assert.hasText(accessory.getMarket(),
"Accessory product should be available atleast in one market");
Assert.isTrue(!this.equals(accessory),
"A product can't be an accessory of itself.");
final AccessoryRelation relation = this.relations.stream() //
.filter(rel -> rel.getAccessory().equals(accessory)) //
.findAny() //
.orElseGet(() -> {
final AccessoryRelation newRelation = new AccessoryRelation(this,
accessory, Sets.newHashSet());
this.relations.add(newRelation);
return newRelation;
});
relation.addMarket(accessory.getMarket());
}
public void removeAccessory(final Product accessory) {
Assert.notNull(accessory, "Accessory product can not be null");
Assert.hasText(accessory.getProductId(),
"Accessory product should have a valid identifier");
Assert.hasText(accessory.getMarket(),
"Accessory product should be available atleast in one market");
final Optional<AccessoryRelation> relation = this.relations.stream() //
.filter(rel -> rel.getAccessory().equals(accessory)) //
.findAny();
if (relation.isPresent()) {
relation.get().removeMarket(accessory.getMarket());
if (relation.get().getMarkets().isEmpty()) {
this.relations.remove(relation.get());
}
}
}
public void removeAccessories() {
this.relations.clear();
}
#Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof Product)) {
return false;
}
final Product product = (Product) obj;
return new EqualsBuilder() //
.append(getProductId(), product.getProductId()) //
.isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder() //
.append(getProductId()) //
.toHashCode();
}
#Override
public String toString() {
return new ToStringBuilder(this) //
.append("ProductId", getProductId()) //
.toString();
}
}
#RelationshipEntity(type = "HAS_ACCESSORY")
public class AccessoryRelation extends AbstractNeo4jEntity {
#StartNode
private Product product;
#EndNode
private Product accessory;
private Set<String> markets = new HashSet<>();
public AccessoryRelation() {
}
public AccessoryRelation(final Product product, final Product accessory,
final Set<String> markets) {
this.product = product;
this.accessory = accessory;
this.markets = markets;
}
public Product getProduct() {
return product;
}
public void setProduct(final Product product) {
this.product = product;
}
public Product getAccessory() {
return accessory;
}
public void setAccessory(final Product accessory) {
this.accessory = accessory;
}
public Set<String> getMarkets() {
return new HashSet<>(markets);
}
public void addMarket(final String market) {
this.markets.add(market);
}
public void removeMarket(final String market) {
this.markets.remove(market);
}
#Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof AccessoryRelation)) {
return false;
}
final AccessoryRelation relation = (AccessoryRelation) obj;
return new EqualsBuilder() //
.append(getProduct(), relation.getProduct()) //
.append(getAccessory(), relation.getAccessory()) //
.isEquals();
}
#Override
public final int hashCode() {
return new HashCodeBuilder() //
.append(getProduct()) //
.append(getAccessory()) //
.toHashCode();
}
#Override
public String toString() {
return new ToStringBuilder(this) //
.append("Product", getProduct()) //
.append("Accessory", getAccessory()) //
.append("Markets", getMarkets()) //
.toString();
}
}
For JUnit test cases I am using nosqlunit-neo4j version 1.0.0-rc.5 and an embedded databsase.
Now I have the findById(productId) method which would return the Product along with the associated AccessoryRelation objects. However, after upgrading to Spring Boot 2, this method does not work. It throws an exception thus:
org.springframework.data.neo4j.exception.UncategorizedNeo4jException:
Error executing Cypher; Code: Neo.ClientError.Statement.InvalidSyntax;
Description: Invalid input '|': expected whitespace, comment, a
relationship pattern, '.', node labels, '[', "=~", IN, STARTS, ENDS,
CONTAINS, IS, '^', '*', '/', '%', '+', '-', '=', "<>", "!=", '<', '>',
"<=", ">=", AND, XOR, OR, ',' or ']' (line 1, column 113 (offset:
112))
"MATCH (n:`Product`) WHERE n.`productId` = { id } WITH n RETURN n,[ [
(n)-[r_h1:`HAS_ACCESSORY`]->(p1:`Product`) | [ r_h1, p1 ] ] ]"
^; nested exception is org.neo4j.ogm.exception.CypherException: Error
executing Cypher; Code: Neo.ClientError.Statement.InvalidSyntax;
Description: Invalid input '|': expected whitespace, comment, a
relationship pattern, '.', node labels, '[', "=~", IN, STARTS, ENDS,
CONTAINS, IS, '^', '*', '/', '%', '+', '-', '=', "<>", "!=", '<', '>',
"<=", ">=", AND, XOR, OR, ',' or ']' (line 1, column 113 (offset:
112))
"MATCH (n:`Product`) WHERE n.`productId` = { id } WITH n RETURN n,[ [
(n)-[r_h1:`HAS_ACCESSORY`]->(p1:`Product`) | [ r_h1, p1 ] ] ]"
By the looks of it, it is treating the '|' character as an invalid character within the query. However, when I run the same query in a neo4 3.4.9 instance on the browser, it works fine. No syntax errors on that one. The application has a default neo4j version of 2.3.3 which coming from the nosqlunit dependency. I have tried including neo4j 3.4.9 dependencies in my pom, but that creates a whole set of new problems.
The following is my 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
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.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>
<project.build.itDirectory>src/it/java</project.build.itDirectory>
<neo4j-cypher-dsl.version>2.3-RELEASE</neo4j-cypher-dsl.version>
<querydsl.version>4.1.4</querydsl.version>
<querydsl-apt.version>1.1.3</querydsl-apt.version>
<cglib.version>2.2.2</cglib.version>
<spring-cloud.version>Finchley.RC2</spring-cloud.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>cglib</groupId>
<artifactId>cglib</artifactId>
<version>${cglib.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-lucene3</artifactId>
<version>${querydsl.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<!-- This jar is used by CypherQueryDSL at runtime. If its not present
in classpath then java.lang.ClassNotFoundException: org.apache.lucene.search.Query
error is thrown -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>3.6.2</version>
</dependency>
<dependency>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-core</artifactId>
<version>2.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-http</artifactId>
<version>2.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-java-dsl</artifactId>
<version>2.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-cypher-dsl</artifactId>
<version>${neo4j-cypher-dsl.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</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>
</dependency>
<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-neo4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-hal-browser</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>com.lordofthejars</groupId>
<artifactId>nosqlunit-neo4j</artifactId>
<version>1.0.0-rc.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.openpojo</groupId>
<artifactId>openpojo</artifactId>
<version>0.8.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>nl.jqno.equalsverifier</groupId>
<artifactId>equalsverifier</artifactId>
<version>2.1.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm-embedded-driver</artifactId>
<version>3.1.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm-all</artifactId>
<version>6.0_ALPHA</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>product-accessory-service</finalName>
<plugins>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>${querydsl-apt.version}</version>
<dependencies>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
<version>${querydsl.version}</version>
</dependency>
</dependencies>
<configuration>
<processor>com.querydsl.apt.QuerydslAnnotationProcessor</processor>
</configuration>
<executions>
<execution>
<id>add-sources</id>
<phase>generate-sources</phase>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/querydsl</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.4.13</version>
<configuration>
Has anyone encountered a similar issue before? Could anyone please help me out in resolving this? Thanks in advance.

Categories