Configuring Jetty component in Camel 2.15 - apache-camel

I'm trying to start using Jetty with Camel.
I have added the dependency to my pom:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jetty</artifactId>
<version>2.15.5</version>
</dependency>
My CamelContext is initialized as follows:
public void startCamelContext() throws Exception {
CamelContext camelContext = new DefaultCamelContext();
camelContext.addComponent("jetty", new JettyHttpComponent8());
camelContext.start();
}
When I try to start up my service, which has a route with endpoint defined as:
jetty:http://0.0.0.0:9000/httpInput
I get an exception:
java.lang.NullPointerException: null
at org.apache.camel.component.jetty8.JettyHttpComponent8.createConnectorJettyInternal(JettyHttpComponent8.java:48)
at org.apache.camel.component.jetty.JettyHttpComponent.createConnector(JettyHttpComponent.java:585)
at org.apache.camel.component.jetty.JettyHttpComponent.getSocketConnector(JettyHttpComponent.java:527)
at org.apache.camel.component.jetty.JettyHttpComponent.getConnector(JettyHttpComponent.java:517)
at org.apache.camel.component.jetty.JettyHttpComponent.connect(JettyHttpComponent.java:320)
at org.apache.camel.component.http.HttpEndpoint.connect(HttpEndpoint.java:185)
at org.apache.camel.component.http.HttpConsumer.doStart(HttpConsumer.java:53)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.impl.DefaultCamelContext.startService(DefaultCamelContext.java:2885)
at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRouteConsumers(DefaultCamelContext.java:3179)
at org.apache.camel.impl.DefaultCamelContext.doStartRouteConsumers(DefaultCamelContext.java:3115)
at org.apache.camel.impl.DefaultCamelContext.safelyStartRouteServices(DefaultCamelContext.java:3045)
at org.apache.camel.impl.DefaultCamelContext.doStartOrResumeRoutes(DefaultCamelContext.java:2813)
at org.apache.camel.impl.DefaultCamelContext.startAllRoutes(DefaultCamelContext.java:865)
The documentation on how to set up the Jetty component is lacking at best. I found a mailing-list entry where it was said that JettyHttpComponent has been made abstract since Camel 2.15 and now that component has to be configured using JettyHttpComponent8 or 9. link
In my case, I'm using Camel 2.15.5 and the JettyHttpComponent9 isn't available in the classpath, and using 8 gives the exception described above.
I also found related discussion here with no information on how to actually use that component.

That's typically not how the CamelContext is initialized/started. Please consider using an archetype to get started, then add the Jetty Maven dependency and see if the error can be reproduced.
Camel archetypes can be found here: http://camel.apache.org/camel-maven-archetypes.html

To start a camel context outside spring you need to create a continuous thread to keep camel alive, as explaine here: http://camel.apache.org/running-camel-standalone-and-have-it-keep-running.html
Don't worry, I have below some code that will setup a jetty on localhost:8081 for you:
pom.xml
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jetty</artifactId>
<version>2.16.1</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>2.16.1</version>
</dependency>
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.main.MainListenerSupport;
import org.apache.camel.main.MainSupport;
import java.util.Date;
/**
* Created by mkbrv on 22/06/16.
*/
public class CamelJetty {
private Main main;
public static void main(String[] args) throws Exception {
CamelJetty example = new CamelJetty();
example.boot();
}
public void boot() throws Exception {
// create a Main instance
main = new Main();
// bind MyBean into the registry
main.bind("foo", new MyBean());
// add routes
main.addRouteBuilder(new MyJettyRouteBuilder());
// add event listener
main.addMainListener(new Events());
// run until you terminate the JVM
System.out.println("Starting Camel. Use ctrl + c to terminate the JVM.\n");
main.run();
}
private static class MyJettyRouteBuilder extends RouteBuilder {
#Override
public void configure() throws Exception {
from("jetty:http://localhost:8081")
.process(exchange -> {
System.out.println("Invoked timer at " + new Date());
exchange.getOut().setBody("Hi, this is Camel!");
})
.bean("foo");
}
}
public static class MyBean {
public void callMe() {
System.out.println("MyBean.callMe method has been called");
}
}
public static class Events extends MainListenerSupport {
#Override
public void afterStart(MainSupport main) {
System.out.println("MainExample with Camel is now started!");
}
#Override
public void beforeStop(MainSupport main) {
System.out.println("MainExample with Camel is now being stopped!");
}
}
}
Next just go to http://localhost:8081 and you should see a welcome message.
Have fun tweaking this further more.

