I use the below code to go to next page. It works as expected but after that the
browser freezes. Does not retrieve any data from the next webpage.
http://www.forbes.com/companies/icbc/
public void test() throws InterruptedException {
Thread.sleep(10000);
for(int i=1;i<3;i++)
{
WebElement tab=driver.findElement(By.className("large"));
Thread.sleep(1000);
String text= tab.getText();
System.out.println(text);
String industry=driver.findElement(By.xpath("//*[contains(text(),'Industry')]//following::dd[1]")).getText();
System.out.println(industry);
Workbook workbook;
try
{
workbook = Workbook.getWorkbook(new File("D:\\Dummy.xls"));
WritableWorkbook copy = Workbook.createWorkbook(new File("D:\\Dummy.xls"),workbook);
WritableSheet sheet=copy.getSheet(0);
Label lable = new Label(0,i,industry);
sheet.addCell(lable);
copy.write();
copy.close();
}
catch (Exception e)
{
e.printStackTrace();
}
//WebElement nextPage=driver.findElement(By.className("next-number"));
WebElement nextPage=driver.findElement(By.xpath("//span[contains(#class, 'next-number')]"));
nextPage.click();
I am getting the error :
NoSuchWindowEception: Unable find element on a closed window
I'm using IE to automate the process.
Related
I am trying to select "OK" button against my browser certificate pop-up using robot class. The same piece of code works well on windows but failing on ubuntu.
Code:
public void load() {
setUrl();
Thread threadNavigation = new Thread() {
#Override
public void run() {
driver.navigate().to(url);
}
};
Thread threadCertificateHandler = new Thread() {
#Override
public void run() {
try {
Thread.sleep(3000);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(2000);
robot.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Start the threads.
threadNavigation.start();
threadCertificateHandler.start();
// Wait for them both to finish
try {
threadNavigation.join();
threadCertificateHandler.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Code Explanation:
As soon as url is navigated using selenium, a certificate pop-up is displayed before page is loaded.
The approach I have used here - 1 thread used here to get application url and another thread is used to handle the pop-up.
Attaching screenshot of the pop-up.
Chromedriver Code:
public void getStandaloneHubNodeServerDriver(String browserType,String platformType, String url) throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
logger.log(Level.INFO, () -> "Setting browser address #: " + url);
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized"); // open Browser in maximized mode
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
options.setAcceptInsecureCerts(true);
options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.ACCEPT);
options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
//threadLocalDriver.set(new RemoteWebDriver(new URL(url),options));
driver = new RemoteWebDriver(new URL(url),options);
driver.manage().window().maximize();
}
Chrome Image Used:
docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-chrome:4.8.0-20230123
I am running into a strange null pointer exception when attempting to create a sheet using ApachePOI. I require a more modular code as this is part of a larger system. I have been unable to find any similar examples online, all examples are stored within a main method.
I am also wondering when it is necessary to include a workbook.write(outputStream) does this need to be in every method that a new sheet/workbook/row/cell is created or only when I am writing data to the sheets (like in the write method)?
public class ExcelWriter {
private XSSFWorkbook workbook;
private String outputFile;
private ArrayList<XSSFSheet> sheets;
private static int sheetCount;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Constructor --> initializes a workbook
public ExcelWriter(String outputFile) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
this.outputFile=outputFile;
sheets=new ArrayList<XSSFSheet>();
sheetCount=0;
FileOutputStream os = new FileOutputStream(outputFile);
workbook.write(os);
os.close();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Method to create a new sheet in the workbook, add to sheet list
public void newSheet(String sheetName) throws IOException {
sheets.add(workbook.createSheet(sheetName)); //ERROR HERE****
sheetCount++;
FileOutputStream os = new FileOutputStream(outputFile);
workbook.write(os);
os.close();
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//Method to write a cell into a worksheet given sheet row and column
public void write(int sheet,int row, int col, String data) {
XSSFSheet tempSheet=sheets.get(sheet);
System.out.println("yest");
// Specific row number
XSSFRow tempRow = tempSheet.createRow(row);
// Specific cell number
XSSFCell cell = tempRow.createCell(col);
// putting value at specific position
cell.setCellValue(data);
// writing the content to Workbook
OutputStream os;
try {
os = new FileOutputStream(outputFile);
workbook.write(os);
} catch (IOException e) {
e.printStackTrace();
}
}
I want to print the output into Excel sheet. My Excel fields be like Name, Phone, Address.
My code is as below:
public class Cpydata
{
WebDriver driver = new FirefoxDriver();
int i=0;
#Test
public enter code herevoid demo()
{
while(i<=1000)
{
driver.get("test.com");
driver.manage().window().maximize();
driver.findElement(By.xpath("xxx")).click();
System.out.println(driver.getTitle());
//System.out.println(Hos_name);
Object ph=driver.findElement(By.className("tel")).getText();
System.out.println(ph);
Object add=driver.findElement(By.className("jadlt")).getText();
System.out.println(add);
i++;
}
driver.quit();
}
}
I'm using Wicket (not sure if it matters) but I'm using Workbook to create an excel file for a user to download. But I'm not sure how exactly to do this. What I would like to happen is the user clicks the button, a log is created and a prompt is given to the user to open (and save to temp files) or to save to their computer. The file is then deleted from the server side, or maybe it is stored in the User's session and deleted at end of session.
Can someone point me in the right direction? If I can have the file not saved in the session at all, that'd be create and have it just have it sent to the client using FileOutputStream somehow..
here is my current code:
private void excelCreator()
{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("SSA User ID " + currentSSAIDSelection2.getSsaUserId()));
Iterator<AuditLogEntry> auditLogEntrys = logList.iterator();
int i = 0;
while (auditLogEntrys.hasNext())
{
final AuditLogEntry auditLogEntry = auditLogEntrys.next();
Row row = sheet.createRow(i);
row.createCell(0).setCellValue(auditLogEntry.getTimeStamp());
row.createCell(1).setCellValue(auditLogEntry.getSourceName());
row.createCell(2).setCellValue(auditLogEntry.getCategory());
row.createCell(3).setCellValue(auditLogEntry.getSsaAdmin());
row.createCell(4).setCellValue(auditLogEntry.getAction());
i++;
}
try
{
FileOutputStream output = new FileOutputStream("ssaUserIDAccess.xls");
workbook.write(output);
output.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
You would have to create a DownloadLink with the temporary file as input. The temporary File must be deleted after download (file.delete())).
Alternatively you can try this:
IResourceStream stream = new ByteArrayResourceStream(data, "application/vnd.ms-excel");
RequestCycle.get().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(stream, filename).setContentDisposition(ContentDisposition.ATTACHMENT));
In this case data is the byte[] content of your workbook which can be for example retrieved with output.toByteArray().
In case anyone runs into this problem here is my solution. There wasn't a lot of straight forward answers on this but this is my solution:
My excelCreator method handles the creation of the excel Sheet, and returns it as a file.
private File excelCreator()
{
Workbook workbook = new HSSFWorkbook();
File excelfile = new File("userIDAccess.xls");
logList = getServer().findAuditLogs(getUserId(), null);
Sheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("User ID " + getUserId()));
Iterator<AuditLogEntry> auditLogEntrys = logList.iterator();
int i = 0;
while (auditLogEntrys.hasNext())
{
final AuditLogEntry auditLogEntry = auditLogEntrys.next();
Row row = sheet.createRow(i);
row.createCell(0).setCellValue(auditLogEntry.getTimeStamp());
row.createCell(1).setCellValue(auditLogEntry.getSourceName());
row.createCell(2).setCellValue(auditLogEntry.getCategory());
row.createCell(3).setCellValue(auditLogEntry.getSsaAdmin());
row.createCell(4).setCellValue(auditLogEntry.getAction());
i++;
}
try
{
FileOutputStream output = new FileOutputStream(excelfile);
workbook.write(output);
output.close();
}catch(Exception e)
{
e.printStackTrace();
}
return excelfile;
}
IModel excelFileModel = new AbstractReadOnlyModel()
{
public Object getObject()
{
return excelCreator();
}
};
I created an IModel to capture the file created inside my excelCreator() method and returned.
auditDownloadlink = new DownloadLink("auditDownloadlink", excelFileModel);
I pass the I.D. of the download link, and then pass the imodel.
finally,
I call,
auditDownloadlink.setDeleteAfterDownload(true);
auditDownloadlink.setCacheDuration(Duration.NONE);
This deletes the file after it is created. And the cache setting is a setting to make sure it is compatible with all browsers (That's how I interpreted it, but you may not need it).
The Imodel creates the File on the fly so it doesn't have to be stored anywhere, and then the file is deleted once it is downloaded.
Hope this helps someone!
You could create a Resource to do this, and make a ResourceLink.
public class ExcelProducerResource extends AbstractResource
{
public ExcelProducerResource()
{
}
#Override
protected ResourceResponse newResourceResponse( Attributes attributes )
{
final String fileName = getFileName();
ResourceResponse resourceResponse = new ResourceResponse();
resourceResponse.setContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" );
resourceResponse.setCacheDuration( Duration.NONE );
resourceResponse.setFileName( fileName );
resourceResponse.setWriteCallback( new WriteCallback()
{
#Override
public void writeData( Attributes attributes ) throws IOException
{
OutputStream outputStream = attributes.getResponse().getOutputStream();
writeToStream( outputStream );
outputStream.close();
}
} );
return resourceResponse;
}
void writeToStream(OutputStream outputStream) throws IOException
{
//.. do stuff here :)
}
String getFileName()
{
//.. do stuff here :)
}
}
I am using LWUIT 1.5 tabs to show notifications. I have three Tabs and I fetch notifications from a php web service. I successfully fetched list of notifications for first Tab. But for next two Tabs I am failing to understand what code I should write to
Detect that second/third Tab is clicked. I know how to add commandListener to a Button. What commandListener is there for Tab selection?
How to refresh content of a Tab when new data is received from the server?
private void showNotificationList() {
try {
Form f = new Form("Notifications");
f.setScrollable(false);
f.setLayout(new BorderLayout());
final List list = new List(getNotifications()); //gets hashtables - notices
list.setRenderer(new GenericListCellRenderer(createGenericRendererContainer(), createGenericRendererContainer()));
list.setSmoothScrolling(true);
//System.out.println("adding list component to listview");
list.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int i = list.getSelectedIndex();
noticeDetailsForm(notices[i]);
//Dialog. show( "title", notices[i].toString(), "ok", "exitt");
}
});
//Container c2 = new Container(new BoxLayout(BoxLayout.Y_AXIS));
//c2.addComponent(list);
Tabs tabs = new Tabs(Tabs.TOP);
tabs.addTab("Recent", list);
tabs.addTab("Urgent", new Label("urgent goes here"));
tabs.addTab("Favourites", new Label("favs goes here"));
//f.addComponent(tabs);
f.addComponent(BorderLayout.CENTER, tabs);
Command backComm = new Command("Back") {
public void actionPerformed(ActionEvent ev) {
Dashboard.dbInstance.setUpDashboard();
}
};
f.addCommand(backComm);
//System.out.println("showing lsit form");
f.show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private Container createGenericRendererContainer() throws IOException { //System.out.println("container called");
//System.out.println("container called");
Container c = new Container(new BorderLayout());
c.setUIID("ListRenderer");
Label xname = new Label("");
Label description = new Label();
Label focus = new Label("");
Container cnt = new Container(new BoxLayout(BoxLayout.Y_AXIS));
xname.setName("Name");
xname.getStyle().setBgTransparency(0);
xname.getStyle().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM));
//description.setFocusable(true);
description.setName("Description");
cnt.addComponent(xname);
cnt.addComponent(description);
c.addComponent(BorderLayout.CENTER, cnt);
Button thumb = new Button(Image.createImage("/res/home-work.png"));
//Image img = Image.createImage("/res/home-work.png");
c.addComponent(BorderLayout.WEST, thumb);
return c;
}
private Hashtable[] getNotifications() {
int total = notices.length;
//System.out.println(total);
Hashtable[] data = new Hashtable[total];
//Hashtable[] data = new Hashtable[5];
/data[0] = new Hashtable();
data[0].put("Name", "Shai");
data[0].put("Surname", "Almog");
data[0].put("Selected", Boolean.TRUE);/
for (int i = 0; i < total; i++) {
data[i] = new Hashtable();
//System.out.println(notices[i].getName());
data[i].put("Name", notices[i].getName());
data[i].put("Description", notices[i].getDescription());
data[i].put("Id", Integer.toString(notices[i].getId()));
}
return data;
}
1)I had the same problem and I solved it by overriding Keyreleased of the Form not the Tab
and inside it I check for the component that is focused and if it is the Tab get "tab.selectedIndex" to detect in which Tab I am and load appropriate data .
Here is Sample code(this inside the my derived form that extends Form )
**
public void keyReleased(int keyCode) {
Component p=this.getFocused();
String str= p.getClass().getName();
if(str.toLowerCase().indexOf("radiobutton")!=-1){ // Radiobutton because when u
Here do tab specific work focus on the
tab it returns radiobutton.
lwuit understands tabs as list
of radiobuttons
}**
2)and about refreshing the data I did a solution and I don't Know if its right
I get the new data , create new List and remove the old one and attach the new one then
call Form.repaint();