How to add a hook to the Vertx Launcher - vert.x

I would like to collect metrics with Vert.x Micrometer Metrics, so I need to set proper options to VertxOptions. I run Vertx with Launcher and there is a hook beforeDeployingVerticle but when I override it it's not called.
I overriden Launcher class and beforeDeployingVerticle method but this method is never executed.
public class LauncherTest {
public static class SimpleVerticle extends AbstractVerticle {
#Override
public void start(Future<Void> startFuture) throws Exception {
System.out.println("verticle started");
}
}
public static class LauncherWithHook extends Launcher {
#Override
public void beforeDeployingVerticle(DeploymentOptions deploymentOptions) {
System.out.println("before deploying");
}
}
public static void main(String[] args) {
new LauncherWithHook().execute("run", SimpleVerticle.class.getName());
}
}
In a result I receive just verticle started, but I expect also to have before deploying there. Should I add this hook somehow different?

change your main method like this:
public static void main(String[] args) {
String[] argz = {"run", "your.namepace.LauncherTest$SimpleVerticle"};
LauncherWithHook launcher = new LauncherWithHook();
launcher.dispatch(argz);
}

Related

How to send email from a servlet using threads or executor service?

Where executor service should be declared so it is available to other servlets and not new thread gets created for every new request
Can I do something like this and whenever need to send email, forward request to this servlet
Can you please suggest better design to use ExecutorService in servlet or any other way to send email from servlet?
public class EmailTestServlet extends HttpServlet
{
ExecutorService emailThreadPool = null;
public void init()
{
super.init();
emailThreadPool = Executors.newFixedThreadPool(3);
}
protected void doGet(HttpServletRequest request,HttpServletResponse response)
{
sendEmail(); //it will call emailThreadPool.execute();
}
public void destroy()
{
super.destroy();
}
}
Depends on whether CDI is available at your environment. It is available out the box in normal Jakarta EE servers, but in case of barebones servletcontainers such as Tomcat or Jetty you'd need to manually install and configure it. It's relatively trivial though and gives a lot of benefit: How to install and use CDI on Tomcat?
Then you can simply create an application scoped bean for the job like below:
#ApplicationScoped
public class EmailService {
private ExecutorService executor;
#PostConstruct
public void init() {
executor = Executors.newFixedThreadPool(3);
}
public void send(Email email) {
executor.submit(new EmailTask(email));
}
#PreDestroy
public void destroy() {
executor.shutdown();
}
}
In order to utilize it, simply inject it in whatever servlet or bean where you need it:
#WebServlet("/any")
public class AnyServlet extends HttpServlet {
#Inject
private EmailService emailService;
#Override
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
Email email = new Email();
// ...
emailService.send(email);
}
}
In case you find yourself in the unfortunate situation that you cannot use CDI, then you'll have to remove the #ApplicationScoped annotation from the EmailService class and reinvent the wheel by simulating whatever CDI is doing under the covers by manually fiddling with ServletContext#get/setAttribute() to simulate an application scoped bean. It might look like this:
#WebListener
public class ApplicationScopedBeanManager implements ServletContextListener {
#Override
public void contextCreated(ServletContextEvent event) {
EmailService emailService = new EmailService();
emailService.init();
event.getServletContext().setAttribute(EMAIL_SERVICE, emailService);
}
#Override
public void contextDestroyed(ServletContextEvent event) {
EmailService emailService = (EmailService) event.getServletContext().getAttribute(EMAIL_SERVICE);
emailService.destroy();
}
}
In order to utilize it, rewrite the servlet as follows:
#WebServlet("/any")
public class AnyServlet extends HttpServlet {
private EmailService emailService;
#Override
public void init() {
emailService = (EmailService) getServletContext().getAttribute(EMAIL_SERVICE);
}
#Override
protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
Email email = new Email();
// ...
emailService.send(email);
}
}
See also:
What is recommended way for spawning threads from a servlet in Tomcat
How to run a background task in a servlet based web application?
Background process in Servlet

How to write junit test for graceful shutdown in spring boot

I'm new to code coverage. I have started to write test cases for my spring boot application.
The below highlighted part in red, I'm unable to cover. Could you please suggest how to test these?
Here is my code.
#SpringBootApplication
public class ImsApplication extends SpringBootServletInitializer implements WebApplicationInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ImsApplication.class);
}
public static void contextDestroyed(ConfigurableApplicationContext ctx) {
int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
#Override
public int getExitCode() {
return 0;
}
});
System.exit(exitCode);
}
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(ImsApplication.class, args);
contextDestroyed(ctx);
}
public ImsApplication() {
super();
setRegisterErrorPageFilter(false);
}
#PostConstruct
public void init() {
TimeZone.setDefault(TimeZone.getTimeZone("IST"));
}
}

