trying to generate automated login java code - webclient

I have been trying to build a java program to perform automatic login to a web page but i am using the code below
import java.util.*;
import java.net.*;
import java.io.*;
import java.applet.*;
class main {
public static void main(String args[]) throws Exception{
final WebClient webClient = new WebClient();
// Fake page
final HtmlPage page1 = webClient.getPage("https://example/login.php");
// Get the form that we are dealing with and within that form,
// find the submit button and the field that we want to change.
final HtmlForm form = page1.getFormByName("login_form");
final HtmlSubmitInput button = form.getInputByName("Submit");
final HtmlTextInput username = form.getInputByName("username");
final HtmlTextInput psswd = form.getInputByName("password");
// Fake username and password
username.setValueAttribute("username");
psswd.setValueAttribute("password");
// Now submit the form by clicking the button and get back the second page.
final HtmlPage page2 = button.click();
}
}
but i had been getting the error WebClient not found, HTMLUnit not found.
Iam not using eclipse or any other kind similar to it. I am using Sublime text3 for writting the java code. Provide me with the correct import package to remove the errors. I had search the internet for this and had already downloaded HTMLUNIt packages from internet and put them in my enivronment path variable.

Related

Make jxBrowser open popups in the current window instead of "popping up"

How to set jxBrowser to open links that would pop-up in a new window to open on the calling page (or, at least, in a new tab)?
this is the call I think I have to override (it's the example):
//....
Engine engine = Engine.newInstance(
EngineOptions.newBuilder(
enderingMode.OFF_SCREEN ).enableIncognito().build()
Browser _browser = engine.newBrowser();
//this won't even compile
_browser.set(
OpenPopupCallback.class,
(params) -> {
// Access the created popup.
Browser popup = params.popupBrowser();
_browser.navigation().loadUrl(params.targetUrl());
return Response.proceed();
});
_browser.navigation().loadUrl("http://www.stackoverflow.com");
This is how I call it in my jfx but won't even compile, the code without this call works (opens a browser).
Update, given the nature of the popup I tried to rewrite javascript function (window.open) itself to force name to _parent.
This by running on every navigation the code
String the Javascript = "window.open = function (open) {return function (url, name, features{ console.log("open wrapper");return open.call(window, url, '_parent', features);};}(window.open);"
I thaught I couldn achieve this by
_browser.frames().get(0).executeJavaScript(theJavascript);
But in the remote console, I can't even see the log message ("open wrapper").
I double-checked the same code and it works if copy-pasted in the remote consolle.
What am I missing?
Here's complete JavaFX example that demonstrates how to open popup's URL in the main Browser instance and suppress popup:
import static com.teamdev.jxbrowser.engine.RenderingMode.OFF_SCREEN;
import com.teamdev.jxbrowser.browser.Browser;
import com.teamdev.jxbrowser.browser.callback.CreatePopupCallback;
import com.teamdev.jxbrowser.browser.callback.CreatePopupCallback.Response;
import com.teamdev.jxbrowser.engine.Engine;
import com.teamdev.jxbrowser.view.javafx.BrowserView;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public final class SmokeTest extends Application {
#Override
public void start(Stage primaryStage) {
// Creating and running Chromium engine.
Engine engine = Engine.newInstance(OFF_SCREEN);
Browser browser = engine.newBrowser();
browser.set(CreatePopupCallback.class, params -> {
browser.navigation().loadUrl(params.targetUrl());
return Response.suppress();
});
// Creating UI component for rendering web content
// loaded in the given Browser instance.
BrowserView view = BrowserView.newInstance(browser);
BorderPane root = new BorderPane(view);
Scene scene = new Scene(root, 1280, 900);
primaryStage.setTitle("Hello World");
primaryStage.setScene(scene);
primaryStage.show();
browser.navigation().loadUrl(
"https://www.encodedna.com/javascript/demo/open-new-window-using-javascript-method.htm");
// Close the engine when stage is about to close.
primaryStage.setOnCloseRequest(event -> engine.close());
}
}
Run this program and click a button that displays popup. You will see that popup is not displayed and its URL is loaded in the main Browser.

Create new NetBeans "save as" module

My goal is simple - save the current HTML file in the NetBeans editor with one additional line at the top and bottom of the file, and with the extension of ".h".
This is my first attempt at a NetBeans module, but following some tutorials and research, I got as far as adding an entry to the popup menu when you right-click on an HTML file in the editor. It currently just shows a "Hello World" message:
The code to do that is here:
package ksmiller99.savehtmlasarduinoresource;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
#ActionID(
category = "Edit",
id = "ksmiller99.savehtmlasarduinoresource.SaveHtmlAsArduinoResource"
)
#ActionRegistration(
displayName = "#CTL_SaveHtmlAsArduinoResource"
)
#ActionReference(path = "Editors/text/html/Popup")
#Messages("CTL_SaveHtmlAsArduinoResource=Save as Arduino Resource")
public final class SaveHtmlAsArduinoResource implements ActionListener {
#Override
public void actionPerformed(ActionEvent ev) {
//todo add a line to top and bottom of current file and save with .h extension
JOptionPane.showMessageDialog(null, "Hello Save As World");
}
}
How can I access the contents of the current editor? Would a different approach make more sense?
I'm using NetBeans 12.0, JDK 13, Windows 10.
Use the New Action wizard to create the source code for a Conditionally Enabled action, enabled when User Selects One Node.
In the 2nd wizard panel select File Type Context Menu and choose text/html as content type. If you want your action to appear only in the context menu you can disable Global Menu Item.
You should end up with code like this:
#ActionID(
category = "File",
id = "org.test.TestHtmlAction"
)
#ActionRegistration(
displayName = "#CTL_TestHtmlAction"
)
#ActionReference(path = "Loaders/text/html/Actions", position = 0)
#Messages("CTL_TestHtmlAction=TestHtmlAction")
public final class TestHtmlAction implements ActionListener
{
private final DataObject context;
private static final Logger LOGGER = Logger.getLogger(TestHtmlAction.class.getName());
public TestHtmlAction(DataObject context)
{
this.context = context;
}
#Override
public void actionPerformed(ActionEvent ev)
{
FileObject file = context.getPrimaryFile();
LOGGER.info("context=" + context.getName() + " file.getPath()=" + file.getPath());
}
}
The wizard creates a context aware action, which is enabled only when user selects a single HTML file node. The DataObject parameter gives you the context of the selected node, so you can retrieve the file path etc.

