Selenium grid is not working on latest selenium version - selenium

After upgrading to latest selenium, Selenium grid is giving an error for RegistrationRequest(). I am getting req.setRole(), req.setConfiguration(), etc. not found. look like RegistrationRequest() class got change in selenium new version but not sure how to use that class and modify my existing code. Any idea how to resolve this?
Here is my code,
package selenium;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openqa.grid.common.GridRole;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.internal.utils.configuration.GridHubConfiguration;
import org.openqa.grid.internal.utils.SelfRegisteringRemote;
import org.openqa.grid.web.Hub;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SeleniumGrid {
private static Hub hub;
private static URL remoteURL;
private static RegistrationRequest req = new RegistrationRequest();
private Map<String, Object> nodeConfig = new HashMap<String, Object>();
private static SelfRegisteringRemote remote = new SelfRegisteringRemote(req);
SeleniumBase sb = new SeleniumBase();
public void setup() throws Exception {
hub = getHub("localhost", 4458);
remoteURL = new URL("http://" + hub.getUrl() + ":" + 5555);
// req = setRegRequest();
req.setRole(GridRole.NODE);
req.addDesiredCapability(sb.getCapability());
List<DesiredCapabilities> dc = req.getCapabilities();
for (DesiredCapabilities c : dc) {
System.out.println("Using capabilities: " + c.toString());
}
// nodeConfig.put(req.AUTO_REGISTER, true);
nodeConfig.put(req.HUB_HOST, hub.getHost());
nodeConfig.put(req.HUB_PORT, hub.getPort());
nodeConfig.put(req.PORT, 5555);
// nodeConfig.put(RegistrationRequest.PROXY_CLASS, "org.openqa.grid.selenium.proxy.DefaultRemoteProxy");
nodeConfig.put(req.MAX_SESSION, 1);
// nodeConfig.put(RegistrationRequest.CLEAN_UP_CYCLE, 2000);
nodeConfig.put(req.REMOTE_HOST, remoteURL);
nodeConfig.put(req.MAX_INSTANCES, 1);
nodeConfig.put(req.BROWSER, "firefox");
nodeConfig.put(req.UNREGISTER_IF_STILL_DOWN_AFTER, 20000);
nodeConfig.put(req.HOST, hub.getHost());
System.out.println("Hub Port: " + hub.getHost() + hub.getPort());
System.out.println(req.HOST);
System.out.println(req.HUB_HOST);
System.out.println(req.HUB_PORT);
req.setConfiguration(nodeConfig);
remote.startRemoteServer();
remote.startRegistrationProcess();
}
public RegistrationRequest setRegRequest() {
RegistrationRequest request = new RegistrationRequest();
request.setRole(GridRole.NODE);
request.addDesiredCapability(sb.getCapability());
List<DesiredCapabilities> dc = request.getCapabilities();
for (DesiredCapabilities c : dc) {
System.out.println("Using capabilities: " + c.toString());
}
return request;
}
public Hub getHub(String host, int port) {
GridHubConfiguration config = new GridHubConfiguration();
config.setHost(host);
config.setPort(port);
Hub someHub = new Hub(config);
return someHub;
}
public void tearDown() throws Exception {
remote.stopRemoteServer();
hub.stop();
}
}