How beforeScenario and afterScenario works in JBehave

Can someone show examples of how beforeScenario and afterScenario works in JBehave?
I created a class with two methods gearUp with #BeforeScenario and tearDown with #AfterScenario annotations.
But these methods are never invoked in JBehave.
What extra configurations are needed. Any code examples will help us.
Whereas this simple and neat in Cucumber.
Following is my story file with single step(src/test/resources/storeis):
Scenario: SampleTest
Given I am test
Following is my Steps file
public class jbehavetc {
#Given("I am test")
public void startOnUrl(String url) {
System.out.println("I am actual test");
}
}
Following is my Hooks file which contains BeforeScenario and AfterScenario methods
public class Hooks {
#BeforeScenario
public void startSystem() throws Exception {
System.out.println("I am before scenario");
}
#AfterScenario
public void stopSystem() throws Exception {
System.out.println("I am after scenario");
}
}
To run the above story i created a runner file and wanted to run as JUnit Test(Correct me this is not the right approach)
public class JBehaveRunner extends JUnitStory{
#Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(
new LoadFromClasspath(getClass().getClassLoader()))
.useStoryReporterBuilder(
new StoryReporterBuilder()
.withDefaultFormats()
.withFormats(Format.HTML));
}
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new jbehavetc(),
new Hooks());
}
public List<String> storyPaths() {
return new StoryFinder().findPaths(
CodeLocations.codeLocationFromClass(this.getClass()),
Arrays.asList("**/*.story"),
Arrays.asList(""));
}
#Test
public void run() throws Throwable {
super.run();
}
}
When i run above runner as JUnit test, nothing is getting executed. How can i run above story? I want Before and After Scenario methods needs to be invoked when i run this runner or story file.
You should treat class with #BeforeScenario/#AfterScenario as classes with step implementations: you should register them in your steps factory.
BeforeAndAfterSteps.java
public class BeforeAndAfterSteps {
#BeforeScenario
public void beforeScenario() throws Exception {
// setup
}
#AfterScenario
public void afterScenario() throws Exception {
// teardown
}
}
Example of steps factory configuration
new InstanceStepsFactory(configuration, new BeforeAndAfterSteps())
Official JBehave examples:
Example of the class containing various before/after implementations: BeforeAfterSteps
Examples of this class references and usages:
CoreEmbedder
CoreStory
CoreStories
Following runner file started working for me:
public class JBehaveRunner extends JUnitStories {
#Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(
new LoadFromClasspath(getClass().getClassLoader()))
.useStoryReporterBuilder(
new StoryReporterBuilder()
.withDefaultFormats()
.withFormats(Format.HTML));
}
#Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new HomePageSteps(),
new BaseEngine());
}
#Test
public void run() throws Throwable {
super.run();
}
#Override
public List<String> storyPaths() {
return new StoryFinder().findPaths(
CodeLocations.codeLocationFromClass(this.getClass()),
Arrays.asList("**/*.story"),
Arrays.asList(""));
}
}

How to create an instance of A class that extends Application

I just designed a simple javaFx app. While running it solo works, but when I try to separated and create an instance of it all I get :
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
my code
import javafx.application.Application;
import javafx.stage.Stage;
public class Demo
{
public static void main(String[] args)
{
Demos dm = new Demos();
}
}
class Demos extends Application {
private String args;
private Stage stage;
public Demos()
{
main(args);
start(stage);
}
public void main(String args)
{
this.args=args;
launch(this.args);
}
#Override
public void start(Stage stage)
{
this.stage=stage;
this.stage.setTitle("Simple JavaFX Application");
this.stage.setResizable(false);
this.stage.show();
}
}
Application.launch requires the Application class to be lauched to be public. This is not the case for your Demos class.
Additional Notes
private String args;
private Stage stage;
public Demos()
{
main(args);
...
}
public void main(String args)
{
this.args=args;
...
}
Just assigns the initial value of args to itself, which will always result in args remaining null.
Application.launch is a static method creating the Application instance itself. Calling this form from a instance makes little sense.
If you want to launch a specific Application, pass the Application class to Application.launch:
public static void main(String[] args) {
Application.launch(Demos.class);
}
public Demos extends Application {
private Stage stage;
public Demos(){
}
#Override
public void start(Stage stage) {
this.stage=stage;
this.stage.setTitle("Simple JavaFX Application");
this.stage.setResizable(false);
this.stage.show();
}
}

How to make out.println() method working in a simple java file without using System Class reference?

public class ABC{ public static void main(String[] args) { out.println("Hello"); } }
This works, though static imports are not generally considered a good thing in java.
import static java.lang.System.out;
public class ABC {
public static void main(String[] args) {
out.println("hello");
}
}