How to write selenium webdriver automation script for Facebook logout?

I tried this code. Its automating the browser, logging in successfully but I'm not able to logout successfully. Please Help.
public class fb {
public static void main(String args[])
{
WebDriver driver = new FirefoxDriver();
driver.get("https://facebook.com");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='email']")).sendKeys("your email");
driver.findElement(By.xpath(".//*[#id='pass']")).sendKeys("your password");
driver.findElement(By.xpath(".//*[#id='u_0_n']")).click();
driver.findElement(By.xpath(".//*[#id='userNavigationLabel']")).click();
driver.findElement(By.id("u_7_2")).click();// for logout-> button.But not working.
Automation Script for FaceBook Login and logout:
WebDriver driver = new FirefoxDriver();
driver.get("https://www.facebook.com/");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='email']")).sendKeys("your email");
driver.findElement(By.xpath(".//*[#id='pass']")).sendKeys("your password");
//click for login
driver.findElement(By.xpath("//label[#id='loginbutton']/input")).click();
//Mouse over on logOut drop down menu icon,then click logout
WebElement mouseOverEle = driver.findElement(By.id("pageLoginAnchor"));
Actions actions = new Actions(driver);
actions.moveToElement(mouseOverEle).click().perform();
//click for logout
driver.findElement(By.xpath("//input[#value='Log Out']")).click();
Try Using the below code to click on the log out button
//wait for the userNavigationLabel to load fully any wait techniques implicit or explicit for sample i have used Thread.sleep although it is not recommended
Thread.sleep(3000);
JavascriptExecutor js = (JavascriptExecutor) driver;
String script = "var forms = document.getElementsByTagName('form');for (var i = 0; i < forms.length; i++) { if(forms[i].getAttribute('action')=='https://www.facebook.com/logout.php'){forms[i].submit();}}";
js.executeScript(script);
In the above code i have used javascript to click on the logout button...i tested it on the browser console it is working fine
Hope this helps you.....Kindly get back if you have any queries
try:
lsb=browser.find_element_by_xpath('//*[#id="pageLoginAnchor"]')
lsb.click()
time.sleep(5)
mlb=browser.find_element_by_xpath('//*[#id="u_d_3"]/div/div/div[1]/div/div/ul/li[16]')
time.sleep(2)
mlb.click()
inputElement33 = browser.find_element_by_name('pass').is_displayed()
print("Looged out")
except:
print("Cannot logout")
// Enter you Email id
dr.findElement(By.xpath(".//*[#id='email']")).sendKeys("YorEmailID");
// Enter you Password
dr.findElement(By.xpath(".//*[#id='pass']")).sendKeys("YourPassword");
//click for login
dr.findElement(By.xpath("//label[#id='loginbutton']/input")).click();
dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// Click for Alert
dr.findElement(By.className("_3ixn")).click();
//Click for Navigation Label
dr.findElement(By.xpath(".//*[#id='userNavigationLabel']")).click();
dr.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Click for Lout Button
dr.findElement(By.xpath("//a[contains(#data-gt,'menu_logout')]")).click();
Replace your logout button click with this.
//Wait for button appear
WebDriverWait wait = new WebDriverWait(driver,TimeSpan.FromSeconds(4));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[.='Log out']")));
//Click it by xpath
driver.FindElement(By.XPath("//a[.='Log out']")).Click();
Or:
//Wait for button appear
WebDriverWait wait = new WebDriverWait(driver,TimeSpan.FromSeconds(4));
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[.='Log out']")));
//Click it by JS
IJavaScriptExecutor js = ((IJavaScriptExecutor)driver);
IWebElement logout = driver.FindElement(By.XPath("//a[.='Log out']"));
js.ExecuteScript("arguments[0].click();", logout);
100% worked
**#Working script**
**#firefox can be used too instead of chrome**
**#sleep is necessary to give sufficient loading time**
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import NoSuchElementException
usr=input('Enter Email Id:')
pwd=input('Enter Password:')
driver = webdriver.Chrome()
driver.get('https://www.facebook.com/')
a = driver.find_element_by_id('email')
a.send_keys(usr)
b = driver.find_element_by_id('pass')
b.send_keys(pwd)
c = driver.find_element_by_id('loginbutton')
c.click()
sleep(20)
d= driver.find_element_by_id("userNavigationLabel")
d.click()
sleep(10)
e=driver.find_element_by_xpath("//a[contains(#data-gt,'menu_logout')]")
e.click()
sleep(5)
driver.quit()
There are duplicate objects in the Home page.Hence, to avoid confusion,Xpath can be written in combination of class names, which in our case is,
//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li
Get the maximum number of <li> tags in the <ul> as follows ,
List<WebElement> li = driver.findElements(By.xpath("//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li"));
System.out.println("Size:"+li.size());
The Log out button will always be the last option, inspite of any changes to the list , hence append the last index to the xpath and click on it ,
String logOutBtn = "//div[#class='uiScrollableAreaBody']/following::div[#class='uiScrollableAreaContent']/following::ul/li[" + li.size() + "]";
driver.findElement(By.xpath(logOutBtn)).click(); -- Clicking on log out button
Hope this helps ! Thank you ..
package package1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class class1 {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\CloudLogic.Tech01\\Desktop\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver drr = new ChromeDriver();
drr.get("https://www.facebook.com/");
drr.findElement(By.id("email")).sendKeys("emailId");
drr.findElement(By.id("pass")).sendKeys("********");
drr.findElement(By.xpath("//label[#id='loginbutton']")).click();
}
}

