I am trying to make an automation wizard that would take some files from system (via a command handler) and make its relevant applet.
I shall try to explain my senario.
I made a plugin for new command "newModule" which is handled via "newModuleHandler.java". so newModuleHandler extends AbstractHandler.
Now i would like to make a wizard (applet) that helps me with certain selections that i need to make in order to complete that "newModule" command. so
newModuleHandler extends Applet too.
i wrote newModuleHandler something like this.
package archetypedcomponent.commands;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import java.applet.*;// required when you create an applet
import java.awt.Graphics;
public class newModuleHandler extends AbstractHandler {
#Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isHandled() {
// TODO Auto-generated method stub
return true;
}
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
// TODO Auto-generated method stub
return null;
}
public class HelloWorld extends Applet
{
// The method that will be automatically called when the applet is started
public void init()
{
// It is required but does not need anything.
System.out.println("Applet initiated");
}
// This method gets called when the applet is terminated
// That's when the user goes to another page or exits the browser.
public void stop()
{
// no actions needed here now.
System.out.println("Applet Stopped");
}
// The standard method that you have to use to paint things on screen
// This overrides the empty Applet method, you can't called it "display" for example.
public void paint(Graphics g)
{
//method to draw text on screen
// String first, then x and y coordinate.
System.out.println("Applet in paint");
g.drawString("Hey hey hey",20,20);
g.drawString("Hellooow World",20,40);
}
}
}
Now when the command will b given this method will be called
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
// TODO Auto-generated method stub
return null;
}
and applet will have to be called inside it. my question is how to call it?
========================================================================================
i was able to solve my problem but m replying here so that somebody who is also facing same problem can b guided
this is my new "newModuleHandler.java"
package archetypedcomponent.commands;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import java.applet.*;// required when you create an applet
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
public class newModuleHandler extends AbstractHandler {
#Override
public boolean isEnabled() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isHandled() {
// TODO Auto-generated method stub
return true;
}
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
// TODO Auto-generated method stub
// call applet here
JFrame jp1 = new JFrame();
Loader a=new Loader ();
jp1.getContentPane().add(a, BorderLayout.CENTER);
jp1.setSize(new Dimension(500,500));
jp1.setVisible(true);
return null;
}
}
i made a new Loader.java which extends applet
package archetypedcomponent.commands;
import java.applet.Applet;
import java.awt.Graphics;
public class Loader extends Applet
{
// The method that will be automatically called when the applet is started
public void init()
{
// It is required but does not need anything.
System.out.println("Applet initiated");
// Graphics g=new ;
}
// This method gets called when the applet is terminated
// That's when the user goes to another page or exits the browser.
public void stop()
{
// no actions needed here now.
System.out.println("Applet Stopped");
}
// The standard method that you have to use to paint things on screen
// This overrides the empty Applet method, you can't called it "display" for example.
public void paint(Graphics g)
{
//method to draw text on screen
// String first, then x and y coordinate.
System.out.println("Applet in paint");
g.drawString("Hey hey hey",20,20);
g.drawString("Hellooow World",20,40);
}
}
Now whatever i need applet to do can b done in paint of Loader.
An applet can have more than one Object, so extends AbstractHandler in some other class that the applet has a reference to.
Related
using bytebuddy to intercept class Foo, whihc has two method A,B
in A method, B method get called. if we deleget both A and B to C method in intercetpor class Bar, which call callable#call at first line
what will happen ? what's the execution sequence of those methods ?
package org.wxt.xtools.agents;
import static net.bytebuddy.matcher.ElementMatchers.isAbstract;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.namedOneOf;
import static net.bytebuddy.matcher.ElementMatchers.not;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.implementation.bind.annotation.SuperCall;
import net.bytebuddy.utility.JavaModule;
class Foo {
public void methodA() {
System.out.println("method A");
methodB();
}
public void methodB() {
System.out.println("method B");
}
}
class Bar {
#RuntimeType
public static void interceptor(#Origin Class<?> clazz, #Origin Method method, #SuperCall Callable<?> callable,
#net.bytebuddy.implementation.bind.annotation.This Object inst) throws Exception {
callable.call();
System.out.println("intercepting " + method.getName());
}
}
public class Test {
public static void premain(String agentArgs, Instrumentation inst) throws IOException {
AgentBuilder.Transformer methodsTransformer = new AgentBuilder.Transformer() {
#Override
public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder, TypeDescription typeDescription,
ClassLoader classLoader, JavaModule javaModule) {
return builder.method(namedOneOf("methodA", "methodB").and(not(isAbstract())))
.intercept(MethodDelegation.to(Bar.class));
}
};
AgentBuilder.Listener listener = new AgentBuilder.Listener.WithErrorsOnly(
new AgentBuilder.Listener.StreamWriting(System.out));
new AgentBuilder.Default().type(named("org.wxt.xtools.agents.Foo")).transform(methodsTransformer)
.with(listener).installOn(inst);
}
public static void main(String[] args) throws IOException {
premain(null, ByteBuddyAgent.install());
new Foo().methodA();
}
}
results
method A
method B
intercepting methodB
intercepting methodA
You can of course just try it, but what will happen is that the internal call will again be intercepted. Methods do not know who is calling them. To avoid this, you can discover the caller via a StackWalker or by generating a stack trace using an exception.
This is a question about abstraction.
I want to be able to use two completely different GUIs for my application. They are completely different but implements the same interface.
My question is, what will the constructor look like? What type of object goes in the signature?
They do not extend a common parent, so I can't use polymorphism.
controller object wants to be injected with an object which implements Displayable interface.
interface Displayable {
void display();
}
class Display1 implements Displayable {
public void display() {
//Shows something Fancy on the screen
}
}
class Display2 implements Displayable {
public void display() {
//write something to console
}
}
class Main {
public static void main(String[] args) {
// Controller controller = new Controller(new Display1());
Controller controller = new Controller(new Display2());
controller.display();
}
}
class Controller {
????? display;
public Controller(?????? display) {
this.display = display;
}
public void display() {
display.display();
}
}
Can anyone please resolve the issue in the below post.
Selenium Framework Page Object Model and Page Navigation
I am not able to resolve the null pointer exception issue when a page returns an object of other page. Can anyone please tell what is the exact way of doing it. As explained in the above link, it's not clear how the error is resolved.
I will try illustrating PageFactory example using 3 different classes types.
Base Class- Has configuration setting like driver declaration
POM Class- Contains the POM objects for a single page
Test Class-Class containing test steps
BaseClass Example
public class BaseClass {
public WebDriver driver=null;
public BaseClass() throws MalformedURLException {
driver=new firefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseURL);
}
POM Class example
//Class1
public class WebshopHomePage {
WebDriver driver;
public WebshopHomePage(WebDriver driver){
this.driver=driver;
}
#FindBy(how=How.LINK_TEXT,using="Log in")//Identifying page elements
WebElement loginLink;
public void clickLoginLink(){
loginLink.click();
}
}
//Class2
public class SignInSignUpPage {
WebDriver driver;
public SignInSignUpPage(WebDriver driver){
this.driver=driver;
}
#FindBy(how=How.ID,using="Email")
WebElement emailID;
}
TestClass Example
public class WebShopSignInTest extends BaseClass {
#Test
public void testSteps() {
System.out.println("I'm in teststeps!!");
WebshopHomePage wshpObj=PageFactory.initElements(driver,WebshopHomePage.class);//Assigning POM class1 objects to driver
wshpObj.clickLoginLink();
SignInSignUpPage signInSignUpPageObj=PageFactory.initElements(driver, SignInSignUpPage.class);//Assigning POM class2 objects to driver
signInSignUpPageObj.enterCredsSubmit(userID, passw0rd);
}
package org.pom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class GoogleHomePageObjects
{
public GoogleHomePageObjects(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
#FindBy(name="q")
public WebElement txtSearch;
#FindBy(name="btnG")
public WebElement btnSearch;
#FindBy(linkText="Selenium - Web Browser Automation")
public WebElement lnkSelenium;
public void searchGoogle(String SearchText)
{
txtSearch.sendKeys(SearchText);
btnSearch.click();
}
public SeleniumPageObjects clickSelenium()
{
lnkSelenium.click();
return new SeleniumPageObjects(driver); //Here is the issue and i am getting error
}
}
//test class 2
package org.pom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class SeleniumPageObjects{
public SeleniumPageObjects(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
#FindBy(linkText="Download")
public WebElement lnkDownload;
#FindBy(xpath=".//*[#id='header']/h1/a")
public WebElement lnkHome;
public void clickDownloads()
{
lnkDownload.click();//Here it throws null pointer excception
}
public void clickHome()
{
lnkHome.click();
}
}
Below is my main class:
package org.pom;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class GoogleSearchTest
{
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.gecko.driver","D:\\Desktop\\Selenium\\Jars\\geckodriver-v0.11.1-win64\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.get("http://www.google.com");
GoogleHomePageObjects page=new GoogleHomePageObjects(driver);
page.searchGoogle("Selenium");
Thread.sleep(4000);
SeleniumPageObjects selPage=page.clickSelenium();
Thread.sleep(4000);
selPage.clickDownloads();
Thread.sleep(4000);
selPage.clickHome();
}
}
In the below example, We have created a Login class , Home class, and a Test class ...
It is not necessary to create one class for one page may be you can group the functionality or modules based on your convenience...
Summary:-
Created Login Class with all the required objects...and the loginas method should return the homepage class.....
public class LoginPage {
private final WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver;
// Check that we're on the right page.
if (!"Login".equals(driver.getTitle())) {
// Alternatively, we could navigate to the login page, perhaps logging out first
throw new IllegalStateException("This is not the login page");
}
}
// The login page contains several HTML elements that will be represented as WebElements.
// The locators for these elements should only be defined once.
By usernameLocator = By.id("username");
By passwordLocator = By.id("passwd");
By loginButtonLocator = By.id("login");
public LoginPage typeUsername(String username) {
driver.findElement(usernameLocator).sendKeys(username);
// Return the current page object as this action doesn't navigate to a page represented by another PageObject
return this;
}
public LoginPage typePassword(String password) {
driver.findElement(passwordLocator).sendKeys(password);
// Return the current page object as this action doesn't navigate to a page represented by another PageObject
return this;
}
public HomePage submitLogin() {
// This is the only place that submits the login form and expects the destination to be the home page.
// A seperate method should be created for the instance of clicking login whilst expecting a login failure.
driver.findElement(loginButtonLocator).submit();
// Return a new page object representing the destination. Should the login page ever
// go somewhere else (for example, a legal disclaimer) then changing the method signature
// for this method will mean that all tests that rely on this behaviour won't compile.
return new HomePage(driver);
}
// Conceptually, the login page offers the user the service of being able to "log into"
// the application using a user name and password.
public HomePage loginAs(String username, String password) {
// The PageObject methods that enter username, password & submit login have already defined and should not be repeated here.
typeUsername(username);
typePassword(password);
return submitLogin();
}
}
2. Created Homepage class , I have added only a sample verification method here , may be you can add methods as per your application needs...
class HomePage {
private final WebDriver driver;
public HomePage(WebDriver driver) {
this.driver = driver;
// Check that we're on the right page.
if (!"HOME".equals(driver.getTitle())) {
// Alternatively, we could navigate to the login page, perhaps
// logging out first
throw new IllegalStateException("This is not the home page");
}
}
// below method is just a sample method
public HomePage verifyRecords() {
/// your homepage validation
return null;
}
}
Now we are going to see how to put the above class together and make it work as per your requirement...
class Test {
public static void main(String[] args) {
LoginPage login = new LoginPage(new FirefoxDriver());
// login and verify records in home page
login.loginAs("myname", "pass##").verifyRecords();
}
}
In this line login.loginAs("", "").verifyRecords(); we are calling a method from login class and the method that is being called would return HomePage class....
You can create any no of pom classes and return it like the above......Like create some thing like dashboard and return it from homepage class
How returning page works :-
login.loginAs("myname", "pass##").verifyRecords();
In the above code once this login.loginAs("myname", "pass##") snippet executes , it will complete the login action and returns this method submitLogin(); which in turns returns new HomePage......
Here once execution of login.loginAs("myname", "pass##") is done it will become new Homepageobject..... Javacompiler is smart enough to manipulate that and provides the Homepageobject's methods once you put a dot after login.loginAs("myname", "pass##").
I am trying to make a simple addition to my plugin so that when someone joins they receive a message that says "Heyyyyyyy". My plugin has a few commands also.
Here's my Main class:
package me.ben.test;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin implements Listener {
#Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(new Click(), this);
getLogger().info("The Plugin Has Been Enabled!");
}
#Override
public void onDisable() {
getLogger().info("The Plugin Has Been Disabled!");
}
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
if (cmd.getName().equalsIgnoreCase("hello") && sender instanceof Player) {
Player player = (Player) sender;
player.sendMessage("Hello, " + player.getName() + "!");
return true;
} else if (cmd.getName().equalsIgnoreCase("isonline")
&& args.length == 1) {
Player target = Bukkit.getServer().getPlayer(args[0]);
if (target == null) {
sender.sendMessage(ChatColor.AQUA + "Player " + args[0]
+ " is not online.");
return true;
} else if (target != null) {
sender.sendMessage(ChatColor.AQUA + "Player " + args[0]
+ " is online.");
return true;
} else {
return false;
}
}
return false;
}
}
and here is my Click class:
package me.ben.test;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class Click extends JavaPlugin implements Listener {
#EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
event.getPlayer().sendMessage("Heyyyyyyy");
}
}
All of the #EventHandler things are not working so I quick made this simple one.
You can have only one class that extends JavaPlugin. Remove extends JavaPlugin from your Click Class - only your main class should extend JavaPlugin.
Check out Bukkit's official plugin tutorial for help on coding Bukkit Plugins.
You are using Listener in your Main class but you are not handling any event there, use it only when you want the class to be able to handler bukkit events.
You can use Listener with your Main class if you want, but you'll need to put the methods that handles events in your main class, but it'll become messy in big projects...
You also don't need to extend JavaPlugin everywhere, just in your main class.
If you want to use your main class:
public class Main extends JavaPlugin implements Listener {
#Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(this, this);
getLogger().info("The Plugin Has Been Enabled!");
}
#EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
event.getPlayer().sendMessage("Heyyyyyyy");
}
}
If you want to use a separated class to handle events:
public class Main extends JavaPlugin {
#Override
public void onEnable() {
this.getServer().getPluginManager().registerEvents(new Click(), this);
getLogger().info("The Plugin Has Been Enabled!");
}
}
public class Click implements Listener {
#EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
event.getPlayer().sendMessage("Heyyyyyyy");
}
}
Don't forget that you need to create a plugin.yml file correctly otherwise nothing will work.
I am Making a Simple App using JavaFX UI, The app simply just do that:
has a systray icon, which when clicked shows a window, when clicked again hides it, on rightclick shows a menu with 1 "exit" item
I already Made the UI and put the App in the Sys Tray, but i can't show/hide it using Normal Actionlistener method, but i got this error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Not on FX application thread; currentThread = AWT-EventQueue-0
here is the Code:
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionListener;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application{
public static void main(String[] args) {
launch(args);
}
#Override
public void start(final Stage primaryStage) {
primaryStage.setTitle("Hello World!");
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello World!"); }
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage("Germany-politcal-map.jpg");
PopupMenu popup = new PopupMenu();
MenuItem item = new MenuItem("Exit");
popup.add(item);
TrayIcon trayIcon = new TrayIcon(image, "Amr_Trial", popup);
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
};
ActionListener listenerTray = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent arg0) {
// TODO Auto-generated method stub
primaryStage.hide();
}
};
trayIcon.addActionListener(listenerTray);
item.addActionListener(listener);
try{
tray.add(trayIcon);
}catch (Exception e) {
System.err.println("Can't add to tray");
}
} else {
System.err.println("Tray unavailable");
}
//
}
}
Wrap the code in the actionListener which calls back to JavaFX in Platform.runLater. This will execute the code which interfaces with the JavaFX system on the JavaFX application thread rather than trying to do it on the Swing event thread (which is what is causing you issues).
For example:
ActionListener listenerTray = new ActionListener() {
#Override public void actionPerformed(java.awt.event.ActionEvent event) {
Platform.runLater(new Runnable() {
#Override public void run() {
primaryStage.hide();
}
});
}
};
By default the application will shutdown when it's last window is hidden. To override this default behaviour, invoke Platform.setImplicitExit(false) before you show the first application Stage. You will then need to explicitly call Platform.exit() when you need the application to really shutdown.
I created a demo for using the AWT system tray within a JavaFX application.
You should only modify the javafx classes on the javafx thread, the listeners on the tray icon are likely to be running on the swing thread. You can do this by posting a runnable to Platform#runLater like so:
Platform.runLater(new Runnable() {
public void run() {
primaryStage.hide();
}
});
The system tray is not supported in JavaFX yet. You could track the progress on this task under the following JIRA issue: https://bugs.openjdk.java.net/browse/JDK-8090475
The issue also provides a workaround, which could be used in JavaFX 8 to get the basic support.
The feature is not planned for JavaFX 8, so it might be released in one of the following updates or even in JavaFX 9.
Shameless self-plug, but I developed a small wrapper library for JavaFX icons that use the SystemTray called FXTrayIcon.
It abstracts away all of the nasty AWT bits and eliminates having to guess which thread you should be running code on. It's available as a dependency on Maven Central.
I resolved your issue. JavaFX with AWT. I have one example of a application that shows and hides when you make left clic. i really hope works for you
import java.awt.AWTException;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class MainApp2 extends Application {
int stateWindow = 1;
#Override
public void start(final Stage stage) throws Exception {
//Check the SystemTray is supported
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
URL url = System.class.getResource("/image/yourImage.png");
Image image = Toolkit.getDefaultToolkit().getImage(url);
//image dimensions must be 16x16 on windows, works for me
final TrayIcon trayIcon = new TrayIcon(image, "application name");
final SystemTray tray = SystemTray.getSystemTray();
//Listener left clic XD
trayIcon.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent event) {
if (event.getButton() == MouseEvent.BUTTON1) {
Platform.runLater(new Runnable() {
#Override
public void run() {
if (stateWindow == 1) {
stage.hide();
stateWindow = 0;
} else if (stateWindow == 0) {
stage.show();
stateWindow = 1;
}
}
});
}
}
});
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
}
stage.setTitle("Hello man!");
Button btn = new Button();
btn.setText("Say 'Hello man'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Hello man!");
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
stage.setScene(new Scene(root, 300, 250));
Platform.setImplicitExit(false);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}