Junit in Eclipse can not deal with a LinkText apostrophe - eclipse

A testcase runs in Selenium IDE but when exported to WebDriver and executed in Eclipse the Junit script can not find a LinkText element with an apostrophe in the name.
I escaped the apostrophe but still Junit can not find it.
The line in question is highlighted in the code
I exported a Selenuim testcase that did not contain any apostrophes and I was able to run the WebDriver Junit test in Eclipse without any issues.
I will continue using the testcases without apostrophes but it would be great if I could figure out how to deal with special characters.
Sincerely,
Rick Doucette
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.support.ui.Select;
public class FirstSelIDEDemo {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.soastastore.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testFirstSelIDEDemo() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.linkText("Store")).click();
driver.findElement(By.linkText("Tron: Legacy")).click();
driver.findElement(By.id("product_155_submit_button")).click();
new Select(driver.findElement(By.name("product_rating"))).selectByVisibleText("2");
driver.findElement(By.id("s")).clear();
driver.findElement(By.id("s")).sendKeys("firth");
driver.findElement(By.id("searchsubmit")).click();
*****driver.findElement(By.linkText("The King\'s Speech")).click();*****
driver.findElement(By.name("product_rating")).click();
new Select(driver.findElement(By.name("product_rating"))).selectByVisibleText("4");
driver.findElement(By.cssSelector("form.wpsc_product_rating > input[type=\"submit \"]")).click();
driver.findElement(By.id("product_160_submit_button")).click();
new Select(driver.findElement(By.name("product_rating"))).selectByVisibleText("4");
driver.findElement(By.cssSelector("form.wpsc_product_rating > input[type=\"submit\"]")).click();
driver.findElement(By.id("product_160_submit_button")).click();
driver.findElement(By.linkText("Checkout")).click();
driver.findElement(By.cssSelector("form.adjustform.remove > input[name=\"submit\"]")).click();
driver.findElement(By.cssSelector("span > input[name=\"submit\"]")).click();
// Warning: assertTextPresent may require manual changes
assertTrue(driver.findElement(By.cssSelector("BODY")).getText().matches("^[\\s\\S]*ERROR: Please enter a username\\.[\\s\\S]*$"));
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}

You don't need to escape an apostrophe in Java source code, so you can lose the \. Is your generated HTML valid (it should have ' in the source, if it's in an attribute)? Perhaps it's not actually ' (code u+0027) but something else like u+2019 (http://www.fileformat.info/info/unicode/char/2019/index.htm)?

Related

Not running Beam job written on Java on Portable Flink runner

When I try to run the simplest PortableRunner pipeline on Java, I get the error:
Exception in thread "main" java.lang.RuntimeException: The Runner experienced the following error during execution:
java.io.IOException: error=2, No such file or directory
at org.apache.beam.runners.portability.JobServicePipelineResult.propagateErrors(JobServicePipelineResult.java:176)
at org.apache.beam.runners.portability.JobServicePipelineResult.waitUntilFinish(JobServicePipelineResult.java:117)
at org.apache.beam.examples.PythonExternal.runWordCount(PythonExternal.java:74)
at org.apache.beam.examples.PythonExternal.main(PythonExternal.java:81)
However, I do not read any files anywhere in the pipeline or I do not sink to anywhere. My arguments are
--runner=PortableRunner --jobEndpoint=localhost:8099
and code
package org.apache.beam.examples;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.options.*;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.values.Row;
import java.util.Arrays;
import java.util.List;
public class Simplest {
public static final Schema SCHEMA =
Schema.of(
Schema.Field.of("sentence", Schema.FieldType.STRING),
Schema.Field.of("count", Schema.FieldType.INT32));
public interface WordCountOptions extends PipelineOptions {
/** Set this option to specify Python expansion service URL. */
#Description("URL of Python expansion service")
String getExpansionService();
void setExpansionService(String value);
}
static void runWordCount(WordCountOptions options){
final List<String> LINES = Arrays.asList(
"To be, or not to be: that is the question: ",
"Whether 'tis nobler in the mind to suffer ",
"The slings and arrows of outrageous fortune, ",
"Or to take arms against a sea of troubles, ");
Pipeline p = Pipeline.create(options);
p.apply("ReadLines", Create.of(LINES)).setCoder(StringUtf8Coder.of())
.apply(ParDo
.of(new DoFn<String, Row>() {
#ProcessElement
public void processElement(#Element String element, OutputReceiver<Row> out, ProcessContext c) {
// In our DoFn, access the side input.
out.output(Row.withSchema(SCHEMA)
.withFieldValue("sentence", element)
.withFieldValue("count", 1)
.build());
}
}))
.setRowSchema(SCHEMA);
p.run().waitUntilFinish();
}
public static void main(String[] args) {
WordCountOptions options =
PipelineOptionsFactory.fromArgs(args).withValidation().as(WordCountOptions.class);
runWordCount(options);
}
}
Although the manual suggests adding --environment_type=LOOPBACK, I also get error as
Class interface org.apache.beam.examples.PythonExternal$WordCountOptions missing a property named 'environment_type'.
Beam Version: 2.40.0
I started the JobService endpoint docker run --net=host apache/beam_flink1.14_job_server:latest as suggested.
Any suggestions?