Eclipse 4 RCP - how to remove Part from application model?

I have this utility method which allows easily to change what is shown in specific location of my application.
The problem is it looks more like that the new Part is on top of the old Part (the old Part is not removed and it is still visible under the new Part).
package cz.vutbr.fit.xhriba01.bc.ui;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.model.application.ui.basic.MPartSashContainer;
import org.eclipse.e4.ui.workbench.modeling.EModelService;
import org.eclipse.e4.ui.workbench.modeling.EPartService;
public class UI {
public static final String PART_INSPECTOR_ID = "bc.part.inspector";
public static void changeInspectorView(String partDescriptorId, EPartService partService, EModelService modelService) {
MPart part = partService.createPart(partDescriptorId);
MPart oldPart = partService.findPart(UI.PART_INSPECTOR_ID);
MPartSashContainer parent = (MPartSashContainer) modelService.getContainer(oldPart);
parent.getChildren().remove(oldPart);
part.setElementId(UI.PART_INSPECTOR_ID);
parent.getChildren().add(0, part);
}
}
You should use:
partService.hidePart(oldPart);
to hide the old part (also removes it from the children).
You might also just be able to do:
oldPart.setToBeRendered(false);
but I am not sure that does enough to update the Eclipse internal state.

problem writing HTMLUnit script for YUI form submit

