I am using jersey rest api (JAX-RS) of 2.25.1 version. I tried to use LoggingFeature class at server side and as well as client side.
Client side code:
public static void getOperation() {
ClientConfig config = new ClientConfig();
config.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, LoggingFeature.Verbosity.PAYLOAD_ANY);
config.register(new LoggingFeature(logger, LoggingFeature.Verbosity.PAYLOAD_ANY));
Client client = ClientBuilder.newClient(config);
client.register(ClientEmpReqFilter.class);
client.register(ClientEmpResFilter.class);
WebTarget target = client.target("http://localhost:8080").path("restappln/rest/entity");
String str = target.request(MediaType.APPLICATION_JSON).get(String.class);
System.out.println(str);
}
and Server-side code is :
#ApplicationPath("/rest")
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages("<package name>");
register(LoggingFeature.class);
}
}
I am not able to get logging. I am passing instance of java.util.Logger to the contructor of client config.
config.register(new LoggingFeature(logger, LoggingFeature.Verbosity.PAYLOAD_ANY));
Related
I'm just beginning to learn Vert.x and how to code Verticles. I wonder if it makes any sense to deploy a Verticle from within an Application server or Web server like Tomcat. For example:
public class HelloVerticle extends AbstractVerticle {
private final Logger logger = LoggerFactory.getLogger(HelloVerticle.class);
private long counter = 1;
#Override
public void start() {
vertx.setPeriodic(5000, id -> {
logger.info("tick");
});
vertx.createHttpServer()
.requestHandler(req -> {
logger.info("Request #{} from {}", counter++, req.remoteAddress().host());
req.response().end("Hello!");
})
.listen(9080);
logger.info("Open http://localhost:9080/");
}
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new HelloVerticle());
}
}
Obviously the main method needs to be replaced by some ContextListener of any trigger provided by the Application Server. Does it make any sense or it's not supposed to use Vert.x in this Context?
Thanks
Using Vert.x as a Verticle inside a Tomcat app doesn't make much sense from my POV, because it defeats the whole point of componentization.
On the other hand you might want to simply connect to Event Bus to send/publish/receive messages, and is fairly easy to achieve.
I did it for a Grails (SB-based) project and put the Vertx stuff inside a service like:
class VertxService {
Vertx vertx
#PostConstruct
void init() {
def options = [:]
Vertx.clusteredVertx(options){ res ->
if (res.succeeded())
vertx = res.result()
else
System.exit( -1 )
})
}
void publish( addr, msg ){ vertx.publish addr, msg }
//...
}
I am currently running into an issue while creating a reactive mongoclient when I provide the URL with ssl=true option.
I am creating configuration class in spring boot where I create Reactive mongoclient using the following option:
MongoClients.create(Connections ring Conn)
Here when I try to connect to a DB with no ssl settings it works, but with ssl enabled option I am getting error saying NettyEventLoop class is not found.
Can anyone suggest what I can do to fix this issue
It seems that the API has changed, so since MongoDB driver v3.8, the method is "applyToSslSettings":
import com.mongodb.Block;
import com.mongodb.connection.SslSettings;
import com.mongodb.connection.SslSettings.Builder;
import com.mongodb.connection.netty.NettyStreamFactoryFactory;
import io.netty.channel.nio.NioEventLoopGroup;
#Configuration
public class Config {
private NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
#Bean
public MongoClientSettingsBuilderCustomizer sslCustomizer() {
Block<SslSettings.Builder> sslSettingsBlock = new Block<SslSettings.Builder>() {
#Override
public void apply(Builder t) {
t.applySettings(SslSettings.builder()
.enabled(true)
.invalidHostNameAllowed(true)
.build());
}
};
return clientSettingsBuilder -> clientSettingsBuilder
.applyToSslSettings(sslSettingsBlock)
.streamFactoryFactory(NettyStreamFactoryFactory.builder()
.eventLoopGroup(eventLoopGroup).build());
}
#PreDestroy
public void shutDownEventLoopGroup() {
eventLoopGroup.shutdownGracefully();
}
}
I was able to overcome this issue by configuring MongoClientSettingsBuilderCustomizer and NioEventLoop Group.
Please find below the code:
private NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
#Bean
public MongoClientSettingsBuilderCustomizer sslCustomizer() {
return clientSettingsBuilder -> clientSettingsBuilder
.sslSettings(SslSettings.builder()
.enabled(true)
.invalidHostNameAllowed(true)
.build())
.streamFactoryFactory(NettyStreamFactoryFactory.builder()
.eventLoopGroup(eventLoopGroup).build());
}
I have a Vert.x REST service that receive requests with jwt tokens, and I want to call my another REST service passing received token. Between router handler and WebClient call I have a business logic layer. My question is if there is a method to provide token to webClient other than passing it explicitly through my business logic layer? In other words is it possible to retrieve somehow my RoutingContext and token from e.g. vertxContext or an other component?
Example code demonstrating what I would like to achieve:
Verticle cass
public class RestApiVerticle extends AbstractVerticle {
businessLogicService service;
#Override
public void start() throws Exception {
initService();
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
JWTAuth authProvider = JWTAuth.create(vertx, getAuthConfig());
router.route("/*").handler(JWTAuthHandler.create(authProvider));
router.route("/somePath").handler(this::handleRequest);
server.requestHandler(router::accept).listen(config().getInteger("port"));
}
private void handleRequest(RoutingContext context){
service.doSomeBusinessLogic(); //I could pass context here, but I thing this is not a proper way to do it, as business logic should not know about RequestContext
}
private void initService(){
ExternalAPICaller caller = new ExternalAPICaller(WebClient.create(vertx));
service = new BusinessLogicService(caller);
}
private JsonObject getAuthConfig() {
return new JsonObject();
}
}
BusinessLogicService:
public class BusinessLogicService {
ExternalAPICaller caller;
public BusinessLogicService(ExternalAPICaller caller){
this.caller = caller;
}
public void doSomeBusinessLogic(){
caller.doSth();
}
}
ExternalAPICaller:
public class ExternalAPICaller {
WebClient client;
public ExternalAPICaller(WebClient client){
this.client = client;
}
public void doSth(){
String TOKEN = null; // I would like to retrive here my token from some vertx component
client.post("externalAPIpath")
.putHeader("Authorization", "Bearer" + TOKEN)
.send(ctx -> {
//(..)
});
}
}
My implementation is in JavaScript (Node.js/Express), but I used cookies to send the JWT to the client.
res.cookie("auth", token);
return res.redirect(`http://localhost:3000/socialauthredirect`);
When you call your do business logic method you could pass the request authorization header value as it contains your untouched jwt token. Then on your web client add a header with that value and of course named authorization and your token is forwarded to the next service.
I am working on a Processing program within Eclipse and I am having issues initializing the Client object. I have properly imported both core.jar and net.jar from the Processing package into my class from these locations:
C:\Program Files\eclipse\processing-2.0.2\core\library
C:\Program Files\eclipse\processing-2.0.2\modes\java\libraries\net\library\net.jar
public class Client extends PApplet {
private static final long serialVersionUID = 0L;
// Declare a client
Client client;
public void setup() {
size(400, 200);
// create the client
client = new Client(this, "127.0.0.1", 8888);
}
}
The line Eclipse is complaining about (client = new Client(this, "127.0.0.1", 8888) shows an error: the constructor Client(Client, String, int) is undefined.
Per the Client API, there is a constructor that takes those arguments: http://processing.org/reference/libraries/net/Client.html.
I have also tried client = new Client(this, 8888); and Eclipse is still complaining about an error. Can anyone help guide me on how to resolve this? Thanks.
Your class is called Client so the new Client in your code is trying to create an instance of your class. What you actually want is an instance of processing.net.Client. It would be best to use a different name for you class:
import processing.net.Client;
public class MyApplet extends PApplet {
private static final long serialVersionUID = 0L;
// Declare a client
Client client;
public void setup() {
size(400, 200);
// create the client
client = new Client(this, "127.0.0.1", 8888);
}
}
I have changed the class name to MyApplet.
I try to connect to a (local) web service using the GWT RequestBuilder with a secure connection (SSL), but the connection isn't established... When I connect using a plain HTTP connection everything works fine.
Some details
everything works fine when I'm using my browser to view the pages,
I use an auto signed SSL certificate on my local machine,
the tests fail because the actual response code (responseCode) is not set,
the tests work fine if I'm using a plain HTTP connection (no SSL).
Code
package com.example.services;
import com.google.gwt.http.client.*;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.Timer;
public class RequestBuilderTest extends GWTTestCase {
private static String SERVER_URL = "https://127.0.0.1/api";
private static final int ASSERT_DELAY_IN_MS = 15000;
private static final int TEST_DURATION_IN_MS = 20000;
private int statusCode;
public void testGet() throws Exception {
new RequestBuilder(RequestBuilder.GET, SERVER_URL).sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable e) {
fail(e.getMessage());
}
public void onResponseReceived(Request request, Response response) {
statusCode = response.getStatusCode();
}
});
delayTestFinish(TEST_DURATION_IN_MS);
new Timer() {
#Override
public void run() {
assertEquals(Response.SC_OK, statusCode);
finishTest();
}
}.schedule(ASSERT_DELAY_IN_MS);
}
#Override
public String getModuleName() {
return "com.example.services.RequestBuilder";
}
}
Results
test passes with SERVER_URL = "http://127.0.0.1/api";
test fails with SERVER_URL = "https://127.0.0.1/api";
This is the stack trace for junit:
junit.framework.AssertionFailedError: Remote test failed at 127.0.0.1
expected=200 actual=0
Any ideas on what could be wrong and how can I make the tests work with SSL?
EDIT
How can I force the tests to run in secure mode? I use eclipse... I tried setting some "Program arguments" in the "Run configurations" (for the junit tests), but they don't work... Here are the arguments:
-noserver -startupUrl https://192.168.8.147/com.example.services.RequestBuilderTest.JUnit/ -bindAddress 0.0.0.0
Is it better if I just deactivate the SSL on the server? These tests are meant to be launched on the continuous integration server and I wanted to test them using SSL.
It sounds like you're running into a same-origin policy problem. Embedding a URL into the app like that is inherently unreliable. Instead, use GWT.getModuleBaseUrl().