Send message using JMS and ApacheMQ and spring boot - java

Hi I want to send message to Active MQ. I am using Spring Boot with apache MQ. I don't want to use any xml class so I have defined beans in Configuration.java class and those beans I want to use in MessageSenderClass. How can i use it?
I have three classes:
1..SenderApplication
package com.ge.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jms.core.JmsMessagingTemplate;
#SpringBootApplication
public class SenderApplication {
/*#Autowired
JmsMessageSender jmsmessagingSender;*/
public static void main(String[] args) {
SpringApplication.run(SenderApplication.class, args);
}
}
2.. SendingMessageController
package com.ge.Controller;
import javax.jms.JMSException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#Controller
#EnableAutoConfiguration
public class SendingMessageController {
#Autowired
MessageSenderClass msgSenderClass;
#RequestMapping(value="/sending",method= {RequestMethod.POST})
#ResponseBody
public String greeting()
{
String msg="Welcome to GE";
System.out.println("MESSAGE-1");
try {
msgSenderClass.onDataLoadMessage(msg);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ("Welcome to GE");
}
}
3..MessageSenderClass
package com.ge.Controller;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQMessageProducer;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.spring.ActiveMQConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.support.destination.DestinationResolver;
import org.springframework.stereotype.Component;
import com.ge.config.AppConfig;
#Component
public class MessageSenderClass
{
private ActiveMQMessageProducer messageProducer=null;
private ActiveMQConnectionFactory activeMQConnectionFactory=null;
#Autowired
ActiveMQConnection connection;
private ActiveMQSession session=null;
private Destination destination = null;
/*#Autowired
DestinationResolver destinationResolver;*/
#JmsListener(destination = "dataLoadChannel")
public void onDataLoadMessage(String message) throws JMSException
{
System.out.println("M in on load data method");
System.out.println(message);
connection = (ActiveMQConnection) activeMQConnectionFactory.createConnection();
connection.start();
session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination =session.createQueue("SAMPLEQUEUE");
messageProducer = (ActiveMQMessageProducer) session.createProducer(destination);
TextMessage message1 = session.createTextMessage();
message1.setText("Hello ...This is a sample message..sending from FirstClient");
messageProducer.send(message1);
System.out.println("Sent: " + message1.getText());
}
}
4.ApplicationConfig
package com.ge.config;
import javax.annotation.Resource;
import javax.jms.ConnectionFactory;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.RedeliveryPolicy;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.support.destination.BeanFactoryDestinationResolver;
import org.springframework.jms.support.destination.DestinationResolver;
#Configuration
#EnableJms
public class AppConfig {
#Resource
private ApplicationContext applicationContext;
#Resource
private Settings settings;
#Bean
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory());
factory.setDestinationResolver(destinationResolver());
factory.setConcurrency("9");
factory.setTransactionManager(null);
return factory;
}
#Bean
public ConnectionFactory connectionFactory() {
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(settings.getActiveMQBrokerUrl());
RedeliveryPolicy policy = new RedeliveryPolicy();
policy.setMaximumRedeliveries(0);
activeMQConnectionFactory.setRedeliveryPolicy(policy);
return activeMQConnectionFactory;
}
#Bean
public DestinationResolver destinationResolver() {
return new BeanFactoryDestinationResolver(applicationContext);
}
#Bean
public ActiveMQQueue dataLoadChannel()
{
return new ActiveMQQueue(settings.getDataLoadDestination());
}
}
Maven 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>MainJMSTemplate</groupId>
<artifactId>MainJMSTemplate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<!-- Spring version -->
<spring-framework.version>4.1.0.RELEASE</spring-framework.version>
<!-- ActiveMQ version -->
<activemq.version>5.10.0</activemq.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.3.2.RELEASE</version>
</dependency>
<!-- Spring aritifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<!-- ActiveMQ Artifacts -->
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-spring</artifactId>
<version>${activemq.version}</version>
</dependency>
</dependencies>
<!-- Using JDK 1.7 for compiling -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<!-- <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories> -->
</project>
In AppConfig file M defining beans and those beans i want to use in MessageSenderClass How can i use it?

Related

Rest api call fails in POST API call