Here's a full fledged working example that starts a hub, starts a node, wires up the node to the hub, runs a test against the locally spun off hub, and then goes on to shut down the node and then the hub.
import org.openqa.grid.common.GridRole;
import org.openqa.grid.internal.utils.SelfRegisteringRemote;
import org.openqa.grid.internal.utils.configuration.GridHubConfiguration;
import org.openqa.grid.internal.utils.configuration.GridNodeConfiguration;
import org.openqa.grid.selenium.proxy.DefaultRemoteProxy;
import org.openqa.grid.web.Hub;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.server.SeleniumServer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
public class SeleniumGrid {
private Hub hub;
private SelfRegisteringRemote remote;
#BeforeClass
public void setup() throws Exception {
hub = getHub("localhost", 4458);
hub.start();
remote = new SelfRegisteringRemote(getNodeConfiguration());
remote.addBrowser(DesiredCapabilities.firefox(), 2);
SeleniumServer server = new SeleniumServer(remote.getConfiguration());
remote.setRemoteServer(server);
remote.startRemoteServer();
remote.startRegistrationProcess();
}
#Test
public void test() throws MalformedURLException {
URL url = new URL(hub.getUrl() + "/wd/hub");
RemoteWebDriver driver = new RemoteWebDriver(url, DesiredCapabilities.firefox());
try {
driver.get("http://www.google.com");
System.err.println("Title " + driver.getTitle());
} finally {
driver.quit();
}
}
#AfterClass
public void tearDown() throws Exception {
remote.stopRemoteServer();
hub.stop();
}
private GridNodeConfiguration getNodeConfiguration() {
GridNodeConfiguration nodeConfiguration = new GridNodeConfiguration();
nodeConfiguration.register = true;
nodeConfiguration.hub = String.format("http://%s:%d", hub.getConfiguration().host, hub.getConfiguration().port);
nodeConfiguration.port = 5555;
nodeConfiguration.proxy = DefaultRemoteProxy.class.getCanonicalName();
nodeConfiguration.maxSession = 1;
nodeConfiguration.cleanUpCycle = 2000;
nodeConfiguration.unregisterIfStillDownAfter = 20000;
nodeConfiguration.role = GridRole.NODE.toString();
nodeConfiguration.port = 5555;
nodeConfiguration.getHubHost();
nodeConfiguration.hub = String.format("http://%s:%d", hub.getConfiguration().host, hub.getConfiguration().port);
return nodeConfiguration;
}
private Hub getHub(String host, int port) {
GridHubConfiguration config = new GridHubConfiguration();
config.host = host;
config.port = port;
return new Hub(config);
}
}

Related

RedissonClient is throwing StringIndexOutOfBoundsException: begin 8, end 5, length 22

I have below code for Redis Configuration, i need to use RedissonClient to flush cache after regular intervals.Using timerTask to run flush code. CacheManager and Proxy Manager is used because it is connected to bucket4j Ratelimiting code.
Connection to Docker Redis Image is successful as well. Using redisson version 3.12.5.
Following this doc: https://www.freecodecamp.org/news/rate-limiting-with-bucket4j-and-redis/
import io.github.bucket4j.distributed.proxy.ProxyManager;
import io.github.bucket4j.grid.jcache.JCacheProxyManager;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
import lombok.extern.log4j.Log4j2;
import org.ehcache.jsr107.EhcacheCachingProvider;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.jcache.configuration.RedissonConfiguration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.utility.DockerImageName;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
#Log4j2
#Configuration
public class RedisConfig {
private static GenericContainer redis = null;
private RedissonClient redisson;
private final Timer timer = new Timer("RedisConfig", true);
private final CleanupRedis clean = new CleanupRedis(this);
public RedisConfig(){
timer.scheduleAtFixedRate(clean, SECONDS.toMillis(2), MINUTES.toMillis(2));
}
#Bean(name = "client")
public RedissonClient client() {
Config config = new Config();
if (redis == null) {
redis = new GenericContainer<>(redisImageName()).withExposedPorts(6379);
redis.start();
}
System.setProperty("spring.redis.host", redis.getHost());
System.setProperty("spring.redis.port", redis.getMappedPort(6379).toString());
config
.useSingleServer()
.setAddress("redis://" + redis.getHost() + redis.getMappedPort(6379));
RedissonClient rdson = Redisson.create(config);
return rdson;
}
#Bean
public CacheManager cacheManager(#Qualifier("client") RedissonClient redissonClient) {
Iterator<CachingProvider> iterator =
Caching.getCachingProviders(Caching.getDefaultClassLoader()).iterator();
while (iterator.hasNext()) {
CachingProvider provider = iterator.next();
if (!(provider instanceof EhcacheCachingProvider)) {
iterator.remove();
}
}
CacheManager manager = Caching.getCachingProvider().getCacheManager();
manager.createCache("cache", RedissonConfiguration.fromConfig(redissonClient.getConfig()));
return manager;
}
private static DockerImageName redisImageName() {
return DockerImageName.parse("docker.io/redis:5.0.3-alpine")
.asCompatibleSubstituteFor("redis:5.0.3-alpine");
}
#Bean
ProxyManager<String> proxyManager(CacheManager cacheManager) {
return new JCacheProxyManager<>(cacheManager.getCache("cache"));
}
protected class CleanupRedis extends TimerTask {
private RedisConfig redisConfig;
CleanupRedis(RedisConfig redisConfig) {
this.redisConfig = redisConfig;
}
#Override
public void run() {
try {
System.out.println("Redisson client call is being made");
RedissonClient redisson = Redisson.create(client().getConfig());
System.out.println("Redisson client is not working");
redisson.getKeys().flushdb();
log.debug("Successfully cleared the Redis Cache");
redisson.shutdown();
} catch (Exception e) {
log.debug("caught exception cleanup availability: {}", e.getMessage());
}
}
}
}

