Expose metrics with akka-http-metrics in java - java

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.

Related

Apache Camel Context start failure

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>

NoSuchMethodError using dropwizard websocket jee7 bundle server

I'm using Dropwizard for a REST server and dropwizard-websocket-jee7-bundle to enable websockets.
For the websocket server I used this example.
Testing the websocket server standalone works fine, but in combination with Dropwizard, when a client tries to connect (to ws://localhost:port/actions) it gets a 500 Internal Server Error (Error log below).
I'm guessing there is some bad or missing configuration, but I can't figure our where.
ServerExample:
package com.example;
import static org.eclipse.jetty.servlets.CrossOriginFilter.ALLOWED_HEADERS_PARAM;
import static org.eclipse.jetty.servlets.CrossOriginFilter.ALLOWED_METHODS_PARAM;
import static org.eclipse.jetty.servlets.CrossOriginFilter.ALLOWED_ORIGINS_PARAM;
import static org.eclipse.jetty.servlets.CrossOriginFilter.ALLOW_CREDENTIALS_PARAM;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import com.example.health.SearchHealthCheck;
import com.example.resources.TestFind;
import be.tomcools.dropwizard.websocket.WebsocketBundle;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import com.example.websocket.DeviceWebSocketServer;
public class ServerExample extends Application<ServerExampleConfiguration> {
private WebsocketBundle websocket = new WebsocketBundle();
public static void main(String[] args) throws Exception {
new ServerExample().run(args);
}
#Override
public String getName() {
return "com.example";
}
#Override
public void initialize(Bootstrap<ServerExampleConfiguration> bootstrap) {
super.initialize(bootstrap);
bootstrap.addBundle(websocket);
}
#Override
public void run(ServerExampleConfiguration configuration, Environment environment) throws Exception {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORSFilter", CrossOriginFilter.class);
filter.setInitParameter(ALLOWED_METHODS_PARAM, "OPTIONS,POST,GET");
filter.setInitParameter(ALLOWED_ORIGINS_PARAM, "*");
filter.setInitParameter(ALLOWED_HEADERS_PARAM, "Origin,Content-Type,Accept,X-Requested-With");
filter.setInitParameter(ALLOW_CREDENTIALS_PARAM, "true");
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
environment.jersey().register(new TestFind());
environment.healthChecks().register("search", new SearchHealthCheck());
//Annotated endpoint
websocket.addEndpoint(DeviceWebSocketServer.class);
}
}
DeviceWebSocketServer:
package com.example.websocket;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.io.StringReader;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import com.example.model.Device;
import java.util.logging.Level;
import java.util.logging.Logger;
#ApplicationScoped
#ServerEndpoint("/actions")
public class DeviceWebSocketServer {
#Inject
private DeviceSessionHandler sessionHandler;
#OnOpen
public void open(Session session) {
sessionHandler.addSession(session);
}
#OnClose
public void close(Session session) {
sessionHandler.removeSession(session);
}
#OnError
public void onError(Throwable error) {
Logger.getLogger(DeviceWebSocketServer.class.getName()).log(Level.SEVERE, null, error);
}
#OnMessage
public void handleMessage(String message, Session session) {
try (JsonReader reader = Json.createReader(new StringReader(message))) {
JsonObject jsonMessage = reader.readObject();
if ("add".equals(jsonMessage.getString("action"))) {
Device device = new Device();
device.setName(jsonMessage.getString("name"));
device.setDescription(jsonMessage.getString("description"));
device.setType(jsonMessage.getString("type"));
device.setStatus("Off");
sessionHandler.addDevice(device);
}
if ("remove".equals(jsonMessage.getString("action"))) {
int id = (int) jsonMessage.getInt("id");
sessionHandler.removeDevice(id);
}
if ("toggle".equals(jsonMessage.getString("action"))) {
int id = (int) jsonMessage.getInt("id");
sessionHandler.toggleDevice(id);
}
}
}
}
DeviceSessionHandler:
package com.example.websocket;
import javax.enterprise.context.ApplicationScoped;
import javax.json.JsonObject;
import javax.json.spi.JsonProvider;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.Session;
import com.example.model.Device;
#ApplicationScoped
public class DeviceSessionHandler {
private int deviceId = 0;
private final Set<Session> sessions = new HashSet<>();
private final Set<Device> devices = new HashSet<>();
public void addSession(Session session) {
sessions.add(session);
for (Device device : devices) {
JsonObject addMessage = createAddMessage(device);
sendToSession(session, addMessage);
}
}
public void removeSession(Session session) {
sessions.remove(session);
}
public List<Device> getDevices() {
return new ArrayList<>(devices);
}
public void addDevice(Device device) {
device.setId(deviceId);
devices.add(device);
deviceId++;
JsonObject addMessage = createAddMessage(device);
sendToAllConnectedSessions(addMessage);
}
public void removeDevice(int id) {
Device device = getDeviceById(id);
if (device != null) {
devices.remove(device);
JsonProvider provider = JsonProvider.provider();
JsonObject removeMessage = provider.createObjectBuilder()
.add("action", "remove")
.add("id", id)
.build();
sendToAllConnectedSessions(removeMessage);
}
}
public void toggleDevice(int id) {
JsonProvider provider = JsonProvider.provider();
Device device = getDeviceById(id);
if (device != null) {
if ("On".equals(device.getStatus())) {
device.setStatus("Off");
} else {
device.setStatus("On");
}
JsonObject updateDevMessage = provider.createObjectBuilder()
.add("action", "toggle")
.add("id", device.getId())
.add("status", device.getStatus())
.build();
sendToAllConnectedSessions(updateDevMessage);
}
}
private Device getDeviceById(int id) {
for (Device device : devices) {
if (device.getId() == id) {
return device;
}
}
return null;
}
private JsonObject createAddMessage(Device device) {
JsonProvider provider = JsonProvider.provider();
JsonObject addMessage = provider.createObjectBuilder()
.add("action", "add")
.add("id", device.getId())
.add("name", device.getName())
.add("type", device.getType())
.add("status", device.getStatus())
.add("description", device.getDescription())
.build();
return addMessage;
}
private void sendToAllConnectedSessions(JsonObject message) {
for (Session session : sessions) {
sendToSession(session, message);
}
}
private void sendToSession(Session session, JsonObject message) {
try {
session.getBasicRemote().sendText(message.toString());
} catch (IOException ex) {
sessions.remove(session);
Logger.getLogger(DeviceSessionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Dependencies:
<dependencies>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>org.apache.jena</groupId>
<artifactId>jena-arq</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.8</version>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1</version>
</dependency><dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>be.tomcools</groupId>
<artifactId>dropwizard-websocket-jee7-bundle</artifactId>
<version>1.1.0</version>
</dependency>
</dependencies>
Error Log:
WARN [2017-08-31 16:55:46,863] org.eclipse.jetty.servlet.ServletHandler: Error for /actions
! java.lang.NoSuchMethodError: org.eclipse.jetty.io.AbstractConnection.<init>(Lorg/eclipse/jetty/io/EndPoint;Ljava/util/concurrent/Executor;Z)V
! at org.eclipse.jetty.websocket.common.io.AbstractWebSocketConnection.<init>(AbstractWebSocketConnection.java:225)
! at org.eclipse.jetty.websocket.server.WebSocketServerConnection.<init>(WebSocketServerConnection.java:41)
! at org.eclipse.jetty.websocket.server.WebSocketServerFactory.upgrade(WebSocketServerFactory.java:520)
! at org.eclipse.jetty.websocket.server.WebSocketServerFactory.acceptWebSocket(WebSocketServerFactory.java:186)
! at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:206)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
! at io.dropwizard.servlets.ThreadNameFilter.doFilter(ThreadNameFilter.java:34)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
! at io.dropwizard.jersey.filter.AllowedMethodsFilter.handle(AllowedMethodsFilter.java:50)
! at io.dropwizard.jersey.filter.AllowedMethodsFilter.doFilter(AllowedMethodsFilter.java:44)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
! at org.eclipse.jetty.servlets.CrossOriginFilter.handle(CrossOriginFilter.java:308)
! at org.eclipse.jetty.servlets.CrossOriginFilter.doFilter(CrossOriginFilter.java:262)
! at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
! at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:581)
! at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1174)
! at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:511)
! at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1106)
! at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
! at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
! at com.codahale.metrics.jetty9.InstrumentedHandler.handle(InstrumentedHandler.java:240)
! at io.dropwizard.jetty.RoutingHandler.handle(RoutingHandler.java:51)
! at org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:459)
! at io.dropwizard.jetty.BiDiGzipHandler.handle(BiDiGzipHandler.java:68)
! at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:56)
! at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:169)
! at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
! at org.eclipse.jetty.server.Server.handle(Server.java:524)
! at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:319)
! at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:253)
! at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273)
! at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
! at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
! at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
! at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
! at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
! at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
! at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
! at java.lang.Thread.run(Thread.java:745)
0:0:0:0:0:0:0:1 - - [31/ago/2017:16:55:46 +0000] "GET /actions HTTP/1.1" 500 245 "-" "-" 47
Edited: Added dependencies list.
Downgraded the dropwizard version I was using to the last reported version in the bundle (0.9.1) and this error is gone (although i have a null pointer exception now. will open a new question about that error).

Vertx trying to launch embedded server

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

How to use jersey with Grizzly 2.3

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?

GoogleTransport class problem

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/).

Categories

Resources