Related

FailedToStartRouteException exception while using camel-spring-boot, amqp and kafka starters with SpringBoot, unable to find connectionFactory bean

I am creating an application using Apache Camel to transfer messages from AMQP to Kafka. Code can also be seen here - https://github.com/prashantbhardwaj/qpid-to-kafka-using-camel
I thought of creating it as standalone SpringBoot app using spring, amqp and kafka starters. Created a route like
#Component
public class QpidToKafkaRoute extends RouteBuilder {
public void configure() throws Exception {
from("amqp:queue:destinationName")
.to("kafka:topic");
}
}
And SpringBoot application configuration is
#SpringBootApplication
public class CamelSpringJmsKafkaApplication {
public static void main(String[] args) {
SpringApplication.run(CamelSpringJmsKafkaApplication.class, args);
}
#Bean
public JmsConnectionFactory jmsConnectionFactory(#Value("${qpidUser}") String qpidUser, #Value("${qpidPassword}") String qpidPassword, #Value("${qpidBrokerUrl}") String qpidBrokerUrl) {
JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory(qpidPassword, qpidPassword, qpidBrokerUrl);
return jmsConnectionFactory;
}
#Bean
#Primary
public CachingConnectionFactory jmsCachingConnectionFactory(JmsConnectionFactory jmsConnectionFactory) {
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(jmsConnectionFactory);
return cachingConnectionFactory;
}
jmsConnectionFactory bean which is created using Spring Bean annotation should be picked by amqp starter and should be injected into the route. But it is not happening. When I started this application, I got following exception -
org.apache.camel.FailedToStartRouteException: Failed to start route route1 because of Route(route1)[From[amqp:queue:destinationName] -> [To[kafka:.
Caused by: java.lang.IllegalArgumentException: connectionFactory must be specified
If I am not wrong connectionFactory should be created automatically if I pass right properties in application.properties file.
My application.properties file looks like :
camel.springboot.main-run-controller = true
camel.component.amqp.enabled = true
camel.component.amqp.connection-factory = jmsCachingConnectionFactory
camel.component.amqp.async-consumer = true
camel.component.amqp.concurrent-consumers = 1
camel.component.amqp.map-jms-message = true
camel.component.amqp.test-connection-on-startup = true
camel.component.kafka.brokers = localhost:9092
qpidBrokerUrl = amqp://localhost:5672?jms.username=guest&jms.password=guest&jms.clientID=clientid2&amqp.vhost=default
qpidUser = guest
qpidPassword = guest
Could you please help suggest why during autoconfiguring connectionFactory object is not being used? When I debug this code, I can clearly see that connectionFactory bean is getting created.
I can even see one more log line -
CamelContext has only been running for less than a second. If you intend to run Camel for a longer time then you can set the property camel.springboot.main-run-controller=true in application.properties or add spring-boot-starter-web JAR to the classpath.
however if you see my application.properties file, required property is present at the very first line.
One more log line, I can see at the beginning of application startup -
[main] trationDelegate$BeanPostProcessorChecker : Bean 'org.apache.camel.spring.boot.CamelAutoConfiguration' of type [org.apache.camel.spring.boot.CamelAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Is this log line suggesting anything?
Note - One interesting fact that exactly same code was running fine last night, just restarted my desktop and there is not even a single word changed and now it is throwing exception.
This just refers to an interface
camel.component.amqp.connection-factory = javax.jms.ConnectionFactory
Instead it should refer to an existing factory instance, such as
camel.component.amqp.connection-factory = #myFactory
Which you can setup via spring boot #Bean annotation style.

Report builder says Cucumber is not a valid report

I have used below code for creating html reports , this code is present in after class of Junit Runner in a cucumber framework , but am getting error saying cucumber.json is not a valid cucumber report. I am assuming that report builder is trying to get the cucumber.json even before it is created completely,
I kept code in cucumber options to create Json file
#CucumberOptions(features = "features/",
glue = { "report"},
format = {"pretty","json:target/cucumber.json"},
tags = {"#testing" }, monochrome = true)
private void generateReportForJsonFiles(File reportOutputDirectory,
List<String> jsonFiles) {
String jenkinsBasePath = "";
String buildNumber = "1";
String projectName = project.getName();
Configuration configuration = new Configuration(reportOutputDirectory, projectName);
configuration.setParallelTesting(false);
configuration.setJenkinsBasePath(jenkinsBasePath);
configuration.setRunWithJenkins(false);
configuration.setBuildNumber(buildNumber);
ReportBuilder reportBuilder = new ReportBuilder(jsonFiles, configuration);
reportBuilder.generateReports();
}
Below is the error:
File 'target/cucumber.json' is not proper Cucumber report!
you should provide a small example (MCVE) which others can use to reproduce your problem
your code snippet configuration.setParallelTesting(false) and your answer cucumber report version is <version>4.2.0</version> do not match, as the method configuration.setParallelTesting was removed in version 4.1.0
Have a look at this small working snippet (based on the few information you provided).
Assume the following structure
pom.xml
src/main/java/CreateReport.java
src/main/resources/log4j2.properties
src/test/java/TestRunner.java
src/test/java/stepdefs/StepDefinitions.java
src/test/resource/features/demo.feature
pom.xml
...
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<!--
info.cukes:cucumber-java:1.2.5 is quite old and has been superseded by
io.cucumber:cucumber-java see: https://mvnrepository.com/artifact/io.cucumber/cucumber-java
-->
<version.cucumber>1.2.5</version.cucumber>
</properties>
<dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
...
CreateReport.java
import java.io.File;
import java.util.Arrays;
import java.util.List;
import net.masterthought.cucumber.Configuration;
import net.masterthought.cucumber.ReportBuilder;
public class CreateReport {
private void generateReportForJsonFiles(File reportOutputDirectory, List<String> jsonFiles) {
String buildNumber = "1";
String projectName = "StackOverflow example";
Configuration configuration = new Configuration(reportOutputDirectory, projectName);
configuration.setParallelTesting(false);
// configuration.setJenkinsBasePath(jenkinsBasePath);
configuration.setRunWithJenkins(false);
configuration.setBuildNumber(buildNumber);
ReportBuilder reportBuilder = new ReportBuilder(jsonFiles, configuration);
reportBuilder.generateReports();
}
public static void main(String[] args) {
new CreateReport().generateReportForJsonFiles(new File("target/"),
Arrays.asList("target/cucumber.json"));
}
}
log4j2.properties
status = info
name = PropertiesConfig
appenders = console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%level] %m%n
rootLogger.level = info
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
TestRunner.java
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src/test/resource/features"},
glue = {"stepdefs"},
plugin = {"json:target/cucumber.json"}
)
public class TestRunner {
}
StepDefinitions.java
package stepdefs;
import org.junit.Assert;
import cucumber.api.java.en.Given;
public class StepDefinitions {
#Given("^a successful step$")
public void aSuccessfulStep() throws Throwable {
System.out.println("a successful step");
}
#Given("^a not successful step$")
public void aNotSuccessfulStep() throws Throwable {
System.out.println("a not successful step");
Assert.fail();
}
}
demo.feature
Feature: Test cucumber reporting plugin
Scenario: Run a non failing scenario
Given a successful step
Scenario: Run a failing scenario
Given a not successful step
run the Cucumber test (this creates the target/cucumber.json file)
$ mvn clean test
run the report creator (
$ mvn exec:java -Dexec.mainClass=CreateReport
...
12:55:21 [INFO] --- exec-maven-plugin:1.6.0:java (default-cli) # cuke-test23.so ---
Dec 18, 2018 12:55:22 PM net.masterthought.cucumber.ReportParser parseJsonFiles
INFO: File 'target/cucumber.json' contains 1 features
the report is generated in target/cucumber-html-reports/overview-features.html

Spring AOP No visible constructors in class

Error: java.lang.IllegalArgumentException: No visible constructors in class org.springframework.hateoas.config.HypermediaSupportBeanDefinitionRegistrar$DefaultObjectMapperCustomizer
Mostly, I used example given in link, and the following code can be found at github repository
Annotation:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
public #interface NeedTestClass {
}
Aspect:
#After("#args(NeedTestClass)")
public void afterReturningAtArgs() {
log.info("aspect: after #args {}");
}
Service:
#Slf4j
#Component
public class BusinessService {
public void logicWithAnnotatedArgs1(Child c) {
log.info("service");
}
}
Pojo (top class, not sub class):
#NoArgsConstructor // tried with or without
#NeedTestClass
public class Child {}
Test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
#WebAppConfiguration
#SpringBootTest
public class AopTest {
#Autowired
private BusinessService myBusinessService;
#Test
public void testAtArgsPCD() {
myBusinessService.logicWithAnnotatedArgs1(new Child());
}
I attempted to examine aop and annotated class inheritance, but it seems the first step could not be ok. I have tried #annotation() and this() PCD both ok.
EDIT:
So far I am wondering maybe the error is related with the bean loading sequence.
Your GitHub project does not even compile. Have you even tested it? First by trial and error I had to add all of these dependencies:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>com.alibaba.druid</groupId>
<artifactId>druid-wrapper</artifactId>
<version>0.2.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
Next, I noticed that the Maven build does not seem to start the local (127.0.0.1) database because Spring Boot says this at start-up:
(...)
2018-01-02 17:57:18.882 INFO 14480 --- [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
2018-01-02 17:57:20.007 ERROR 14480 --- [tionPool-Create] com.alibaba.druid.pool.DruidDataSource : create connection error
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:590) ~[mysql-connector-java-6.0.6.jar:6.0.6]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:57) ~[mysql-connector-java-6.0.6.jar:6.0.6]
(...)
Would you mind refactoring your GitHub project into an MCVE first before I can check on your actual problem? This way the error is not reproducible.
But having said this, I did notice something in your POM and Java files: Maybe the problem is not where you think it is. I can see that you want to use Lombok in combination with Spring AOP. According to my answer here, there are compatibility problems between AspectJ and Lombok. Maybe they also affect Spring AOP. So can you temporarily test without #Slf4j and other Lombok stuff? As soon as you will have fixed your project I can also test by myself.
Update after GitHub repo project has been repaired:
Now I can build and run your program, thanks. It seems that the parameter is somehow passed through to internal Spring classes you do not wish to target. So just modify your pointcut like this:
#After("#args(com.example.demosm.my.aop.NeedTestClass) && within(com.example.demosm..*)")

How to use Microsoft Access database with spring boot and spring data

Here is my application.properties file:
spring.datasource.url=jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=BD_Name.mdb")
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=sun.jdbc.odbc.JdbcOdbcDriver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
and I use jdk7 which contains the driver sun.jdbc.odbc.JdbcOdbcDriver but when I start, springBoot return the exception "couldn't load driver".
First, you need the following dependencies
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
Connecting MS Access with spring boot, use the below following configuration in application.properties
spring.datasource.url=jdbc:ucanaccess://C:/Users/FazalHaroon/Documents/JavaTest/accountsdb.accdb;openExclusive=false;ignoreCase=true
spring.datasource.driver-class-name=net.ucanaccess.jdbc.UcanaccessDriver
this is the example where i insert new data into my MS Access Database, then i use a select query to fetch all the records from the 'Account' table.
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
#SpringBootApplication
public class TaskApplication implements CommandLineRunner {
#Autowired
private JdbcTemplate template;
public static void main(String[] args) {
SpringApplication.run(NagarroTaskApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// template.update("INSERT INTO account(account_type, account_number) VALUES('test', '1233443543')");
List<Account> accountList = template.query("SELECT ID, account_type, account_number FROM account", new RowMapper<Account>() {
#Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Account(rs.getInt("ID"), rs.getString("account_type"), rs.getString("account_number"));
}
});
accountList.forEach(System.out::println);
}
}
It seems that you want to connect with MS Access, but the driver used is for JDBC.
Change the driver to the following and it should work:
spring.datasource.driver-class-name=net.ucanaccess.jdbc.UcanaccessDriver

CXF: WARNING: No message body writer has been found for response class ArrayList

I'm getting the following error:
WARNING: No message body writer has been found for response class ArrayList.
On the following code:
#GET
#Consumes("application/json")
public List getBridges() {
return new ArrayList(bridges);
}
I know it's possible for CXF to handle this case because I've done it before - with a platform that defined the CXF and related maven artifacts behind the scenes (i.e. I didn't know how it was done).
So, the question: how can I get CXF to support this without adding XML bindings or other source code modifications?
Note the following answer addressed the same problem with XML bindings, which is not satisfactory for my case:
No message body writer has been found for response class ArrayList
The problem turns out to be a simple missing Accept header:
Accept: application/json
Adding this to the request resolves the problem.
The best thing is indeed to use Jackson.
The following post gives a great description of why and how to do it.
for your convinience I've summerized the main things:
You will need to set Jackson as the provider, the best way to do it is to use your custom Application overriding javax.ws.rs.core.Application
you will need to add the following code
#Override
public Set<Object> getSingletons() {
Set<Object> s = new HashSet<Object>();
// Register the Jackson provider for JSON
// Make (de)serializer use a subset of JAXB and (afterwards) Jackson annotations
// See http://wiki.fasterxml.com/JacksonJAXBAnnotations for more information
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector primary = new JaxbAnnotationIntrospector();
AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primary, secondary);
mapper.getDeserializationConfig().setAnnotationIntrospector(pair);
mapper.getSerializationConfig().setAnnotationIntrospector(pair);
// Set up the provider
JacksonJaxbJsonProvider jaxbProvider = new JacksonJaxbJsonProvider();
jaxbProvider.setMapper(mapper);
s.add(jaxbProvider);
return s;
}
Finally,
do not forget to add Jackson to your maven
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.7</version>
<scope>compile</scope>
</dependency>
Having the same problem I've finally solved it like this. In your Spring context.xml define bean:
<bean id="jsonProvider" class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider"/>
And use it in the <jaxrs:server> as a provider:
<jaxrs:server id="restService" address="/resource">
<jaxrs:providers>
<ref bean="jsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
In your Maven pom.xml add:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.0</version>
</dependency>
If you are using Jackson you can write custom message body writer.
public class KPMessageBodyWriter implements
MessageBodyWriter<ArrayList<String>> {
private static final Logger LOG = LoggerFactory.getLogger(KPMessageBodyWriter.class);
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return true;
}
public long getSize(ArrayList<String> t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return t.size();
}
public void writeTo(ArrayList<String> t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(entityStream, t);
}
}
In cx configuration file add the provider
<jaxrs:providers>
<bean class="com.kp.KPMessageBodyWriter" />
</jaxrs:providers>

Resources