I'm making a web application using Spring Boot and I have the functionality I want by using a in memory database(H2) but I can't connect it to the postgresql server I set up on my computer. I've been at this for some time and tried a bunch of stuff that didn't work so I set everything back to the way it was just to get it working again.
Here's my UploadController.java, it handles the upload from the server and puts it into my in memory database:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import project.service.MediaFile;
import project.service.MediaFileRepository;
#Controller
public class UploadController {
#Autowired
private MediaFileRepository repository;
#RequestMapping(value = "/uploadmedia", method = RequestMethod.GET)
public String uploadForm() {
return "upload";
}
#RequestMapping(value = "/uploadmedia", method = RequestMethod.POST)
public String uploadSubmit(#RequestParam(value="files[]") MultipartFile[] files,
#RequestParam("tags") String tags, #RequestParam("type") String type)
{
String[] tagsArray = tags.split("\\s+");
MultipartFile file;
String name;
String tag;
String path;
for (int i = 0; i < files.length; i++) {
file = files[i];
name = file.getOriginalFilename();
path = "/Users/johannesthorkell/Developer/spring_prufa/images/" + name;
System.out.println(name);
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(path)));
stream.write(bytes);
stream.close();
for (int j = 0; j < tagsArray.length; j++) {
tag = tagsArray[j].toLowerCase();
repository.save(new MediaFile(name, tag, path, type));
}
System.out.println("Success!");
} catch (Exception e) {
System.out.println("Failure... " + e.getMessage());
}
} else {
System.out.println("No file");
}
}
return "upload";
}
}
...and here's my MediaFile class, the #Entity object:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class MediaFile {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String name;
private String tag;
private String resource;
private String type;
protected MediaFile() {}
public MediaFile(String name, String tag, String resource, String type) {
this.name = name;
this.tag = tag;
this.resource = resource;
this.type = type;
}
public String getTag() {
return tag;
}
#Override
public String toString() {
return String.format(
"MediaFile[id=%d, name='%s', tag='%s', resource='%s', type='%s']",
id, name, tag, resource, type);
}
}
...here's 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>HBV501G</groupId>
<artifactId>Spring_Web_MVC</artifactId>
<version>0.1</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.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-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
...and finally, here's the application.properties:
spring.view.prefix=/WEB-INF/jsp/
spring.view.suffix=.jsp
multipart.maxFileSize=-1
With this setup everything works. I tried putting the following in my application.properties:
spring.datasource.url=jdbc:postgresql://localhost/test
spring.datasource.username=myusername
spring.datasource.password=mypassword
spring.datasource.driver-class-name=org.postgresql.jdbc.Driver
...Along with adding the following dependency to the pom.xml:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1200-jdbc41</version>
</dependency>
...And then I tried mixing and matching these things and reading tutorials for a few hours to no avail.
Edit:
I removed one line and added another (at the advice of Stéphane Nicoll) so now my application.properties look like this:
spring.view.prefix=/WEB-INF/jsp/
spring.view.suffix=.jsp
multipart.maxFileSize=-1
debug=true
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=username
spring.datasource.password=password
...And my pom.xml looks like 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>HBV501G</groupId>
<artifactId>Spring_Web_MVC</artifactId>
<version>0.1</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.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-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1200-jdbc41</version>
</dependency>
<!--<dependency>-->
<!--<groupId>com.h2database</groupId>-->
<!--<artifactId>h2</artifactId>-->
<!--</dependency>-->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
With the changes to my application.properties my app now runs! But I get the following error when I submit to my POST form to UploadController.java:
2015-10-06 11:32:14.878 INFO 22287 --- [ main] project.Application : Started Application in 11.897 seconds (JVM running for 12.971)
2015-10-06 11:32:40.263 INFO 22287 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2015-10-06 11:32:40.264 INFO 22287 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2015-10-06 11:32:40.295 INFO 22287 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 31 ms
hopaskipting.pdf
2015-10-06 11:32:49.752 DEBUG 22287 --- [nio-8080-exec-3] org.hibernate.SQL : select nextval ('hibernate_sequence')
2015-10-06 11:32:49.760 WARN 22287 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42P01
2015-10-06 11:32:49.760 ERROR 22287 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: relation "hibernate_sequence" does not exist
Position: 17
Failure... could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
I changed the GenerationType to IDENTITY and get the following error:
2015-10-06 12:56:32.496 DEBUG 22746 --- [nio-8080-exec-7] org.hibernate.SQL : insert into media_file (name, resource, tag, type) values (?, ?, ?, ?)
2015-10-06 12:56:32.505 DEBUG 22746 --- [nio-8080-exec-7] org.hibernate.SQL : insert into media_file (name, resource, tag, type) values (?, ?, ?, ?)
Failure... A different object with the same identifier value was already associated with the session : [project.service.MediaFile#0]; nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [project.service.MediaFile#0]
The key part of the error is:
2015-10-06 11:32:49.760 ERROR 22287 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: relation "hibernate_sequence" does not exist
Hibernate's looking for a table named hibernate_sequence to support #GeneratedValue on MediaFile. You've configured it with AUTO at the moment. The actual behaviour then varies depending on the database you're using.
I think you have a couple of options:
Create a sequence in Postgres (CREATE SEQUENCE), named hibernate_sequence
Change to using a different generation type, e.g. GenerationType.IDENTITY
If I were you, I'd create my own dataSource bean, like:
#Configuration
public class MyConfig{
#Autowired
Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("myapp.dataSource.driver"));
dataSource.setUrl(env.getProperty("myapp.dataSource.url"));
dataSource.setUsername(env.getProperty("myapp.dataSource.username"));
dataSource.setPassword(env.getProperty("myapp.dataSource.password"));
return dataSource;
}
}
application.properties:
logging.level. = INFO
myapp.dataSource.driver =
myapp.dataSource.url =
myapp.dataSource.username =
myapp.dataSource.password =
IF you don't want to try this, you could try changing your driver org.postgresql.jdbc.Driver to org.postgresql.Driver.
It's hard to help without any logs.
Related
How to correctly use DynamoDB with Spring?
I tried to follow many tutorials but always got the same error.
For example my realization of [baeldung tutorial][1]:
application-properties:
#AWS-creds
amazon.dynamodb.endpoint=https://dynamodb.us-east-1.amazonaws.com
amazon.aws.accesskey=
amazon.aws.secretkey=
spring.jpa.hibernate.ddl-auto=create
spring.main.allow-bean-definition-overriding=true
configuration:
#Configuration
#EnableDynamoDBRepositories
(basePackages = "com.hrzc.demo.repository")
public class DynamoDBConfig {
#Value("${amazon.dynamodb.endpoint}")
private String amazonDynamoDBEndpoint;
#Value("${amazon.aws.accesskey}")
private String amazonAWSAccessKey;
#Value("${amazon.aws.secretkey}")
private String amazonAWSSecretKey;
#Bean
public AmazonDynamoDB amazonDynamoDB() {
AmazonDynamoDB amazonDynamoDB
= new AmazonDynamoDBClient(amazonAWSCredentials());
if (!StringUtils.isEmpty(amazonDynamoDBEndpoint)) {
amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint);
}
return amazonDynamoDB;
}
#Bean
public AWSCredentials amazonAWSCredentials() {
return new BasicAWSCredentials(
amazonAWSAccessKey, amazonAWSSecretKey);
}
}
entity:
#DynamoDBTable(tableName = "Url")
public class Url {
private int id;
private String longUrl;
#DynamoDBAttribute
#DynamoDBRangeKey
public String getLongUrl() {
return longUrl;
}
public void setLongUrl(String longUrl) {
this.longUrl = longUrl;
}
#DynamoDBHashKey
#DynamoDBAutoGeneratedKey
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
repository:
#EnableScan
public interface UrlRepository extends CrudRepository<Url, Long> {
}
The pom file does not equal the pom from the tutorial, but I hope this is not the reason, since I can't start the project with dependencyManagement - the error sounds like An attempt was made to call a method that does not exist. - and I found the suggestion to remove the spring-boot-data overriding [here][2].
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 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.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.hrzc</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>linkshrtnr</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</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-web</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>1.11.64</version>
</dependency>
<dependency>
<groupId>com.github.derjust</groupId>
<artifactId>spring-data-dynamodb</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I created the Url table via aws-cli:
> aws dynamodb describe-table --table-name Url
{
"Table": {
"AttributeDefinitions": [
{
"AttributeName": "id",
"AttributeType": "N"
},
{
"AttributeName": "longUrl",
"AttributeType": "S"
}
],
"TableName": "Url",
"KeySchema": [
{
"AttributeName": "id",
"KeyType": "HASH"
},
{
"AttributeName": "longUrl",
"KeyType": "RANGE"
}
],
"TableStatus": "ACTIVE",
"CreationDateTime": "2022-09-25T22:40:39.385000+03:00",
"ProvisionedThroughput": {
"NumberOfDecreasesToday": 0,
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1
},
"TableSizeBytes": 0,
"ItemCount": 0,
"TableArn": "arn:aws:dynamodb:us-east-1:393546347656:table/Url",
"TableId": "33f8baed-4d6c-4787-845d-1df7d0749cea"
}
}
So, how to use dynamoDB correctly?
[1]: https://www.baeldung.com/spring-data-dynamodb
[2]: https://stackoverflow.com/questions/64171751/spring-boot-refuses-to-start-problem-with-abstractrepositoryconfigurationsource
check your application properties file
#for mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#for postgres
#spring.datasource.driver-class-name=org.postgresql.Driver
my properties file is with other config is like
spring.datasource.name=localSource
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
sometimes also check to update maven dependency by updating the maven (sts4/ eclipse)
I'm trying to make a Spring Boot Application with simple login page but when i try to use #Autowired with a interface that i created seems to be a problem. I read 7-8 similar questions but the answers that i find there was useless for me. #Autowired works fine when i use it on interface that expends JpaRepository.
my structure is:
My packages are on the same level as my Application file .
Here is my controller
#Controller
#RequestMapping(value = "/users")
public class LoginContoller {
#Autowired
UsersRepositoryCustom usersRepositoryCustom;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginForm(){
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public #ResponseBody
String verifyLogin(#RequestParam String name, #RequestParam String password) {
System.out.println("Controller: name: " + name + " pass " + password);
Users users=usersRepositoryCustom.loginUser(name, password);
if (users==null) {
System.out.println("login control user null");
return "login";
}
return "users/all";
}
}
Repository:
#Repository
public interface UsersRepositoryCustom {
Users loginUser(String name, String password);
}
I do not think it helps but here is the implementation
public abstract class UserImpl implements UsersRepositoryCustom {
#Autowired
UsersRepository usersRepository;
#Override
public Users loginUser(String name, String password) {
System.out.println("UserImpl: nume: " + name + " pass " + password);
Users user=usersRepository.findByUsername(name);
if (user != null && user.getPassword().equals(password)) {
System.out.println("User Login"+user.getId()+" "+user.getUsername());
return user;
}
return null;
}
}
Application.properties:
server.port=8080
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3308/assignment-one-db
spring.datasource.username=root
spring.datasource.password=789456123
spring.jpa.hibernate.ddl-auto= update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>com.asg1</groupId>
<artifactId>asg1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>asg1</name>
<description>assignment1</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.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>10</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-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>
</plugin>
</plugins>
</build>
</project>
I try to use #EnableJpaRepositories, #EnableAutoConfiguration but it was useless
Here is the error:
Description:
Field usersRepositoryCustom in com.asg1.asg1.controllers.LoginContoller required a bean of type 'com.asg1.asg1.repository.UsersRepositoryCustom' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.asg1.asg1.repository.UsersRepositoryCustom' in your configuration.
Process finished with exit code 1
I have a spring boot application. where i am trying to below operation
AuthenticateIntercepter.java
This class is an Interceptor class in which I'mm trying to print the logs
package com.javamongo.java_mongo.configuration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.javamongo.java_mongo.utils.JWTUtil;
#Component
public class AuthenticateIntercepter implements HandlerInterceptor {
Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass());
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception arg3)
throws Exception {
log.info("Request Completed!");
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model)
throws Exception {
log.info("Method executed");
}
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
log.info("After request executed");
return true;
}
}
WebMvcConfig.java
This class is used to call the interceptor.
package com.javamongo.java_mongo.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Autowired
AuthenticateIntercepter intercepter;
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(intercepter).addPathPatterns("/**");
}
}
When i am calling a request i am getting below. but it is not an error
2018-11-09 12:24:34.805 INFO 3964 --- [nio-8090-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-11-09 12:24:34.805 INFO 3964 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-11-09 12:24:34.865 INFO 3964 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 59 ms
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.javamongo</groupId>
<artifactId>java_mongo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>java_mongo</name>
<description>Spring Boot and mongodb</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.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-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.1</version>
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My Problem:
WebMvcConfig.java class not executing the AuthenticateIntercepter.java, by which I'm not getting the logs in console. So anyone tell me where i made mistake.
It works with the following:
pom.xml snippet:
<?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>hello-world</artifactId>
<version>1.0.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</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-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
HandlerInterceptor:
#Component
public class MyHandlerInterceptor implements HandlerInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(MyHandlerInterceptor.class);
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception arg3) throws Exception {
LOGGER.info("~~~ After-Completion");
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView model) throws Exception {
LOGGER.info("~~~ Post-Handle");
}
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
LOGGER.info("~~~ Pre-Handle");
return true;
}
}
Configuration:
#Configuration
public class WebMvcConfig implements WebMvcConfigurer {
#Autowired
private MyHandlerInterceptor interceptor;
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor).addPathPatterns("/**");
}
}
Sample Controller:
#CrossOrigin
#RestController
#RequestMapping("/api")
class HelloController {
#GetMapping("/hello")
public HelloMessage hello() {
return new HelloMessage("Hello World!")
}
}
Results: When I hit http://localhost:8080/api/hello
2018-11-09 12:48:07.090 INFO 16992 : ~~~ Pre-Handle
2018-11-09 12:48:07.233 INFO 16992 : ~~~ Post-Handle
2018-11-09 12:48:07.233 INFO 16992 : ~~~ After-Completion
I am working on a spring-boot application and I have a configuration class in which i have defined 2 beans of same type but with different names and i am using that bean as parameter to a different bean, i am using qualifier to have different names but still i am not able to autowire the bean
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import java.io.File;
/**
* Created by jauharia on 6/28/2017.
*/
#Configuration
public class DbConfig {
#Bean(name = "sourceJdbcTemplate")
public JdbcTemplate sourceJdbcTemple(#Qualifier("srcDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
#Bean(name = "srcDataSource")
public DataSource sourceDataSource(Config config) {
String driverClassName = config.getString("dbPullConfig.Database.Source.driver");
String url = config.getString("dbPullConfig.Database.Source.url");
String userName = config.getString("dbPullConfig.Database.Source.username");
String password = config.getString("dbPullConfig.Database.Source.password");
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName(driverClassName);
driverManagerDataSource.setUrl(url);
driverManagerDataSource.setUsername(userName);
driverManagerDataSource.setPassword(password);
return driverManagerDataSource;
}
#Bean(name = "destDataSource")
public DataSource destinationDataSource(Config config) {
String driverClassName = config.getString("dbPullConfig.Database.Destination.driver");
String url = config.getString("dbPullConfig.Database.Destination.url");
String userName = config.getString("dbPullConfig.Database.Destination.username");
String password = config.getString("dbPullConfig.Database.Destination.password");
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName(driverClassName);
driverManagerDataSource.setUrl(url);
driverManagerDataSource.setUsername(userName);
driverManagerDataSource.setPassword(password);
return driverManagerDataSource;
}
#Bean(name = "config")
public Config config() {
return ConfigFactory.parseFile(new File("DbPullConfig.conf"));
}
}
And i am getting the below error
parameter 0 of method sourceJdbcTemple in com.ambuj.risk.DbConfig required a single bean, but 2 were found:
- srcDataSource: defined by method 'sourceDataSource' in class path resource [com/ambuj/risk/DbConfig.class]
- destDataSource: defined by method 'destinationDataSource' in class path resource [com/ambuj/risk/DbConfig.class]
pom is as below
<?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>
<artifactId>DbPull</artifactId>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
<version>1.3.1</version>
</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.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.sybase.jconnect</groupId>
<artifactId>jconn4</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I am trying to convert a csv file into xml file using apache camel i am facing problem in mar shalling and unmarshalling ....The code of this program is ......
package com.mycompany.camel.java;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#CsvRecord(separator = ",", skipFirstLine = true)
public class EmployeeDTO implements Serializable{
#XmlAttribute
#DataField(pos = 1)
private int employeeId;
#XmlAttribute
#DataField(pos = 2)
private String firstName;
#XmlAttribute
#DataField(pos = 3)
private String lastName;
#XmlAttribute
#DataField(pos = 4)
private String role;
}
package com.mycompany.camel.java;
import org.apache.camel.CamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.DataFormat;
public class ConvertorRoute implements RoutesBuilder{
#Override
public void addRoutesToCamelContext(CamelContext context) throws Exception {
context.addRoutes(new RouteBuilder() {
public void configure() {
try {
DataFormat bindy = new BindyCsvDataFormat("com.mycompany.camel.java");
from("file://C:/Users/rahul/Desktop/Employee.csv").
unmarshal(bindy).
marshal().
xstream().
to("file://C:/Users/rahul/Desktop/employee.xml");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) {
try{
CamelContext context = new DefaultCamelContext();
ConvertorRoute route = new ConvertorRoute();
route.addRoutesToCamelContext(context);
context.start();
Thread.sleep(5000);
context.stop();
}catch(Exception exe){
exe.printStackTrace();
}
}
}
Error i am facing is:
org.apache.camel.FailedToCreateRouteException: Failed to create route route1 at: >>> Marshal[org.apache.camel.model.dataformat.XStreamDataFormat#1aa9f99] <<< in route: Route[[From[file://C:/Users/JaHnAvI/Desktop?fileName=Employe... because of Data format 'xstream' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:879)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:172)
at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:722)
at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:1789)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:1575)
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:1444)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:60)
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:1412)
at com.mycompany.camel.java.ConvertorRoute.main(ConvertorRoute.java:36)
Caused by: java.lang.IllegalArgumentException: Data format 'xstream' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
at org.apache.camel.model.DataFormatDefinition.getDataFormat(DataFormatDefinition.java:89)
at org.apache.camel.model.DataFormatDefinition.getDataFormat(DataFormatDefinition.java:79)
at org.apache.camel.model.MarshalDefinition.createProcessor(MarshalDefinition.java:150)
at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:461)
at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:179)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:876)
... 8 more
org.apache.camel.FailedToCreateRouteException: Failed to create route route1 at: >>> Marshal[org.apache.camel.model.dataformat.XStreamDataFormat#1aa9f99] <<< in route: Route[[From[file://C:/Users/JaHnAvI/Desktop?fileName=Employe... because of Data format 'xstream' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:879)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:172)
at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:722)
at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:1789)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:1575)
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:1444)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:60)
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:1412)
at com.mycompany.camel.java.ConvertorRoute.main(ConvertorRoute.java:36)
Caused by: java.lang.IllegalArgumentException: Data format 'xstream' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
at org.apache.camel.model.DataFormatDefinition.getDataFormat(DataFormatDefinition.java:89)
at org.apache.camel.model.DataFormatDefinition.getDataFormat(DataFormatDefinition.java:79)
at org.apache.camel.model.MarshalDefinition.createProcessor(MarshalDefinition.java:150)
at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:461)
at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:179)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:876)
... 8 more
Please help me in fixing this error.....
Thanks in advance.....
I tested same example in my local machine with the following dependencies.
file paths are not correct if you are running it in windows.
check the code below.
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>CamelBasic</groupId>
<artifactId>CamelBasic</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<camel-version>2.12.0</camel-version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-csv</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-xstream</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-bindy</artifactId>
<version>${camel-version}</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
path example:
file:D:\CamelTestData\csvDir?fileName=input.csv
It worked for me.
Did you include the dependency for Xstream in your maven file? If you are using maven please add the following to your project file:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-xstream</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency>
The error clearly states you are missing a component