Hi I have newly created a microservice post API call with STS4 which was build and deployed successfully. the localhost:8080/demo/ link is opening up. but the rest maping underneath it failing with 404 not found. I haved added requestmapping and post mapping and tried still not working. Can anyone fix the code?
PFB the code:-
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.5.3</version>
<!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<maven.test.skip> true</maven.test.skip>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<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-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</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>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<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>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
here is the config for swagger :-
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#Configuration
//Enable Swagger
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
//creating constructor of Docket class that accepts parameter DocumentationType
return new Docket(DocumentationType.SWAGGER_2);
}
}
here is the rest controller:
package com.example.demo.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.MyResponse;
import com.example.demo.service.dao.DemoServiceDAO;
import com.example.demo.service.impl.DemoServiceImpl;
#RestController
#Validated
#RequestMapping(value ="/newcall", method = RequestMethod.POST)
public class DemoController {
Logger logger =LoggerFactory.getLogger(DemoController.class);
#PostMapping(value ="/newResp", headers ="Accept=Application/JSON", produces="Application/JSON")
public MyResponse newResp(#RequestBody String myInput) {
MyResponse myResponse = null;
try {
DemoServiceDAO demoServiceDAO = new DemoServiceImpl();
logger.debug("Started getValue() method...");
myResponse=demoServiceDAO.getValue(myInput);
logger.debug("Completed getValue() method...");
}
catch(Exception e){
logger.debug("Exception occurs",e);
e.printStackTrace();
System.out.println("Exception occurs");
}
return myResponse;
}
}
here is the application:-
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#SpringBootApplication
#ComponentScan(basePackages = "com.example.*")
#EnableSwagger2
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
Logger logger =LoggerFactory.getLogger(DemoApplication.class);
SpringApplication.run(DemoApplication.class, args);
}
}
here is the app.properties:-
logging.file.name=opt/var/logs/demoService.log
logging.file.path=opt/var/logs
logging.level.web=DEBUG
spring.jmx.default-domain=demo
server.servlet.context-path=/demo
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
springfox.documentation.swagger-ui.base-url=true
management.endpoint.info.enabled: true
springfox.documentation.swagger-ui.enabled=true
springfox.documentation.open-api.enabled=true
spring.security.user.name = user
spring.security.user.password = password
Output from http://localhost:8080/demo/
"_links" : {
"profile" : {
"href" : "http://localhost:8080/demo/profile"
}
}
full code is in github with logs:-
https://github.com/Sourav654/tempProject/tree/master/demo
Without any logs we can only guess, but looking at your Controller I see some weird things. Can you please try the following?
#RestController
#Validated
#RequestMapping("newcall")
public class DemoController {
Logger logger =LoggerFactory.getLogger(DemoController.class);
#PostMapping("/newResp", consumes = "application/json", produces = application/json)
public MyResponse newResp(#RequestBody String myInput) {
MyResponse myResponse = null;
try {
DemoServiceDAO demoServiceDAO = new DemoServiceImpl();
logger.debug("Started getValue() method...");
myResponse=demoServiceDAO.getValue(myInput);
logger.debug("Completed getValue() method...");
}
catch(Exception e){
logger.debug("Exception occurs",e);
e.printStackTrace();
System.out.println("Exception occurs");
}
return myResponse;
}
}

Could not autowire. No beans of 'JobRepositoryTestUtils' type found. With SpringBatchTest Annotation added

