Error in Eclipse when compiling code but not when is validated - eclipse

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.

Related

Error setting database config property for IDatabaseConnection (HSQLDB)

I've included fully testable code below, which generates the following error when supplied with a dataset xml containing empty fields. A sample dataset.xml is also below.
java.lang.IllegalArgumentException: table.column=places.CITY value is
empty but must contain a value (to disable this feature check, set
DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS to true)
The thread here is similar but is different since it uses multiple dbTester.getConnection() whereas my code only uses one, yet has the same error. The main problem relates to this line databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE); .
It seems to be ignored entirely. I've tried putting the init code inside the #Test method but the error remains.
dataset.xml
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<places address="123 Up Street" city="Chicago" id="001"/>
<places address="456 Down Street" city="" id="002"/>
<places address="789 Right Street" city="Boston" id="003"/>
</dataset>
Code:
import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.dbunit.operation.DatabaseOperation;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DBConnectionIT {
IDatabaseTester databaseTester = null;
IDatabaseConnection iConn = null;
Connection connection = null;
#Before
public void init() throws Exception {
databaseTester = new JdbcDatabaseTester(org.hsqldb.jdbcDriver.class.getName(), "jdbc:hsqldb:mem:testdb;sql.syntax_pgs=true", "sa", "");
iConn = databaseTester.getConnection();
DatabaseConfig databaseConfig = iConn.getConfig();
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE);
connection = iConn.getConnection();
createTable(connection);
IDataSet dataSet = new FlatXmlDataSetBuilder().build(new File("dataset.xml"));
databaseTester.setDataSet(dataSet);
databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
databaseTester.setTearDownOperation(DatabaseOperation.DELETE_ALL);
databaseTester.onSetup();
}
#Test
public void testDBUnit() {
try {
PreparedStatement pst = connection.prepareStatement("select * from places");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void createTable(Connection conn) throws Exception {
PreparedStatement pp = conn.prepareStatement(
"CREATE TABLE PLACES" +
"(address VARCHAR(255), " +
"city TEXT, " +
"id VARCHAR(255) NOT NULL primary key)");
pp.executeUpdate();
pp.close();
}
}
EDIT (based on César Rodríguez's answer):
I've now refactored out this method in the parent class:
protected void setUpDatabaseConfig(DatabaseConfig databaseConfig) {
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, Boolean.TRUE);
}
and created a sub-class which #Overrides this method, but it's saying this sub-class is not being used. How do I address this class (DBConnectionOverride) in the parent class, to solve my problem?
class DBConnectionOverride extends DBConnectionIT {
#Override
protected void setUpDatabaseConfig(DatabaseConfig databaseConfig) {
databaseConfig.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
}
}
I've stumbled upon the correct answer, at least the one which solves my problem. It related to this line all along databaseTester.onSetup() which could simply be replaced with DatabaseOperation.CLEAN_INSERT.execute(iConn, dataSet);. Feel free comment on why this seemed to have fixed the error.
You must override method setUpDatabaseConfig(DatabaseConfig config) as follows:
#Override
protected void setUpDatabaseConfig(DatabaseConfig config) {
config.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
}
Hope it helps
for me it's work:
IDatabaseConnection dbConn = new DatabaseDataSourceConnection(getDataSource());
dbConn.getConfig().setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
DatabaseOperation.CLEAN_INSERT.execute(dbConn, getiDataSet(loadDBData.source()));

i am trying to readfrom excel file, but i am getting error Xls_Reader cannot be resolved to a type, how to resolve it

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class multicheckbox {
public static void main(String[] args) {
WebDriver driver= new FirefoxDriver();
driver.get("http://www.jobserve.com/au/en/Job-Search/");
driver.findElement(By.xpath(".//*[#id='ddcl-selInd']/span/span")).click();
driver.findElement(By.xpath(".//*[#id='ddcl-selInd-ddw']/div/div[1]/label")).click();
int selection=9;
Xls_Reader ob1=new Xls_Reader("C:\\Users\\saurovs\\workspace\\New\\java\\firsttest.xlsx");// i am getting error on this line
String ob2= ob1.getCelldata("selenium","indexvalue",2);
String selections[]= ob2.split(",");
String xpath_start= ".//*[#id='ddcl-selInd-ddw']/div/div[";
String xpath_end="]/label";
for(int i=1; i<selections.length;i++)
driver.findElement(By.xpath(xpath_start + selections[i] + xpath_end)).click();
}}
i have added the full script please help me how to resolve it.
Xls_Reader cannot be resolved to a type
Xls_Reader cannot be resolved to a type

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.

Junit in Eclipse can not deal with a LinkText apostrophe

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 &apos; 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)?

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.