I currently try out the Grizzly-Framework 2.3.6.
I am using the following maven dependency:
<dependency>
<groupId>org.glassfish.grizzly</groupId>
<artifactId>grizzly-framework</artifactId>
<version>2.3.6</version>
</dependency>
<dependency>
<groupId>org.glassfish.grizzly</groupId>
<artifactId>grizzly-http-server</artifactId>
<version>2.3.6</version>
</dependency>
I can start a server with the following code example:
HttpServer server = HttpServer.createSimpleServer();
try {
server.start();
addJaxRS(server);
System.out.println("Press any key to stop the server...");
System.in.read();
} catch (Exception e) {
System.err.println(e);
}
I added the following JAX-RS Class:
#Path("/helloworld")
public class HelloWorldResource {
#GET
#Produces("text/plain")
public String getClichedMessage() {
return "Hello World";
}
}
My question is: how can I tell grizzly to add the HelloWorldRessoruce as a JAX-RS Resource?
I found a solution by changing the dependency to "jersey-grizzly2" which includes the grizzly version 2.2.16
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-grizzly2</artifactId>
<version>1.17.1</version>
</dependency>
</dependencies>
I can now start grizzly with my JAX-RS resources like this:
import java.io.IOException;
import org.glassfish.grizzly.http.server.HttpServer;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
public class Main {
public static void main(String[] args) throws IOException {
// HttpServer server = HttpServer.createSimpleServer();
// create jersey-grizzly server
ResourceConfig rc = new PackagesResourceConfig("my.resources");
HttpServer server = GrizzlyServerFactory.createHttpServer(
"http://localhost:8080", rc);
try {
server.start();
System.out.println("Press any key to stop the server...");
System.in.read();
} catch (Exception e) {
System.err.println(e);
}
}
}
But I initially thought that jersey is part of Grizzly?
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>
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
I am creating an embedded Jetty webapp with Jersey. I do not know how to add Jackson for automatic JSON serde here:
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter(
ServerProperties.PROVIDER_CLASSNAMES,
StringUtils.join(
Arrays.asList(
HealthCheck.class.getCanonicalName(),
Rest.class.getCanonicalName()),
";"));
// Create JAX-RS application.
final Application application = new ResourceConfig()
.packages("com.example.application")
.register(JacksonFeature.class);
// what do I do now to tie this to the ServletHolder?
How do I register this ResourceConfig with the ServletHolder so Jackson with be used where the annotation #Produces(MediaType.APPLICATION_JSON) is used? Here is the full main class for the embedded Jetty application
package com.example.application.web;
import com.example.application.api.HealthCheck;
import com.example.application.api.Rest;
import com.example.application.api.Frontend;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import javax.ws.rs.core.Application;
import java.util.Arrays;
public class JettyStarter {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(9090);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter(
ServerProperties.PROVIDER_CLASSNAMES,
StringUtils.join(
Arrays.asList(
HealthCheck.class.getCanonicalName(),
Rest.class.getCanonicalName()),
";"));
// Create JAX-RS application.
final Application application = new ResourceConfig()
.packages("com.example.application")
.register(JacksonFeature.class);
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
System.out.println("Could not start server");
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
One way is to just wrap the ResourceConfig in an explicit construction of the ServletContainer, as seen here.
Tested with your example
public class RestServer {
public static void main(String[] args) throws Exception {
// Create JAX-RS application.
final ResourceConfig application = new ResourceConfig()
.packages("jersey.jetty.embedded")
.register(JacksonFeature.class);
ServletContextHandler context
= new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(9090);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = new ServletHolder(new
org.glassfish.jersey.servlet.ServletContainer(application));
jerseyServlet.setInitOrder(0);
context.addServlet(jerseyServlet, "/*");
// ... removed property (init-param) to compile.
try {
jettyServer.start();
jettyServer.join();
} catch (Exception e) {
System.out.println("Could not start server");
e.printStackTrace();
} finally {
jettyServer.destroy();
}
}
}
You could also...
without changing anything else in your original post, just set the init param to scan the Jackson provider package
jerseyServlet.setInitParameter(ServerProperties.PROVIDER_PACKAGES,
"com.fasterxml.jackson.jaxrs.json;"
+ "jersey.jetty.embedded" // my package(s)
);
Note your attempted use of ResourceConfig seems a little redundant, as you are already configuring your classes in the the init param. You could alternatively get rid of adding each class explicitly and just scan entire packages as I have done.
You could also...
just use the Jackson provider classes you need. You can look in the jar, and you will see more than just the marshalling/unmarhalling provider (Jackson[JAXB]JsonProvider), like a ExceptionMappers. You may not like these mappers and wand to configure your own. In which case, like I said, just include the provider you need. For example
jerseyServlet.setInitParameter(ServerProperties.PROVIDER_CLASSNAMES,
"com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider");
jerseyServlet.setInitParameter(ServerProperties.PROVIDER_PACKAGES,
"jersey.jetty.embedded" // my package(s)
);
After further testing...
Not sure what version of Jersey, but I am using Jersey 2.15 (with jersey-media-json-jackson:2.15), and without any further configuration from just scanning my package for my resource classes, the Jackson feature is already enabled. This is part of the auto discoverable features. I believe this was enable as of 2.8 or 2.9 for the Jackson feature. So if you are using a later one, I don't think you need to explicitly configure anything, at least from what I've tested :-)
UPDATE
All of the above examples have been tested with the below 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.underdog.jersey</groupId>
<artifactId>jersey-jetty-embedded</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<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.15</jersey.version>
<jetty.version>9.2.6.v20141205</jetty.version>
</properties>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>${jetty.version}</version>
</dependency>
</dependencies>
<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>
</project>
And resource class
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/json")
public class JsonResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getJson() {
Resource resource = new Resource();
resource.hello = "world";
return Response.ok(resource).build();
}
public static class Resource {
public String hello;
}
}
Using path
http://localhost:9090/json
i'm using a maven project with following dependency :
<dependency>
<groupId>com.google.api.client</groupId>
<artifactId>google-api-client-googleapis-auth-clientlogin</artifactId>
<version>1.2.3-alpha</version>
</dependency>
when i run following code:
import java.io.IOException;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.googleapis.auth.clientlogin.ClientLogin;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws IOException
{
HttpTransport transport = GoogleTransport.create();
// transport.addParser(new JsonCParser());
try {
// authenticate with ClientLogin
ClientLogin authenticator = new ClientLogin();
authenticator.authTokenType = "ndev";
authenticator.username = "....";
authenticator.password = "....";
authenticator.authenticate().setAuthorizationHeader(transport);
// make query request
HttpRequest request = transport.buildGetRequest();
request.setUrl("https://www.googleapis.com/bigquery/v1/query");
request.url.put(
"q", "select count(*) from [bigquery/samples/shakespeare];");
System.out.println(request.execute().parseAsString());
} catch (HttpResponseException e) {
System.err.println(e.response.parseAsString());
throw e;
}
}
}
i get below exception:
Exception in thread "main" java.lang.IllegalStateException: Missing required low-level HTTP transport package.
Use package "com.google.api.client.javanet".
at com.google.api.client.http.HttpTransport.useLowLevelHttpTransport(HttpTransport.java:129)
at com.google.api.client.http.HttpTransport.<init>(HttpTransport.java:187)
at com.google.api.client.googleapis.GoogleTransport.create(GoogleTransport.java:58)
at com.example.clientlogin.App.main(App.java:18)
what is the problem with GoogleTransport class?
Quick googeling resulted in maven for com.google.api.client.javanet.nethttpresponse Try adding
<dependency>
<groupId>com.google.api.client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.2.3-alpha</version>
</dependency>
or
<dependency>
<groupId>com.google.api.client</groupId>
<artifactId>google-api-client-javanet</artifactId>
<version>1.2.3-alpha</version>
</dependency>
to your POM file
this question is pretty old, but I've added some updates to our Java Google Client Lib + BigQuery samples (here: http://code.google.com/p/google-bigquery-tools/source/browse/samples/java/gettingstarted/BigQueryJavaGettingStarted/).