I am working on a Spring Batch unit testing using the #SpringBatchTest annotation which is supposed to automatically add the beans for JobLauncherTestUtils and JobRepositoryTestUtils.
Here's the Job configuration class:
#Configuration
#EnableBatchProcessing
public class JobConfiguration {
#Bean
public Job getJob(JobBuilderFactory jobBuilderFactory,
#Qualifier("flow_master") Flow flowMaster) {
return jobBuilderFactory.get("job")
.incrementer(new RunIdIncrementer())
.start(flowMaster)
.build().build();
}
}
Here's the Test Class:
#ExtendWith(SpringExtension.class)
#SpringBatchTest
#ContextConfiguration(classes = JobConfiguration.class)
public class SpringBatchTest {
#Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
#Before
public void clearJobExecutions() {
this.jobRepositoryTestUtils.removeJobExecutions();
}
#Test
public void testMyJob() throws Exception {
JobParameters jobParameters = this.jobLauncherTestUtils.getUniqueJobParameters();
JobExecution jobExecution = this.jobLauncherTestUtils.launchJob(jobParameters);
Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
}
Problem:
I am getting the error messages:
Could not autowire. No beans of 'JobLauncherTestUtils' type found.
I have cloned some repo examples which are supposed to work but I am getting the same error for all of them.
Am I missing something?
You did not share your imports but you are probably mixing imports between junit4 and junit5. I'm not able to reproduce your error. Here is a complete example:
The job configuration class:
package com.example.demo;
import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
#Configuration
#EnableBatchProcessing
public class MyJobConfig {
#Bean
public Job job(JobBuilderFactory jobs, StepBuilderFactory steps) {
return jobs.get("job")
.start(steps.get("step")
.tasklet((contribution, chunkContext) -> {
System.out.println("Hello world!");
return RepeatStatus.FINISHED;
}).build())
.build();
}
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("/org/springframework/batch/core/schema-h2.sql")
.build();
}
public static void main(String[] args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(MyJobConfig.class);
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
Job job = context.getBean(Job.class);
jobLauncher.run(job, new JobParameters());
}
}
The test class:
package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.test.JobLauncherTestUtils;
import org.springframework.batch.test.JobRepositoryTestUtils;
import org.springframework.batch.test.context.SpringBatchTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
#ExtendWith(SpringExtension.class)
#SpringBatchTest
#ContextConfiguration(classes = MyJobConfig.class)
class MyJobConfigTest {
#Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
#Autowired
private JobRepositoryTestUtils jobRepositoryTestUtils;
#BeforeEach
public void clearJobExecutions() {
this.jobRepositoryTestUtils.removeJobExecutions();
}
#Test
public void testMyJob() throws Exception {
// given
JobParameters jobParameters = this.jobLauncherTestUtils.getUniqueJobParameters();
// when
JobExecution jobExecution = this.jobLauncherTestUtils.launchJob(jobParameters);
// then
Assertions.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
}
and the pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>so67767525</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>so67767525</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<!-- While this has "boot" in the name, it does not bring any Spring Boot feature. -->
<!-- It is used to manage Spring projects dependencies that are known to work correctly together -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.4.6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
The test runs successfully without the error you mentioned.

#Transactional annotation configuration

Hi I'm learning Spring Framework after my Java Core Study. I'm making very simple CRUD MVC application. There is a problem #Transactional annotation doesn't work. Could someone more expierienced in that matter help me? Stack:(Java,Spring,Hibernate,Maven).
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.adrianzaplata</groupId>
<artifactId>hibernate-tutorial</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>hibernate-tutorial Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.27.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.4.27.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>hibernate-tutorial</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
my configuration:
package com.adrianzaplata.project.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import java.beans.PropertyVetoException;
import java.util.Properties;
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan(basePackages = {"com.adrianzaplata.project"})
public class AppConfig {
#Bean
public InternalResourceViewResolver viewResolver()
{
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Bean(destroyMethod = "close")
public ComboPooledDataSource comboPooledDataSource() throws PropertyVetoException {
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver");
cpds.setJdbcUrl("jdbc:mysql://localhost:3306/hibernate?useSSL=false");
cpds.setUser("adrian");
cpds.setPassword("chomik12");
cpds.setMinPoolSize(5);
cpds.setMaxPoolSize(20);
cpds.setMaxIdleTime(30000);
return cpds;
}
//
#Bean
public LocalSessionFactoryBean beanFactory() throws PropertyVetoException {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(comboPooledDataSource());
factory.setPackagesToScan("com.adrianzaplata.project.entities");
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect","org.hibernate.dialect.MySQLDialect");
hibernateProperties.setProperty("hibernate.show_sql","true");
factory.setHibernateProperties(hibernateProperties);
return factory;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager() throws PropertyVetoException {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
transactionManager.setSessionFactory(beanFactory().getObject());
return transactionManager;
}
}
my init class instead of web.xml
package com.adrianzaplata.project.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Configuration
public class AppInit extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
Class[] confClasses = {AppConfig.class};
return confClasses;
}
#Override
protected String[] getServletMappings() {
String[] mappings = {"/"};
return mappings;
}
}
Controller
package com.adrianzaplata.project.controllers;
import com.adrianzaplata.project.entities.Customer;
import com.adrianzaplata.project.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
#Controller
#RequestMapping("/customer")
public class CustomerController {
#Autowired
private CustomerService customerService;
#GetMapping("/all")
public String listCustomers(Model model)
{
List<Customer> theCustomers = customerService.getAllCustomers();
model.addAttribute("customers",theCustomers);
return "customer-all";
}
#GetMapping("/showAddForm")
public String addCustomer(#ModelAttribute("CustomerDTO") Customer customerDTO)
{
return "add-customer";
}
#PostMapping("/process-add-form")
public void processCustomer(HttpServletRequest request, HttpServletResponse response, #ModelAttribute("CustomerDTO") Customer customerDTO) throws IOException {
customerService.addCustomer(customerDTO);
response.sendRedirect(request.getContextPath()+"/customer/all");
}
}
At the moment I'm able to read customers from database but method addCustomer doesn't work unless managed transcaction manually inside saveCustomer() method. I suspect that reading customers also does not work by #Transactional annotation.
Service
package com.adrianzaplata.project.service;
import com.adrianzaplata.project.dao.CustomerDao;
import com.adrianzaplata.project.entities.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerDao customerDao;
#Override
#Transactional
public List<Customer> getAllCustomers()
{
return customerDao.getCustomers();
}
#Transactional
#Override
public void addCustomer(Customer customer) {
customerDao.addCustomer(customer);
}
}
DAO
package com.adrianzaplata.project.dao;
import com.adrianzaplata.project.entities.Customer;
import org.hibernate.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public class CustomerDaoImpl implements CustomerDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Customer> getCustomers() {
Session session = sessionFactory.openSession();
try {
SQLQuery query = session.createSQLQuery("SELECT * from customer");
query.addEntity(Customer.class);
List<Customer> customers = query.list();
return customers;
} finally {
session.close();
}
}
#Override
public void addCustomer(Customer customer) {
Session session = sessionFactory.openSession();
session.save(customer);
}
}
I'm just trying to use #Transactional to help me reduce boilerplate code i have to use for hibernate but when i use #Transactional my logic from dao class does not execute. (No queries to database).

