I am trying to launch an initial test of a Vertx.io server, but I get the following error message:
Exception in thread "main" java.lang.NoClassDefFoundError: org/vertx/java/core/Handler
Code:
package com.company;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.VertxFactory;
import org.vertx.java.core.http.HttpServerRequest;
import java.io.IOException;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
private Object shutdownLock = new Object();
public Main() throws IOException, InterruptedException {
start(1234);
keepServerFromShuttingDown();
}
private void keepServerFromShuttingDown() throws InterruptedException {
synchronized (shutdownLock) {
shutdownLock.wait();
}
log.info("Shutting down");
}
public void start(int port) {
Vertx vertx = VertxFactory.newVertx();
vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() {
#Override
public void handle(HttpServerRequest request) {
}
}).listen(port);
}
public static void main(String[] args) throws IOException, InterruptedException {
new Main();
}
}
pom.xml:
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-platform</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-hazelcast</artifactId>
<version>2.1.2</version>
</dependency>
</dependencies>
It looks like a basic CLASSPATH issue where it is not able to find Vertx classes while executing your program. Please check if the vertx libraries are indeed a part of your CLASSPATH.
Though unrelated, but if you are checking out Vertx for some new projects, I highly recommend version 3.0 and you could start with this simple maven project example
Related
I'm trying expose metrics to Prometheus with library https://github.com/RustedBones/akka-http-metrics in java project.
After adapted code to java, I dont receive http metrics after call method, only a empy response.
If add module for jvm I have only jvm metrics.
package test;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.server.AllDirectives;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.server.directives.RouteAdapter;
import fr.davit.akka.http.metrics.core.scaladsl.server.HttpMetricsDirectives$;
import fr.davit.akka.http.metrics.prometheus.PrometheusRegistry;
import fr.davit.akka.http.metrics.prometheus.PrometheusSettings;
import fr.davit.akka.http.metrics.prometheus.marshalling.PrometheusMarshallers$;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.hotspot.DefaultExports;
import static akka.http.javadsl.server.PathMatchers.segment;
public class TestHttpMetrics extends AllDirectives {
public Route createRoute() {
return pathPrefix(segment("v1").slash("metrics"),
() -> concat(
path(segment("prometheus"), () -> get(this::micrometer)),
complete(StatusCodes.NOT_FOUND, "Path not found")
)
);
}
public Route micrometer() {
return pathEnd(() -> {
try {
CollectorRegistry prometheus = new CollectorRegistry();
PrometheusSettings settings = new MyPrometheusSettings().getInstance();
PrometheusRegistry registry = new PrometheusRegistry(settings, prometheus);
//DefaultExports.register(prometheus); //for JVM metrics
return RouteAdapter.asJava(HttpMetricsDirectives$.MODULE$.metrics(registry, PrometheusMarshallers$.MODULE$.marshaller()));
} catch (Exception e) {
e.printStackTrace();
}
return complete(StatusCodes.INTERNAL_SERVER_ERROR, "ERROR");
});
}
}
class MyPrometheusSettings {
public PrometheusSettings getInstance() throws Exception {
PrometheusSettings ps = ((PrometheusSettings) PrometheusSettings.class.getDeclaredMethod("default").invoke(null)) //default is reserved in java!
.withNamespace("akka_http")
.withIncludePathDimension(true)
.withIncludeMethodDimension(true)
.withIncludeStatusDimension(true)
.withDurationConfig(PrometheusSettings.DurationBuckets())
.withReceivedBytesConfig(PrometheusSettings.DefaultQuantiles())
.withSentBytesConfig(PrometheusSettings.DefaultQuantiles())
.withDefineError(response -> response.status().isFailure());
return ps;
}
}
in pom
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-http_2.12</artifactId>
<version>10.2.4</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.12.13</version>
</dependency>
<dependency>
<groupId>fr.davit</groupId>
<artifactId>akka-http-metrics-prometheus_2.12</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>io.prometheus</groupId>
<artifactId>simpleclient_hotspot</artifactId>
<version>0.15.0</version>
</dependency>
Where is the problem? In debug mode there is only null values in registry.
I am pretty new to Spring Boot, Apache Camel and the ActiveMQ broker. I am trying to create an application which will send a message to a queue which I am hosting locally using Camel for routing.
POM:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>2.22.0</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-activemq</artifactId>
<version>3.2.0</version>
</dependency>
MsgRouteBuilder:
public void configure() throws Exception {
from("direct:firstRoute")
.setBody(constant("Hello"))
.to("activemq:queue:myQueue");
}
application.yaml:
activemq:
broker-url: tcp://localhost:61616
user: meAd
password: meAd
MainApp.java:
package me.ad.myCamel;
import org.apache.camel.CamelContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import me.ad.myCamel.router.MessageRouteBuilder;
#SpringBootApplication
#EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
#EnableAspectJAutoProxy(proxyTargetClass = true)
#EnableCaching
public class MeAdApp implements CommandLineRunner {
private static final Logger LOG = LoggerFactory.getLogger(MeAdApp.class);
public static void main(String[] args) {
try {
SpringApplication.run(MeAdApp.class, args);
} catch (Exception ex) {
LOG.error(ex.getMessage(), ex);
}
}
#Override
public void run(String... args) throws Exception {
LOG.info("Starting MeAdApp...");
}
}
MyController.java :
#GetMapping(value = "/routing")
public boolean sendToMyQueue() {
sendMyInfo.startRouting();
return true;
}
SendMyInfo.java :
MsgRouteBuilder routeBuilder = new MsgRouteBuilder();
CamelContext ctx = new DefaultCamelContext();
public void startRouting(){
try {
ctx.addRoutes(routeBuilder);
ctx.start();
Thread.sleep(5 * 60 * 1000);
ctx.stop();
}
catch (Exception e) {
e.printStackTrace();
}
}
So, whenever I call my rest end point: /routing, I get the error:
java.lang.NoSuchMethodError: org.apache.camel.RuntimeCamelException.wrapRuntimeException(Ljava/lang/Throwable;)Ljava/lang/RuntimeException;`
Can anybody please point me to the right direction as to why I am getting this error? Any help is greatly appreciated .
You need to have the components of the same version. If you are using camel-core with 3.2.0, use camel-activemq 3.2.0. And, since you are using spring-boot, you can make use of the starter dependencies. Just add these and you are good to go.
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-activemq-starter</artifactId>
<version>3.2.0</version>
</dependency>
In my Java and maven project I have used cucumber for BDD test.
Here is the dependency I use:
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>4.2.0</version>
</dependency>
my Hooks class:
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.AfterStep;
import cucumber.api.java.BeforeStep;
public class Hooks {
#Before
public void init() {
System.out.println( " Before Scenario " );
}
#After
public void cleanUp() {
System.out.println( " After Scenario " );
}
#BeforeStep
public void beforeStep() {
System.out.println("======> This is before step <======");
//Do something before executing the step
}
#AfterStep
public void afterStep() {
System.out.println("======> This is after step <======");
}
}
But when I run my cucumber test it just prints Before Scenario, and After Scenario. Meanwhile, I expect to see, This is before step, and This is after step
before, and after each step.
So, why #AfterStep, and #BeforeStep do not work?
you should provide a small example which others can use to reproduce your problem
Have a look at this small snippet which is working
Assume the following structure
pom.xml
src/test/java/TestRunner.java
src/test/java/stepdefs/StepDefinitions.java
src/test/java/stepdefs/Hooks.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>
<version.cucumber>4.2.0</version.cucumber>
</properties>
<dependencies>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${version.cucumber}</version>
<scope>test</scope>
</dependency>
</dependencies>
...
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"}
)
public class TestRunner {
}
StepDefinitions.java
package stepdefs;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinitions {
#Given("^a successful step$")
public void aSuccessfulStep() {
System.out.println(" aSuccessfulStep()");
}
#When("doing something")
public void doingSomething() {
System.out.println(" doingSomething()");
}
#Then("something happen")
public void somethingHappen() {
System.out.println(" somethingHappen()");
}
}
Hooks.java
package stepdefs;
import cucumber.api.java.After;
import cucumber.api.java.AfterStep;
import cucumber.api.java.Before;
import cucumber.api.java.BeforeStep;
public class Hooks {
#Before
public void init() {
System.out.println("#Before scenario");
}
#After
public void cleanUp() {
System.out.println("#After scenario");
}
#BeforeStep
public void beforeStep() {
System.out.println(" #BeforeStep");
}
#AfterStep
public void afterStep() {
System.out.println(" #AfterStep");
}
}
demo.feature
Feature: Test cucumber reporting plugin
Scenario: Run a non failing scenario
Given a successful step
When doing something
Then something happen
running the tests
$ mvn clean test
produces following output
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running TestRunner
#Before scenario
#BeforeStep
aSuccessfulStep()
#AfterStep
#BeforeStep
doingSomething()
#AfterStep
#BeforeStep
somethingHappen()
#AfterStep
#After scenario
1 Scenarios (1 passed)
3 Steps (3 passed)
I am reading Spring Framework reference documentation (version 5.0.0.M1), page 70:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scripting.Messenger;
public final class Boot {
public static void main(final String[] args) throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("scripting/beans.xml");
Messenger messenger = (Messenger) ctx.getBean("messenger");
System.out.println(messenger);
}
}
I try adding:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
but cannot resolve dependency. Where to find dependency has org.springframework.scripting.Messager?
I'm trying to use google guice for dependency injection however I can't seem to wire everything togheter.
In my web.xml I defined the guiceFilter and the guiceListener like so:
<filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>backend.listener.GuiceConfigListener</listener-class>
</listener>
the config listener is basicly pretty simple:
#Override
protected Injector getInjector(){
return Guice.createInjector(new ServletModule(), new ArtsModule());
}
and the ArtsModule at this moment just has one binding like so:
#Override
protected void configure(){
bind(ArtsDAO.class).to(ArtsDAOGae.class);
}
I then continue to do a field injection of the ArtsDao in a service class:
#Inject
private ArtsDAO artsDAO;
But when I try to build my project (which is a maven build) I get a NPE on the artsDAO field, this most likely happens because the unit tests aren't running in a web environment.
Can anyone advice me on how to configure the guice bidings so that they are picked up during unit testing?
Thanks
Pip,
this is not trivial task but definitely you can achieve what you want.
First of all have a look at Tadedon project at https://code.google.com/p/tadedon
especially tadedon-guice-servlet-mock.
You will need something like fake container for your test. My fake container contains also Apache Shiro integration so you can throw it out, It looks like:
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.xemantic.tadedon.guice.servlet.mock.FakeServletContainer;
import com.xemantic.tadedon.guice.servlet.mock.FakeServletContainerModule;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.SubjectThreadState;
import org.apache.shiro.web.subject.WebSubject;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Arrays;
public class FakeTestContainerInit {
private final FakeServletContainer servletContainer;
private final Injector internalInjector;
private Subject internalSubject;
public FakeTestContainerInit() {
this(new Module[] {});
}
public FakeTestContainerInit(Module... modules) {
super();
modules = Arrays.copyOf(modules, modules.length + 1);
modules[modules.length-1] = new FakeServletContainerModule();
internalInjector = Guice.createInjector(modules);
servletContainer = internalInjector.getInstance(FakeServletContainer.class);
}
public void start() throws ServletException, IOException {
this.start(true);
}
public void start(boolean initializeSecurityContext) throws ServletException, IOException {
getServletContainer().start();
MockHttpServletRequest request = servletContainer.newRequest("GET","/");
MockHttpServletResponse response = new MockHttpServletResponse();
if(initializeSecurityContext) {
SecurityManager scm = internalInjector.getInstance(SecurityManager.class);
internalSubject = new WebSubject.Builder(scm, request, response).buildWebSubject();
SubjectThreadState sts = new SubjectThreadState(internalSubject);
sts.bind();
} else { internalSubject = null; }
getServletContainer().service(request, response);
}
public void stop() {
servletContainer.stop();
}
public FakeServletContainer getServletContainer() {
return servletContainer;
}
public <T> T getInstance(final Class<T> type) throws IOException, ServletException {
return getServletContainer().getInstance(type);
}
public <T> T getInstance(final Key<T> key) throws IOException, ServletException {
return getServletContainer().getInstance(key);
}
public Subject getSubject() {
return internalSubject;
}
}
Dependencies:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.sonatype.sisu</groupId>
<artifactId>sisu-guice</artifactId>
</dependency>
<dependency>
<groupId>com.xemantic.tadedon</groupId>
<artifactId>tadedon-guice-servlet-mock</artifactId>
</dependency>
and Apache Shiro you won't need:
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
</dependency>
All you need to do, is create FakeTestContainerInit and call start() and stop() method. Also all object creations have to be done via FakeTestContainerInit.getInstance method inside tests.
Well, I used it to test Vaadin application so I did not need sending requests and checking responses. So, this one you will need to implement. It can be done via getServletContainer().service(request, response);. But i think you will figure out. Hope it will help you.