Selenium test wont launch Firefox (java with Netbeans)

I have Selenium IDE installed on Firefox, I ran a simple test on it and I exported the test cases to Netbeans under Java/JUNIT4/WebDriver. When I put the code in Netbeans and try to run it, It doesn't launch firefox. I've another simple program that will launch Firefox and go to google and search for cheese but when I try to export a test that I've ran using Selenium IDE, I can't get it to run. I'm not getting any errors and I get "successful build" when I run it, just nothing happens. Here's my code. Thanks
> Blockquotepackage firstpackage;
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.support.ui.Select;
public class FirstPackage {
private WebDriver driver;
private String baseUrl;
//private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private boolean acceptNextAlert;
public static void main(String args[]){}
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.get("http://google.com");
baseUrl = "https://www.google.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
// WebDriver driver = new FirefoxDriver();
System.out.println(driver.getTitle());
}
#Test
public void testGoogleSearch() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("Google");
driver.findElement(By.id("gbqfb")).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;
}
}
}
// TODO code application logic h
> Blockquote
This problem is likely due to incompatible versions of Firefox and Selenium Firefox WebDriver.
My guess is that your program that works (the one that goes to Google and searches for cheese) has a different version of Selenium in its path than the one that NetBeans ends up using for your imported tests from the IDE.
For more information on how to deal with the version compatibility issue, see my answer to this question.
I just ran your code on my machine and it worked as expected. Make sure you're using correct jar files and are correctly mapped in your project.

GWT Generator conflicts with GIN in production mode?

