Running Verticle from start() method - java

I'm new to Vert.x and I'm a little bit confused with how to run\deploy Vert.x app.
I'm used to write a server by having a main class with static main() method which there performs all my initial startup code, like: connecting to DB, reading configuration files, initializing internal services and eventually creating the listening socket for accepting new connections.
For example:
public class Server {
public static void main(String args[]) {
Server server = new Server();
server.run();
}
public void run() {
// load configuration
....
// Connect to DB
....
// Initialize internal services
....
// Create listening socket on server port
...
// and more...
}
now to my question:
Vert.x forces me to make my main class extends Verticle class and override start() method
to initialize the listening socket.
so now all my initialization process must be done inside this start() method.
Does this make sense??
and I can never run my application via command line like I'm used to but rather use the "vertex" app
Am I missing something??

Yes, you are correct. A vertx app is nothing but a set of verticles running inside vertx instances.
If you want your app to have main method as usual then you can use vertx as embedded mode i.e inside your main method you start a vertx instance using the API and then start verticles inside that instance.
Check out embedding guide at: https://vertx.io/vertx2/embedding_manual.html

Related

Writing tests for grizzly sever with jersey with jar dependency

I start the server from the terminal via the java -jar target/test-service-1.0-jar-with-dependencies.jar command
However when running tests from Intellij Idea, I just cannot figure out how to start the server..
This is the current code, which doesn't work
private HttpServer server;
private WebTarget target;
#Before
public void setUp() throws Exception {
// start the server
server = Main.startServer();
// create the client
Client c = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
// uncomment the following line if you want to enable
// support for JSON in the client (you also have to uncomment
// dependency on jersey-media-json module in pom.xml and Main.startServer())
// --
// c.configuration().enable(new org.glassfish.jersey.media.json.JsonJaxbFeature());
target = c.target(Main.BASE_URI);
}
This is my startServer code
public static HttpServer startServer() {
// create a resource config that scans for JAX-RS resources and providers
ResourceConfig rc = new ResourceConfig().packages("com.test.service").register(JacksonFeature.class);
EncodingFilter.enableFor(rc, GZipEncoder.class);
rc.register(LoggingFilter.class);
rc.register(MultiPartFeature.class);
rc.register(CORSResponseFilter.class);
// rc.property("config", configParams);
// create and start a new instance of grizzly http server
// exposing the Jersey application at BASE_URI
HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
//httpServer.getServerConfiguration().addHttpHandler(shh);
return httpServer;
}
It should just start by itself. But for testing you probably want to control when it starts. You can pass false as the third argument to the server factory method. That way you control when it should start.
You can call start and stop on the HttpServer instance in your before and after methods in your test. You'll need to update the code in the Main class also, to call start().
You might also want to check out Jersey Test Framework. Here you won't need to start and stop any servers. The framework will handle it for you. It also makes your tests more configurable than your current set up. Say you only want one resource registered or you want to inject some mocks services. Personally, I would go with the test framework.

Executing java methods and application on remote slave

I want to able to have a client/server application which can perform the following:
Have client send "java task instructions" (ex. name of method, class to run or app to execute) to a remote server
server receives the task execution details and launches a new JVM and loads the classpath etc...
server executes the task
server stores the task response in a cache
shuts down the new JVM
server continues to wait for further executable task details which could reference object in cache by name
What is the best APIs to implement this in Java if I don't want to use RMI?
Do I want to establish a connection by using a socket or is there an easier API?
From what I know, correct me if im wrong, I cannot use ProcessBuilder to execute a static method or to get a response.
thanks in advance
UPDATE
I am new to threads and RMI, so how would I then make it so that when client gets the factory stub to creates a new object which will contain the behavior actually needed to execute a task on the server, that the object code is executing in its own thread?
I want this behavior so that two different clients are executing two different tasks at the same time in different threads without reusing the same remote object instance. Here is some simple sample code to help explain what I want
Factor Interface
public interface Factory extends Remote
{
public Executor create() throws RemoteException;
}
Factory implementation
public class FactoryImpl implements Factory
{
public FactoryImpl()
{}
#Override
public Executor create() throws RemoteException
{
//create a new executor in another thread
}
}
Executor interface
public interface Executor extends Runnable, Remote
{
public String executeTask(String pClass, String pMethod, List<String> arguments) throws RemoteException;
}
Do I just want to create/start a new Runnable class that instantiates the executor object?

How to shutdown Ehcache CacheManager in standalone application

I have a simple API that my clients use in a standalone application. Behind the scenes my API uses Ehcache for performance.
Everything works fine except that my client needs to invoke a shutdown() method in my API to invoke CacheManager.shutdown() without which Ehcache continues to run in the background even though the main thread is completed.
Is there a way I can avoid this extra shutdown() call for my client?
I tried using #PreDestroy Spring annotation to invoke this call, but it didn't work?
Here I am adding a sample client program.
public class ClientApp{
#Autowired
private IClientService service;
public static void main(String[] args){
try{
service.getClients();
...
} finally {
service.shutdown(); // to shutdown the cache background thread
}
}
}
In ClientServiceImpl.java, I have the following lines
public void shutdown(){
LOGGER.info("Shutting the cache down...");
ehcacheManager.shutdown();
}
Your example confirms the standalone application setup.
Ehcache should not prevent the JVM from shutting down when the main thread terminates.
If it does, you will need to add thread dumps to this issue so we can analyse further the issue and its cause.
Adding the following line does what I was looking for.
System.setProperty(CacheManager.ENABLE_SHUTDOWN_HOOK_PROPERTY, "true");

Java TCPIP EJB Threads

I am developing a TCPIP application where the client will send information to a specified port and the server will listen to that port. I would like to achieve the following:
Reconnect to the the client/port to see whether it is active after a specified time period.
I have the below code implemented:
#Stateless
#Local
public Listener implements ConnectionListener {
public void listen() throws Exception {
ServerSocket serverSocket = new ServerSocket(somePort);
Socket socket = serverSocket.accept();
while(!socket.isClosed()) {
}
}
}
public interface ConnectionListener {
public void listen() throws Exception;
}
How can this be achived with EJB technology? I know the while loop is wrong but what can be included. I have two approaches:
Wait for a time period to reconnect
Thread
However, I do not wish to use the Thread appraoch.
I know in EJB there are things such as an EJBTimer. What would be the best way to implement this and how could this be implemented in the code. Could you help how I could change the while loop to do what I want it to do?
Also, the client has no API to call on this application. How can this instance be triggered on start up of the Application Server so that messages are listened to. Usually, this could be achieved through a Servlet but I don't think this will work. Any ideas?
This kind of functionality is at the "edge" of the types of things you would do in EJB. typically, EJBs do not directly do network type activity, especially long term listening.
what you really want is an EJB singleton. this is kind of like a standalone instance which can do more advanced things like custom concurrency/threading and (relevant to you) start a custom socket listener.

junit wait until external resource is ready

I am trying to test Cassandra with JUnit External resources. I have two classes CassandraExternalResource and TestCassandra. Here is snippet from TestCassandra:
public class TestCassandra {
#Rule
public CassandraExternalResource cassandraExternalResource = new CassandraExternalResource();
#Test
public void test() throws InterruptedException {
System.out.println("During Test");
}
}
In before method of CassandraExternalResource I start Cassandra Server with a separate thread. What I want is to make test cases wait until cassandra server is up and running.
Since server takes some time to start, test cases start to run before server is ready.
Any help is appreciated.
You can extend the rule's before method by pinging the cassandra server until it is ready.

Categories