Unable To Launch Chrome Browser Because Driver Is Null

I am executing my code using shell scripting file and as per requirement if i will not pass parameter then my code will execute on my local machine and if i will pass parameter with shell scripting then code should be execute on browser stack. If i am executing with parameter then my code is working fine . But if i am not passing parameter in shell scripting then unable to launch chrome browser because in If condition driver is null. This is my base class
When i am executing shell script without parameter then my execution is going in If condition but unable to launch chrome browser because driver variable is not initialized in if condition . if i am printing driver value then it is showing null.
package com.epath.smoketest.tests;
/**
* Class: Base
* Author: D Albanese
* Creation Date: 4/5/2017
*/
import org.junit.Rule;
import org.junit.rules.ExternalResource;
import org.openqa.selenium.WebDriver;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Base {
//-Browser capability passed by CLI argument.
private static String sBrowser;
//-Browser version passed by CLI argument.
private static String sBversion;
//-OS capability passed by CLI argument.
private static String sOsName;
//-OS version capability passed by CLI argument.
private static String sOsVersion;
//-Passing input folder name by CLI argument.
public String sFolderName = "resources";
public static String getExecutionPath;
public static String getResourcePath;
public static WebDriver driver;
public Base(String sBrowser, String sBversion, String sOsName, String sOsVersion,String sFolderName) {
this.sBrowser = sBrowser;
this.sBversion = sBversion;
this.sOsName = sOsName;
this.sOsVersion = sOsVersion;
if(null != sFolderName && ! sFolderName.trim().equals("")) {
this.sFolderName = sFolderName;
}
}
//-Utilizing ExternalResource rule to preserve functionality of #Before and #After annotations in tests
//-ExternalResource rule has before and after methods that execute prior to methods annotated with #Before and #After
#Rule
public ExternalResource resource = new ExternalResource() {
#Override
protected void before() throws Throwable {
//-Use this for local testing
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browser", sBrowser);
caps.setCapability("browser_version", sBversion);
caps.setCapability("os", sOsName);
caps.setCapability("os_version", sOsVersion);
caps.setCapability("folder_name", sFolderName);
caps.setCapability("browserstack.local", "true");
if(sBrowser.length() == 0 && sBversion.length() == 0 && sOsName.length() == 0 && sOsVersion.length() == 0)
{
System.out.println("Inside If Condition ");
//-Load the properties
Properties prop = new Properties();
InputStream input = null;
input = new FileInputStream(System.getProperty("user.home") +
"/epath/services/tests/resources/AutomationData.properties");
prop.load(input);
// getResourcePath=prop.getProperty("resources_path");
getExecutionPath = prop.getProperty("local_resources_path");
System.out.println("Print Execution Path :- " +getExecutionPath);
System.out.println("Print Driver Path :- " + driver);
System.setProperty("webdriver.chrome", "\\\\192.168.10.21\\volume1\\ngage_dev\\engineering\\ngage\testing\\automated\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
} else {
//-Load the properties
System.out.println("Inside else Condtions ");
Properties prop = new Properties();
InputStream input = null;
input = new FileInputStream(System.getProperty("user.home") +
"/epath/services/tests/resources/AutomationData.properties");
prop.load(input);
getResourcePath=prop.getProperty("resources_path");
getExecutionPath = prop.getProperty("resources_path")+sFolderName;
//-Get USERNAME and AUTOMATE_KEY of browser stack
String browserStackUsername = prop.getProperty("browser_stack_username");
String browserStackAutomateKey = prop.getProperty("browser_stack_automate_key");
String URL = "https://" + browserStackUsername + ":" +
browserStackAutomateKey + "#hub-cloud.browserstack.com/wd/hub";
driver = new RemoteWebDriver(new URL(URL), caps);
//-Load the URL to be tested
driver.get(prop.getProperty("test_url"));
//-For local file uploads
((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
}
}
#Override
protected void after() {
driver.quit();
}
};
public String getAutomationInputDataPath() {
return this.getExecutionPath;
}
public static String getResourcePathFromPropertiesfile() {
return getResourcePath;
}
}
And this is my test case class where i am calling base class(above class)
public class AddRegisterLAs extends Base {
private Login login;
private Navigation go;
private LearningActivityAdd addLa;
private ImageAdd addImage;
private DocumentAdd addDocument;
private VideoAdd addVideo;
private AudioAdd addAudio;
private LinkAdd addLink;
private CustomAdd addCustom;
private AiccAdd addAicc;
private ScormAdd addScorm;
private RegistrationCreate createRegistration;
private Utils utils;
private GetVersion getVersion;
public AddRegisterLAs() {
super(System.getProperty("browser"),System.getProperty("browser_version"),System.getProperty("os"),System.getProperty("ov"),System.getProperty("folderName"));
}
#Before
public void setUp() {
login = new Login(driver);
go = new Navigation(driver);
addLa = new LearningActivityAdd(driver);
addImage = new ImageAdd(driver);
addDocument = new DocumentAdd(driver);
addVideo = new VideoAdd(driver);
addAudio = new AudioAdd(driver);
addLink = new LinkAdd(driver);
addCustom = new CustomAdd(driver);
addAicc = new AiccAdd(driver);
addScorm = new ScormAdd(driver);
utils = new Utils();
getVersion = new GetVersion(driver);
createRegistration = new RegistrationCreate(driver);
}
#Test
public void Shallow() throws Exception {
//utils.logAndPrint("AddRegisterLAs");
int maxLAs = 1000;
int maxRegs = 1000;
//-Print to screen to create log. Log can be copied and pasted to Word document or elsewhere as needed.
System.out.println("\n" + "---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("Adding and Registering Learning Activities Automation"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
//-Load the properties
System.out.println("\n" + "---------------------------------------------------------------------------------"+ "\r\n");
System.out.println("Read in PROPERTIES file"+ "\r\n");
System.out.println("---------------------------------------------------------------------------------"+ "\r\n");
Properties prop = new Properties();
InputStream input = null;
At first kindly check that you have access to that driver path which you mentioned inside if.

Use Drools 6.0 new PHREAK algorithm by using the 5.5. legacy API

Is it possible to try out the new PHREAKS algorithm but using the conventional API from Drools 5.5
* EDIT: to make the question more precise *
conventional 5.5 API
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.Resource;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
instead new Drools 6 API
import org.kie.api.KieBase;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieScanner;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.conf.ClockTypeOption;
It's also possible with the 5 knowledge api in drools 6.0+ by setting a rule engine property:
drools.ruleEngine = phreak
Here's how you set in the 5 knowledge api:
knowledgeBaseConfiguration.setProperty("drools.ruleEngine", "phreak");
I'm copy-pasting the simplest Java code for launching a 6.0 session. Everything else - fact insertion, global definitions,... works using the same API, only with KieSession.
package simple;
import java.io.FileInputStream;
import org.kie.api.KieServices;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Results;
import org.kie.api.builder.Message;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.KieContainer;
public class Main {
private KieSession kieSession;
public void build() throws Exception {
KieServices kieServices = KieServices.Factory.get();
KieFileSystem kfs = kieServices.newKieFileSystem();
FileInputStream fis = new FileInputStream( "simple/simple.drl" );
kfs.write( "src/main/resources/simple.drl",
kieServices.getResources().newInputStreamResource( fis ) );
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
System.out.println( results.getMessages() );
throw new IllegalStateException( "### errors ###" );
}
KieContainer kieContainer =
kieServices.newKieContainer( kieServices.getRepository().getDefaultReleaseId() );
KieBase kieBase = kieContainer.getKieBase();
kieSession = kieContainer.newKieSession();
}
public void exec(){
kieSession.fireAllRules();
}
public static void main( String[] args ) throws Exception {
Main m = new Main();
m.build();
m.exec();
}
}
Yes, most of the API is still supported. You will need to add the knowledge-api jar to your classpath (https://github.com/droolsjbpm/drools/tree/master/knowledge-api-legacy5-adapter).
The main difference is that Drools 6 no longer uses PKG for deployment. It uses mavenized kjars now. If you are not using PKG files (built by guvnor in Drools 5), you should be fine.
the working code to preserve rules and facts by using the same KieSession and deploy Jars, the code is adapted from here https://github.com/droolsjbpm/drools/blob/master/drools-compiler/src/test/java/org/drools/compiler/integrationtests/IncrementalCompilationTest.java.
package test.drools;
import java.io.UnsupportedEncodingException;
import org.drools.compiler.kie.builder.impl.InternalKieModule;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.builder.ReleaseId;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class Playground4 {
private String newline = System.getProperty("line.separator");
public static void main(String[] args) {
Playground4 pg = new Playground4();
try {
pg.doRules();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private String generateDRLString(int start, int end) {
StringBuilder sb;
sb = new StringBuilder();
sb.append("package performance.drools;" + newline);
for (int i = start; i <= end; i++) {
sb.append("rule \"R" + i + "\"" + newline);
sb.append("when" + newline);
sb.append("then" + newline);
sb.append("System.out.println(\"rule" + i + " fired!\");" + newline);
sb.append("end" + newline);
}
return sb.toString();
}
int count = 1;
public void doRules() throws UnsupportedEncodingException {
KieServices kieServices = KieServices.Factory.get();
KieBaseConfiguration kieBaseConf = kieServices.newKieBaseConfiguration();
//kieBaseConf.setProperty("drools.ruleEngine", "phreak");
kieBaseConf.setProperty("drools.ruleEngine", "phreak");
ReleaseId releaseId;
KieModule kieModule;
releaseId = kieServices.newReleaseId("performance.drools",
"test-upgrade", "1.$v.0".replace("$v", String.valueOf(count)));
// create session without rules for version 1.1.0
kieModule = createAndDeployJar(releaseId);
KieContainer kieContainer = kieServices.newKieContainer(kieModule
.getReleaseId());
kieContainer.newKieBase(kieBaseConf);
KieSession kieSession = kieContainer.newKieSession();
// Create an in-memory jar for version 1.2.0
count++;
releaseId = kieServices.newReleaseId("performance.drools",
"test-upgrade", "1.$v.0".replace("$v", String.valueOf(count)));
kieModule = createAndDeployJar(releaseId, generateDRLString(1, 3));
kieContainer.updateToVersion(releaseId);
kieSession.insert(new Object());
// Create an in-memory jar for version 1.3.0
count++;
releaseId = kieServices.newReleaseId("performance.drools",
"test-upgrade", "1.$v.0".replace("$v", String.valueOf(count)));
kieModule = createAndDeployJar(releaseId, generateDRLString(4, 12));
kieContainer.updateToVersion(releaseId);
kieSession.fireAllRules();
System.out.println(kieSession.getFactCount());
}
public KieModule createAndDeployJar(ReleaseId releaseId, String... drls) {
KieServices kieServices = KieServices.Factory.get();
byte[] jar = createKJar(kieServices, releaseId, null, drls);
return deployJar(kieServices, jar);
}
KieFileSystem kfs;
public byte[] createKJar(KieServices ks, ReleaseId releaseId,
String pom, String... drls) {
if (kfs == null) kfs = ks.newKieFileSystem();
if (pom != null) {
kfs.write("pom.xml", pom);
} else {
kfs.generateAndWritePomXML(releaseId);
}
for (int i = 0; i < drls.length; i++) {
if (drls[i] != null) {
kfs.write("src/main/resources/r" + 10 * count + i + ".drl", drls[i]);
}
}
KieBuilder kb = ks.newKieBuilder(kfs).buildAll();
if (kb.getResults()
.hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
for (org.kie.api.builder.Message result : kb.getResults()
.getMessages()) {
System.out.println(result.getText());
}
return null;
}
InternalKieModule kieModule = (InternalKieModule) ks.getRepository()
.getKieModule(releaseId);
byte[] jar = kieModule.getBytes();
return jar;
}
public KieModule deployJar(KieServices ks, byte[] jar) {
// Deploy jar into the repository
Resource jarRes = ks.getResources().newByteArrayResource(jar);
KieModule km = ks.getRepository().addKieModule(jarRes);
return km;
}
}

Use Selenium with same browser session

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
public class Test1 {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.ie.driver", "D:/Development/ProgrammingSoftware/Testing/IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
baseUrl = "http://seleniumhq.org/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test1() throws Exception {
driver.get(baseUrl + "/download/");
driver.findElement(By.linkText("Latest Releases")).click();
driver.findElement(By.linkText("All variants of the Selenium Server: stand-alone, jar with dependencies and sources.")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
I would like to have the IE with the same session but this code opens always a new instance of IE. How I get this work?
I don't think it is possible to attach driver to an existing session.
If You've done executing a test method and if you want to execute another test method which is present in another class or package, call the method by passing the present driver to it so that you can use the present instance of the driver over there.
This question has been asked several times in the past and the one I'm about to answer is not even close to recent. However I still gonna go ahead and post an answer because recently I've been engulfed with questions related to same browser session. How would I be able to leverage the browser which is already open, so I can continue my test run, rather than restart it from the scratch. It's even painstaking in some cases, after navigating through tons of pages, when you encounter the issue of restarting your Selenium test. Instead I was left wondering "where is the silver bullet?". Finally I saw one of the articles written by "http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/". However still there are a few missing links. So I wanted to unravel it here with the help of a suitable example.
In the following code snippet, I'm trying to launch SeleniumHQ and Clicking Download link in a Selenium session in Chrome browser.
System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
//First Session
ChromeDriver driver = new ChromeDriver();
HttpCommandExecutor executor = (HttpCommandExecutor)
driver.getCommandExecutor();
URL url = executor.getAddressOfRemoteServer();
SessionId session_id = driver.getSessionId();
storeSessionAttributesToFile("Id",session_id.toString());
storeSessionAttributesToFile("URL",url.toString());
driver.get("https://docs.seleniumhq.org/");
WebElement download = driver.findElementByLinkText("Download");
download.click();
If you read the above code, I'm capturing the URL of Selenium remote server and the session id of the current selenium (browser) session and writing it to a properties file.
Now if I need to continue executing in the same browser window/session, despite stopping the current test run, all I need to do is comment the code below the commented First session in the aforementioned code snippet and continuing your tests from the code below:
System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
//First Session
//ChromeDriver driver = new ChromeDriver();
//HttpCommandExecutor executor = (HttpCommandExecutor) driver.getCommandExecutor();
//URL url = executor.getAddressOfRemoteServer();
//SessionId session_id = driver.getSessionId();
//storeSessionAttributesToFile("Id",session_id.toString());
// storeSessionAttributesToFile("URL",url.toString());
// driver.get("https://docs.seleniumhq.org/");
// WebElement download = driver.findElementByLinkText("Download");
// download.click();
//Attaching to the session
String existingSession = readSessionId("Id");
String url1 = readSessionId("URL");
URL existingDriverURL = new URL(url1);
RemoteWebDriver attachToDriver = createDriverFromSession(existingSession, existingDriverURL);
WebElement previousReleases = attachToDriver.findElementByLinkText("Previous Releases");
previousReleases.click();
Now you may have to refactor and rename the driver object (even leaving the name would still work, but I just wanted to differentiate between attaching it to an existing driver and the launching the driver). In the above code block, I continue my tests, after reading and assigning the URL and sessionid and create the driver from session to continue leveraging the browser and session.
Please view the complete code below:
package org.openqa.selenium.example;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.Collections;
import java.util.Properties;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.SessionId;
import org.openqa.selenium.remote.http.W3CHttpCommandCodec;
import org.openqa.selenium.remote.http.W3CHttpResponseCodec;
public class AttachingToSession {
public static String SESSION_FILE = "C:\\example\\Session.Properties";
public static Properties prop = new Properties();
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
//First Session
ChromeDriver driver = new ChromeDriver();
HttpCommandExecutor executor = (HttpCommandExecutor) driver.getCommandExecutor();
URL url = executor.getAddressOfRemoteServer();
SessionId session_id = driver.getSessionId();
storeSessionAttributesToFile("Id",session_id.toString());
storeSessionAttributesToFile("URL",url.toString());
driver.get("https://docs.seleniumhq.org/");
WebElement download = driver.findElementByLinkText("Download");
download.click();
//Attaching to the session
String existingSession = readSessionId("Id");
String url1 = readSessionId("URL");
URL existingDriverURL = new URL(url1);
RemoteWebDriver attachToDriver = createDriverFromSession(existingSession, existingDriverURL);
WebElement previousReleases = attachToDriver.findElementByLinkText("Previous Releases");
previousReleases.click();
}
public static RemoteWebDriver createDriverFromSession(final String sessionId, URL command_executor){
CommandExecutor executor = new HttpCommandExecutor(command_executor) {
#Override
public Response execute(Command command) throws IOException {
Response response = null;
if (command.getName() == "newSession") {
response = new Response();
response.setSessionId(sessionId);
response.setStatus(0);
response.setValue(Collections.<String, String>emptyMap());
try {
Field commandCodec = null;
commandCodec = this.getClass().getSuperclass().getDeclaredField("commandCodec");
commandCodec.setAccessible(true);
commandCodec.set(this, new W3CHttpCommandCodec());
Field responseCodec = null;
responseCodec = this.getClass().getSuperclass().getDeclaredField("responseCodec");
responseCodec.setAccessible(true);
responseCodec.set(this, new W3CHttpResponseCodec());
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
response = super.execute(command);
}
return response;
}
};
return new RemoteWebDriver(executor, new DesiredCapabilities());
}
public static void storeSessionAttributesToFile(String key,String value) throws Exception{
OutputStream output = null;
try{
output = new FileOutputStream(SESSION_FILE);
//prop.load(output);
prop.setProperty(key, value);
prop.store(output, null);
}
catch(IOException e){
e.printStackTrace();
}
finally {
if(output !=null){
output.close();
}
}
}
public static String readSessionId(String ID) throws Exception{
Properties prop = new Properties();
InputStream input = null;
String SessionID = null;
try {
input = new FileInputStream(SESSION_FILE);
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty(ID));
SessionID = prop.getProperty(ID);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return SessionID;
}
}

Selenium tests for custom portlets

Can anyone provide me a link/document with information on how to write and test custom liferay portlets with Selenium.
I am using Liferay 6.1EE
Thanks
Same as with other tests, assuming you want to run as JUnit test
package org.ood.selenium.test;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.IncorrectnessListener;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptErrorListener;
import com.thoughtworks.selenium.SeleneseTestBase;
import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.regex.Pattern;
public class MyTest extends SeleneseTestBase {
WebDriver driver =null;
#Before
public void setUp() throws Exception {
DesiredCapabilities dc = DesiredCapabilities.firefox();
// dc.setCapability(FirefoxDriver.BINARY, new
//File("C:/Program Files (x86)/Mozilla Firefox/firefox.exe").getAbsolutePath());
dc.setJavascriptEnabled(true);
// driver= new HtmlUnitDriver(true);//Not properly working
driver = new FirefoxDriver(dc);
String baseUrl = "http://localhost:8080/web/guest/home";
selenium = new WebDriverBackedSelenium(driver, baseUrl);
}
/* #Test
public void homePage() throws Exception {
final WebClient webClient = new WebClient();
//HTMLUNit throws lots of errors
webClient.setJavaScriptEnabled(true);
webClient.setJavaScriptErrorListener(new JavaScriptErrorListener() {
public void timeoutError(HtmlPage htmlPage, long allowedTime,
long executionTime) {
// TODO Auto-generated method stub
}
public void scriptException(HtmlPage htmlPage,
ScriptException scriptException) {
System.out.println(scriptException.getMessage());
}
public void malformedScriptURL(HtmlPage htmlPage, String url,
MalformedURLException malformedURLException) {
System.out.println(url);
}
public void loadScriptError(HtmlPage htmlPage, URL scriptUrl,
Exception exception) {
// TODO Auto-generated method stub
}
});
//webClient.setThrowExceptionOnFailingStatusCode(false);
webClient.setThrowExceptionOnScriptError(false);
final HtmlPage page = webClient.getPage("http://localhost:8080/web/guest/home");
webClient.getCache().clear();
page.getElementById("sign-in").click();
page.getElementById("_58_login").type("test#liferay.com");
page.getElementById("_58_password").type("test#liferay.com");
final HtmlButton submit = (HtmlButton)page.getByXPath("//input").get(0);
submit.click();
//assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
System.out.println("Title= " +page.getTitleText());
final String pageAsXml = page.asXml();
// assertTrue(pageAsXml.contains("<body class=\"composite\">"));
System.out.println("pageAsXml=" +pageAsXml);
final String pageAsText = page.asText();
//assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"));
System.out.println("pageAsText="+pageAsText);
webClient.closeAllWindows();
}*/
#Test //Using Graphical GUI
public void testMytest() throws Exception {
//driver.get("http://localhost:8080/web/guest/home");
selenium.open("/");
//selenium.click("id=sign-in");
driver.findElement(By.id("sign-in")).click();
driver.findElement(By.name("_58_login")).clear();
driver.findElement(By.name("_58_login")).sendKeys("test#liferay.com");
driver.findElement(By.name("_58_password")).sendKeys("123");
//driver.findElement(By.name("_58_login")).sendKeys("test#nsn.com");
//driver.findElement(By.name("_58_password")).sendKeys("test");
driver.findElement(By.className("aui-button-input-submit")).submit();
//selenium.setSpeed("1000");
//selenium.waitForPageToLoad("5000");
//Select a nested div( the NodeTree)
driver.findElement(By.xpath("//div[contains(#class,'aui-tree-node-content')" +
" and (contains(.,'TreeNodeX'))]//div[contains(#class,'aui-tree-hitarea')]"))
.click();
//selenium.captureScreenshot("d:/_del/sel_screen.png");//this throws an error
//workaround
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("d:/_del/sel_screen.png"));
System.out.println("Bodytex=[" +selenium.getBodyText() +"]End Body Text");
String[] titles= selenium.getAllWindowTitles();
System.out.println("Titles Start-");
for (int i = 0; i < titles.length; i++) {
System.out.println(titles[i]);
}
System.out.println("Titles End");
verifyEquals(true, selenium.getBodyText().contains("Site View"));
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}