Could you please help me to solve my problem with GWT Generator? Let me explain.
I wish to generate a widget (ListBox with pre-defined values) during the compilation time and I use GWT Generator for that. My solution works as expected in DevMode (when I run the project with mvn gwt:run) and I see the generated listbox on the screen. But when I compile the code and run it in the "Production mode" (using command mvn clean gwt:compile jetty:run-war) I see the dumb listbox with only one item "no-value" instead.
I have one idea about the issue reason. I use GIN in my project. Despite the fact, that I substitute my empty listbox with generated one using Deferred Binding but not GIN Injection, it probably somehow prevents the substitution during the runtime. I tried my listbox on an empty testing project - everything worked as desired in both Dev Mode and Production Mode. But it fails on my working project.
Here is my realisation:
package com.test.generated;
import com.google.gwt.user.client.ui.IsWidget;
public interface IMySelectBox extends IsWidget {}
My empty selectbox:
package com.test.generated;
import com.google.gwt.user.client.ui.ListBox;
/**
* <p>Dumb listbox. It should be replaced with generated file.</p>
*
*/
public class MySelectBox implements IMySelectBox {
#Override
public ListBox asWidget() {
ListBox listBox = new ListBox();
listBox.addItem("no-value","no-value");
return listBox;
}
}
My Generator:
package com.test.generated;
import java.io.PrintWriter;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
/**
* Generates the ListBox and populates it
*
*/
public class SelectBoxGenerator extends Generator {
/**
* {#inheritDoc}
*/
#Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
try {
JClassType classType = context.getTypeOracle().getType(typeName);
return this.getSourceWriter(classType, context, logger);
} catch (NotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* Generates the source code of the List box.
*/
private String getSourceWriter(JClassType classType, GeneratorContext context, TreeLogger logger) {
final String packageName = classType.getPackage().getName();
final String className = classType.getSimpleSourceName() + "GeneratedImpl";
PrintWriter printWriter = context.tryCreate(logger, packageName, className);
if (printWriter == null) {
// source code has already been generated, abort
return null;
}
ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);
// Extends
composer.setSuperclass(classType.getName());
// Implements interface IMySelectBox
composer.addImplementedInterface(IMySelectBox.class.getSimpleName());
// Imports
composer.addImport(ListBox.class.getName());
// Class body
SourceWriter src = composer.createSourceWriter(context, printWriter);
src.println("#Override");
src.println("public ListBox asWidget() {");
src.println("ListBox sb = new ListBox();");
// ...here I generate values for the selectbox during compilation time.
src.println("return sb;");
src.println("}");
src.commit(logger);
System.out.println("Generating for: " + className);
// return the fully qualifed name of the generated class
return packageName + "." + className;
}
}
This is how I declare the substitution in my module.gwt.xml file:
<generate-with class="com.test.generated.SelectBoxGenerator">
<when-type-assignable class="com.test.generated.IMySelectBox" />
</generate-with>
And I use my generated ListBox as usually:
IMySelectBox mySelectBox = GWT.create(MySelectBox.class);
anyPanel.add(mySelectBox);
As you can see, I don't touch GIN stuff here at all. I use GIN to inject my modules and views. I found Issue 95 in GIN website, probably it is related to my case.
I will be really glad to get any help. Any explanations, hints, workarounds, suggestions are welcome!
Thank you very much in advance!

Error in Eclipse when compiling code but not when is validated

I have Eclipse Java EE IDE Helios Service Release 2 Build id: 20110218-0911; I am trying use them with SeleniumRC and when I compile the code appears the next error message:
Type mismatch: cannot convert from DataProviderSites to annotation
The attribute DataProviderSites is undefined for the annotation type Test
However, when I validate the code, is visualized "the validation completed with no errors or warnings"
The Code in DataProviderSites.java is:
package script;
import org.junit.Test;
import junit.framework.TestCase;
import com.thoughtworks.selenium.SeleneseTestBase;
import org.junit.AfterClass;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.*;
import java.io.File;
import jxl.*;
public class DataProviderSites extends SeleneseTestBase {
#BeforeClass
public void setUp() throws Exception {
SeleniumServer seleniumserver=new SeleniumServer();
seleniumserver.boot();
seleniumserver.start();
setUp("http://www.examinator.ws/", "*firefox");
selenium.open("/");
selenium.windowMaximize();
selenium.windowFocus();
}
#DataProviderSites
(name = "DPS1")
public Object[][] createData1() throws Exception{
Object[][] retObjArr=getTableArray("test\\Resources\\Data\\sitios.xls",
"DataPool", "TestData");
return(retObjArr);
}
#Test(DataProviderSites = "DPS1")
public void testDataProviderSites(String nombre) throws Exception {
selenium.type("sitio", nombre);
if (selenium.isTextPresent("examinator"))
selenium.click("xpath=/descendant::button[#type='submit']");
else
selenium.waitForPageToLoad("30000");
selenium.click("xpath=/descendant::a[text()='"+nombre+"']");
}
#AfterClass
public void tearDown(){
selenium.close();
selenium.stop();
}
public String[][] getTableArray(String xlFilePath, String sheetName, String tableName) throws Exception{
String[][] tabArray=null;
Workbook workbook = Workbook.getWorkbook(new File(xlFilePath));
Sheet sheet = workbook.getSheet(sheetName);
int startRow,startCol, endRow, endCol,ci,cj;
Cell tableStart=sheet.findCell(tableName);
startRow=tableStart.getRow();
startCol=tableStart.getColumn();
Cell tableEnd= sheet.findCell(tableName, startCol+1,startRow+1, 100, 64000, false);
endRow=tableEnd.getRow();
endCol=tableEnd.getColumn();
System.out.println("startRow="+startRow+", endRow="+endRow+", " +
"startCol="+startCol+", endCol="+endCol);
tabArray=new String[endRow-startRow-1][endCol-startCol-1];
ci=0;
for (int i=startRow+1;i<endRow;i++,ci++){
cj=0;
for (int j=startCol+1;j<endCol;j++,cj++){
tabArray[ci][cj]=sheet.getCell(j,i).getContents();
}
}
return(tabArray);
}
}
Anybody have a idea to resolve this?
Just click the error and click "Convert to TestNG(Annotations)".
Validation does not check the logic like it does not check for syntax of code.
But when we compile the program it will check for syntax so you got type cast exception.
Validation success does not mean program is correct.
I think annotations(#Test(DataProviderSites = "DPS1"), #DataProviderSites
(name = "DPS1")) causes the exception.