Basic Spring based WSSecurity client gets a null response

I've been following this tutorial to learn how to develop a basic spring client and server application using wssecurity (certificates).
The demo works beautifully, but i need to deploy my application on a wildfly server, so i had to change the example a bit in order to avoid the embedded tomcat, the changes are as follows:
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.memorynotfound.spring.ws</groupId>
<artifactId>ws-security-certificate-wss4j-security-interceptor</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>SPRING-WS - ${project.artifactId}</name>
<url>http://memorynotfound.com</url>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.security</groupId>
<artifactId>wss4j</artifactId>
<version>1.6.19</version>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.5.0</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<sources>
<source>src/main/resources/xsd</source>
</sources>
<generatePackage>com.memorynotfound.beer</generatePackage>
</configuration>
</plugin>
</plugins>
</build>
RunServer.java
package com.memorynotfound.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class RunServer extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(RunServer.class);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<RunServer> applicationClass = RunServer.class;
}
BeerEndpoint.java
package it.corvallis.soap.endpoint;
import com.memorynotfound.beer.Beer;
import com.memorynotfound.beer.GetBeerRequest;
import com.memorynotfound.beer.GetBeerResponse;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import org.springframework.ws.soap.server.endpoint.annotation.SoapAction;
#Endpoint
public class BeerEndpoint {
public static final String NAMESPACE_URI = "http://memorynotfound.com/beer";
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "getBeerRequest")
#SoapAction("http://localhost:8080/ws/beers")
#ResponsePayload
public GetBeerResponse getBeer(#RequestPayload GetBeerRequest request) {
GetBeerResponse beerResponse = new GetBeerResponse();
Beer beer = new Beer();
beer.setId(request.getId());
beer.setName("Beer name");
beerResponse.setBeer(beer);
return beerResponse;
}
}
I deployed the server application on my wildfly and i tried to call it using the same client application used in the tutorial. The service seems to answer correctly, the beerResponse object is correctly istantiated, but, as soon as the object is being sent back to the the client, i see it's NULL.
What am i missing?
Thanks in advance
Oh well, next time i'll read better. At the same link of my first post, a guy asked the same question in the comments, here is the solution: add a callBackHandler to the client configuration, and modify the securityInterceptor to use this handler.
SoapClientConfig.java
package com.memorynotfound.client;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Component;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.soap.security.wss4j2.Wss4jSecurityInterceptor;
import org.springframework.ws.soap.security.wss4j2.callback.KeyStoreCallbackHandler;
import org.springframework.ws.soap.security.wss4j2.support.CryptoFactoryBean;
import java.io.IOException;
#Configuration
public class SoapClientConfig {
#Bean
public Wss4jSecurityInterceptor securityInterceptor() throws Exception {
Wss4jSecurityInterceptor securityInterceptor = new Wss4jSecurityInterceptor();
// set security actions
securityInterceptor.setSecurementActions("Timestamp Signature Encrypt");
// sign the request
securityInterceptor.setSecurementUsername("client");
securityInterceptor.setSecurementPassword("changeit");
securityInterceptor.setSecurementSignatureCrypto(getCryptoFactoryBean().getObject());
// encrypt the request
securityInterceptor.setSecurementEncryptionUser("server-public");
securityInterceptor.setSecurementEncryptionCrypto(getCryptoFactoryBean().getObject());
securityInterceptor.setSecurementEncryptionParts("{Content}{http://memorynotfound.com/beer}getBeerRequest");
// sign the response
securityInterceptor.setValidationActions("Signature Encrypt");
securityInterceptor.setValidationSignatureCrypto(getCryptoFactoryBean().getObject());
securityInterceptor.setValidationDecryptionCrypto(getCryptoFactoryBean().getObject());
securityInterceptor.setValidationCallbackHandler(securityCallbackHandler());
return securityInterceptor;
}
#Bean
public CryptoFactoryBean getCryptoFactoryBean() throws IOException {
CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean();
cryptoFactoryBean.setKeyStorePassword("changeit");
cryptoFactoryBean.setKeyStoreLocation(new ClassPathResource("client.jks"));
return cryptoFactoryBean;
}
#Bean
public Jaxb2Marshaller getMarshaller(){
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.memorynotfound.beer");
return marshaller;
}
#Bean
public BeerClient getBeerClient() throws Exception {
BeerClient beerClient = new BeerClient();
beerClient.setMarshaller(getMarshaller());
beerClient.setUnmarshaller(getMarshaller());
beerClient.setDefaultUri("http://localhost:8080/ws/beers");
ClientInterceptor[] interceptors = new ClientInterceptor[]{securityInterceptor()};
beerClient.setInterceptors(interceptors);
return beerClient;
}
#Bean
public KeyStoreCallbackHandler securityCallbackHandler(){
KeyStoreCallbackHandler callbackHandler = new KeyStoreCallbackHandler();
callbackHandler.setPrivateKeyPassword("changeit");
return callbackHandler;
}
}