I want to write a simple HTMLUnit test script for Jenkins (former Hudson). INFO: Jenkins uses the YUI Javascript library. The YUI library replaces the form submit with a custom button. The script just creates a new job in Jenkins.
start Jenkins:
java -jar jenkins.war
Current versions of HTMLUnit do not support form.submit any more and require you to use button.click() for form submitting. Unfortunately this does not work for Jenkins (the sample below does not advance the page and create the job but stays on the new job page)
I tried for some hours now to find a solution or workaround but so far I could not get the form submitted. Hopefully somebody has found a solution and let me know.
Here is my sample code:
package example;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
public class jenkins3 {
public static void main(String args[]) {
// create a new job in jenkins
// home
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_3_6);
try {
final HtmlPage page1 = webClient.getPage("http://localhost:8080");
//assertEquals("Dashboard [Jenkins]", page1.getTitleText());
// new job
final HtmlAnchor new_job = page1.getAnchorByText("New Job");
final HtmlPage page2 = new_job.click();
// job name
HtmlTextInput name_field = (HtmlTextInput) page2.getElementById("name");
name_field.type("new job by htmlunit");
// radio button
final HtmlInput radio_freestyle = (HtmlInput) page2.getByXPath("//input[#value='hudson.model.FreeStyleProject']").get(0);
radio_freestyle.click();
Thread.sleep(10000);
// OK button (submit form)
final HtmlForm form = page2.getFormByName("createItem");
//final HtmlSubmitInput button = (HtmlSubmitInput) form.getByXPath("//button").get(0);
final HtmlButton button = (HtmlButton) form.getByXPath("//button").get(0);
final HtmlPage page3 = button.click(); // !!!!! Form submit does not workstacko
//assertEquals("Dashboard [Jenkins]", page3.getTitleText());
}
catch( Exception e ) {
System.out.println( "General exception thrown:" + e.getMessage() );
e.printStackTrace();
}
webClient.closeAllWindows();
}
}
Although this may be completely out of the question in your senerio: i would suggest giving up on HTMLUnit. I've had bug after bug, mainly because of the pages I've been automating tests for aren't always 100% valid html (3rd party piggybacked requests). I finally went looking elsewhere and found PhantomJS (js bindings to the WebKit engine) much better suited.
For me the advantages were evident:
- no need for another app server
- much simpler and faster to script JS than Java
- a "real"-world engine is more realistic than a buggy emulator one
Thats my advice,
Cheers
HTMLUnit doesn't include support for testing javascript actions. You might not want to switch your testing framework at this point, but I would recommend using Selenium for this kind of testing. It runs a mock browser and executes javascript, making it possible to do this sort of thing.
I have found this little trick to work. Navigate to the Jenkins login page using HtmlUnit. Add a Submit button to the login form. Set appropriate attributes to Submit element, including an "onclick" value. Click on this new button and viola! You're logged in.
Note, if you're not concerned about security, you can also do this:
webClient.getPage("https://yourdomain:8443/jenkins/j_acegi_security_check?j_username=yourUsername&j_password=yourPassword");
See below for first method.
Enjoy,
Nick.
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class JenkinsLogin {
final String urlValue = "https://<yourdomain>:8443/jenkins";
private final String userName = "yourUsername";
private final String password = "yourPassword";
protected static final BrowserVersion BROWSER_VERSION_FIREFOX = new BrowserVersion(
"Netscape", "5.0 (Windows)",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0",
(float) 1.2);
private final WebClient webClient = new WebClient(BROWSER_VERSION_FIREFOX);
public static void main(final String[] args) throws Exception {
final JenkinsLogin jenkinsLogin = new JenkinsLogin();
jenkinsLogin.login();
}
private void login() throws Exception {
this.webClient.setThrowExceptionOnScriptError(false);
HtmlPage page = this.webClient.getPage(this.urlValue + "/login");
final HtmlForm form = page.getFormByName("login");
form.getInputByName("j_username").setValueAttribute(this.userName);
form.getInputByName("j_password").setValueAttribute(this.password);
final HtmlElement createdElement = page.createElement("input");
createdElement.setAttribute("type", "submit");
createdElement.setAttribute("name", "submitIt");
createdElement.setAttribute("onclick", "login.submit();");
form.appendChild(createdElement);
final HtmlElement submitButton = form.getInputByName("submitIt");
page = submitButton.click();
final HtmlElement loginField = page.getFirstByXPath("id('login-field')");
if (loginField == null || !loginField.getTextContent().contains(this.userName))
throw new RuntimeException("Unable to log on to Jenkins. ");
System.out.println("Logged in! ");
}
}
Does replacing
final HtmlButton button = (HtmlButton) form.getByXPath("//button").get(0);
final HtmlPage page3 = button.click()
with
form.submit((HtmlButton)last(form.getHtmlElementsByTagName("button")));
work?