Reading xls file in gwt

I am looking to read xls file using the gwt RPC and when I am using the code which excecuted fine in normal file it is unable to load the file and giving me null pointer exception.
Following is the code
{
{
import com.arosys.readExcel.ReadXLSX;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.Preview.client.GWTReadXL;
import java.io.InputStream;
import com.arosys.customexception.FileNotFoundException;
import com.arosys.logger.LoggerFactory;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* #author Amandeep
*/
public class GWTReadXLImpl extends RemoteServiceServlet implements GWTReadXL
{
private String fileName;
private String[] Header=null;
private String[] RowData=null;
private int sheetindex;
private String sheetname;
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private static Logger logger=null;
public void loadXlsxFile() throws Exception
{
logger.info("inside loadxlsxfile:::"+fileName);
InputStream resourceAsStream =ClassLoader.getSystemClassLoader().getSystemResourceAsStream("c:\\test2.xlsx");
logger.info("resourceAsStream-"+resourceAsStream);
if(resourceAsStream==null)
throw new FileNotFoundException("unable to locate give file");
else
{
try
{
workbook = new XSSFWorkbook(resourceAsStream);
sheet = workbook.getSheetAt(sheetindex);
}
catch (Exception ex)
{
logger.error(ex.getMessage());
}
}
}// end loadxlsxFile
public String getNumberOfColumns() throws Exception
{
int NO_OF_Column=0; XSSFCell cell = null;
loadXlsxFile();
Iterator rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator cellIter = firstRow.cellIterator();
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
return NO_OF_Column+"";
}
}
}
I am calling it in client program by this code:
final AsyncCallback<String> callback1 = new AsyncCallback<String>() {
public void onSuccess(String result) {
RootPanel.get().add(new Label("In success"));
if(result==null)
{
RootPanel.get().add(new Label("result is null"));
}
RootPanel.get().add(new Label("result is"+result));
}
public void onFailure(Throwable caught) {
RootPanel.get().add(new Label("In Failure"+caught));
}
};
try{
getService().getNumberOfColumns(callback1);
}catch(Exception e){}
}
Pls tell me how can I resolve this issue as the code runs fine when run through the normal java file.
Why are using using the system classloader, rather than the normal one?
But, If you still want to use then look at this..
As you are using like a web application. In that case, you need to use the ClassLoader which is obtained as follows:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
This one has access to the all classpath paths tied to the webapplication in question and you're not anymore dependent on which parent classloader (a webapp has more than one!) has loaded your class.
Then, on this classloader, you need to just call getResourceAsStream() to get a classpath resource as stream, not the getSystemResourceAsStream() which is dependent on how the webapplication is started. You don't want to be dependent on that as well since you have no control over it at external hosting:
InputStream input = classLoader.getResourceAsStream("filename.extension");
The location of file should in your CLASSPATH.