Problems with Postgresql with Spring Boot on Heroku

I decided to try out Spring Boot on Heroku and everything works perfectly...well, apart from the database!
I tried many different things to make it work, followed a lot of different approaches I found online and also from questions on StackOverflow, but nothing seems to work for me.
I'm going to post only the bare minimum of the app I'm trying to deploy.
The below is desployed fine, but when I'm trying to POST something I get the following as response:
{"timestamp":1413600470146,"error":"Unsupported Media Type","status":415,"message":"Unsupported Media Type"}
And when I'm trying to GET, I get the following exception in the Heroku logs:
nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: ERROR: relation "exampleEntity" does not exist
Position: 109
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2103)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1836)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:273)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
....
So, I have the following 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>com.example</groupId>
<artifactId>project-name</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.2.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<jersey.version>2.8</jersey.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-inmemory</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>1.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.2.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>http://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>org.jboss.repository.releases</id>
<name>JBoss Maven Release Repository</name>
<url>https://repository.jboss.org/nexus/content/repositories/releases</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<name>Spring Releases</name>
<url>http://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Then my Main class is:
package com.example;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.example.config.JerseyConfig;
#EnableAutoConfiguration
#ComponentScan
#EnableJpaRepositories
public class Main {
#Bean
public ServletRegistrationBean jerseyServlet() {
ServletRegistrationBean registration = new ServletRegistrationBean(new ServletContainer(), "/rest/*");
// our rest resources will be available in the path /rest/*
registration.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyConfig.class.getName());
return registration;
}
public static void main(String[] args) {
new SpringApplicationBuilder(Main.class).showBanner(false).run(args);
}
}
I also have a JerseyConfig (for Jersey configuration):
package com.example.config;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spring.scope.RequestContextFilter;
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(RequestContextFilter.class);
packages("com.example");
register(LoggingFilter.class);
}
}
And a BasicDataSource for the database:
package com.example.config;
import java.net.URI;
import java.net.URISyntaxException;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class SimpleDbConfig {
#Bean
public DataSource dataSource() throws URISyntaxException {
URI dbUri;
try {
String username = "username";
String password = "password";
String url = "jdbc:postgresql://localhost/dbname";
String dbProperty = System.getProperty("database.url");
if(dbProperty != null) {
dbUri = new URI(dbProperty);
username = dbUri.getUserInfo().split(":")[0];
password = dbUri.getUserInfo().split(":")[1];
url = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
}
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setUrl(url);
basicDataSource.setUsername(username);
basicDataSource.setPassword(password);
return basicDataSource;
} catch (URISyntaxException e) {
//Deal with errors here.
throw e;
}
}
}
Finally, I have my REST resource:
package com.example.resource;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.service.ExampleService;
import com.example.transport.ExampleEntity;
#Path("/entities")
#Component
public class ExampleResource {
private ExampleService exampleService;
#Autowired
public ExampleResource(ExampleService exampleService) {
this.exampleService = exampleService;
}
#POST
#Path("/new")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public ExampleEntity createNewEntity(ExampleEntity entity) {
return exampleService.createNewEntity(entity);
}
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public ExampleEntity getExampleDetails(#PathParam("id") Long id) {
return exampleService.findEntity(id);
}
}
A service class:
package com.example.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.repositories.ExampleRepository;
import com.example.transport.ExampleEntity;
#Service
public class ExampleService {
private ExampleRepository repo;
#Autowired
public ExampleService(ExampleRepository repo) {
this.repo = repo;
}
#Transactional
public ExampleEntity createNewEntity(ExampleEntity entity) {
ExampleEntity savedEntity = repo.save(entity);
return savedEntity;
}
#Transactional
public ExampleEntity findEntity(Long id) {
return repo.findOne(id);
}
}
The entity:
package com.example.transport;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
#Entity
public class ExampleEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And finally the repo interface:
package com.example.repositories;
import org.springframework.data.repository.CrudRepository;
import com.example.transport.ExampleEntity;
public interface MeetingRepository extends CrudRepository<ExampleEntity, Long> {
}
Any help is much appreciated!
Edit:
The Procfile I'm using is the following:
web: java -Dserver.port=$PORT -Ddatabase.url=$DATABASE_URL $JAVA_OPTS -jar target/project-name-0.0.1-SNAPSHOT.jar
It seems you have not created the table exampleEntity yet. I can see you are using postgreSQL, so please use heroku config | grep HEROKU_POSTGRESQL to check if you have one enabled in heroku (also its name and url). If not, enable it in your heroku account manager, it's a free plugin.
Use heroku pg:promote HEROKU_POSTGRESQL_<color of your db> to promote it to the main one. You will get some output like:
Promoting HEROKU_POSTGRESQL_BROWN_URL (DATABASE_URL) to DATABASE_URL... done
Now you should use DATABASE_URL environment variable to connect to your db. Heroku will provide it for you. (Also please post your Procfile too).
Using the url connect to your database and add the required table with a schema that maches your ExampleEntity class.
Side notes
Connecting to heroku db:
https://devcenter.heroku.com/articles/connecting-to-heroku-postgres-databases-from-outside-of-heroku
If you didn't understand some heroku stuff I wrote, their documentation is really well written:
https://devcenter.heroku.com/categories/heroku-architecture
https://devcenter.heroku.com/articles/heroku-postgresql
If I understood you all wrong and you're running your app on localhost and didn't deploy it to heroku yet, then just add the table to your local db instance.
Example I use with automatic table generation
Apart from DATABASE_URL, which is always there, Heroku creates 3 environment variables at Runtime. They are:
JDBC_DATABASE_URL
JDBC_DATABASE_USERNAME
JDBC_DATABASE_PASSWORD
As you may be aware, Spring Boot will automatically configure your database if it finds spring.datasource.* properties in your application.properties file. Here is an example of my application.properties
spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}
spring.jpa.show-sql=false
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
Hibernate / Postgres Dependencies
In my case I'm using Hibernate (bundled in spring-boot-starter-jpa with PostgreSQL, so I needed the right dependencies in my build.gradle:
dependencies {
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile('org.postgresql:postgresql:9.4.1212')
}

Categories