I am unable to fetch excel data to selenium code At ubuntu o/s - excel

public class ReadAndWrite {
public static void main(String[] args) throws InterruptedException, BiffException, IOException
{
System.out.println("hello");
ReadAndWrite.login();
}
public static void login() throws BiffException, IOException, InterruptedException{
WebDriver driver=new FirefoxDriver();
driver.get("URL");
System.out.println("hello");
FileInputStream fi = new FileInputStream("/home/sagarpatra/Desktop/Xpath.ods");
System.out.println("hiiiiiii");
Workbook w = Workbook.getWorkbook(fi);
Sheet sh = w.getSheet(1);
//or w.getSheet(Sheetnumber)
//String variable1 = s.getCell(column, row).getContents();
for(int row=1; row <=sh.getRows();row++)
{
String username = sh.getCell(0, row).getContents();
System.out.println("Username "+username);
driver.get("URL");
driver.findElement(By.name("Email")).sendKeys(username);
String password= sh.getCell(1, row).getContents();
System.out.println("Password "+password);
driver.findElement(By.name("Passwd")).sendKeys(password);
Thread.sleep(10000);
driver.findElement(By.name("Login")).click();
System.out.println("Waiting for page to load fully...");
Thread.sleep(30000);
}
driver.quit();
}
}
I don't know what is wrong with my code, or how to fix it. It outputs the following error:
Exception in thread "main" jxl.read.biff.BiffException: Unable to recognize OLE stream
at jxl.read.biff.CompoundFile.<init>(CompoundFile.java:116)
at jxl.read.biff.File.<init>(File.java:127)
at jxl.Workbook.getWorkbook(Workbook.java:221)
at jxl.Workbook.getWorkbook(Workbook.java:198)
at test.ReadTest.main(ReadTest.java:19)

I would try using Apache MetaModel instead. I have had better luck with that, than using JXL. Here is a example project I wrote that reads from a .XLSX file. I use this library to run tests on a Linux Jenkins server from .XLS files generated on MS Windows.
Also, it should be noted that this library is also perfect for making a parameterized DataProvider that queries a database with JDBC.
Using JXL, you limit yourself to one data type, either .XLS or .CSV. I believe MetaModel is actually using JXL under the hood and wrapping it to make it easier to use. So, it also would support the OpenOffice documents in the same fashion and suffer the same file compatibility issues.

Related

I am trying to convert ppt into pdf using Apache POI but getting following error.Please help me out of this

Following code is used:
public static void main(String[] args) throws IOException {
FileInputStream is = new FileInputStream("C:/Users/hp/Downloads/sampPPT.ppt");
HSLFSlideShow ppt = new HSLFSlideShow(is);
is.close();
Dimension pgsize = ppt.getPageSize();
int idx = 1;
for (HSLFSlide slide : ppt.getSlides()) {
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
// clear the drawing area
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// render
slide.draw(graphics);
// save the output
FileOutputStream out = new FileOutputStream("C:/Users/hp/Downloads/slide-" + idx + ".png");
javax.imageio.ImageIO.write(img, "png", out);
out.close();
idx++;
}
}
This throws following exception:
Exception in thread "main" java.lang.IllegalAccessError: class org.apache.poi.hslf.usermodel.HSLFSlideShowImpl tried to access private field org.apache.poi.POIDocument.directory (org.apache.poi.hslf.usermodel.HSLFSlideShowImpl and org.apache.poi.POIDocument are in unnamed module of loader 'app')
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.readCurrentUserStream(HSLFSlideShowImpl.java:340)
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.<init>(HSLFSlideShowImpl.java:154)
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.<init>(HSLFSlideShowImpl.java:127)
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.<init>(HSLFSlideShowImpl.java:116)
at org.apache.poi.hslf.usermodel.HSLFSlideShow.<init>(HSLFSlideShow.java:138)
at PPTConv.PPTConv.main(PPTConv.java:27)
To make an answer why such exceptions occur. Maybe it is helpful for others too:
This kind of exception occur if you mix Apache POI jars from different versions. This is not supported. See FAQ.
In that special case there probably are poi-*.jar and poi-scratchpad-*.jar from different versions in classpath. The class org.apache.poi.hslf.usermodel.HSLFSlideShowImpl, which extends org.apache.poi.POIDocument, is contained in poi-scratchpad-*.jar while org.apache.poi.POIDocument is contained in poi-*.jar. If those *.jars are from different versions, then following can occur:
The org.apache.poi.hslf.usermodel.HSLFSlideShowImpl of poi-scratchpad-3.15.jar calls currentUser = new CurrentUserAtom(directory); in code line 340. This is possible because it extends org.apache.poi.POIDocument and this has field protected DirectoryNode directory; in version 3.15 (poi-3.15.jar).
But the same class org.apache.poi.POIDocument of version 3.16 (poi-3.16.jar) has field private DirectoryNode directory;. So if org.apache.poi.hslf.usermodel.HSLFSlideShowImpl of version 3.15 calls currentUser = new CurrentUserAtom(directory); in code line 340, but org.apache.poi.POIDocument is from version 3.16, then java.lang.IllegalAccessError: class org.apache.poi.hslf.usermodel.HSLFSlideShowImpl tried to access private field org.apache.poi.POIDocument.directory is thrown because it really tries to access a private field now.

NPOI Write Corrupts File - Bare Ampersands

Using NPOI 2.1.3.1, I am trying to read an existing Excel (*.xlsx) workbook, modify it, and then write it back to the original file. After reading various threads (including this one), I still cannot find a solution to the problem I'm having.
When I write the file to disk and then try to open it again in Excel, I get the following error:
We found a problem with some content in (filename. Do you want us to
try to recover as much as we can? If you trust the source of this
workbook, click Yes.
Clicking "Yes" fixes various problems in the Excel file, after which I see the following report of the fixes performed:
Replaced Part: /xl/worksheets/sheet3.xml part with XML error. Illegal
name character. Line 3, column 3891168.
Replaced Part: /xl/worksheets/sheet19.xml part with XML error. Illegal name
character. Line 1, column 699903.
Removed Records: Formula from /xl/calcChain.xml part (Calculation properties)
I unzipped the *.xlsx file and found the sheets mentioned and discovered that the character it was referring to is a bare ampersand (&) that was not written as "&" in the XML. The original does use "&", but the file NPOI wrote does not. I have no idea what the issue is with the formula (third issue).
Here is a complete program that reproduces this issue every single time with the workbook I'm using, with the file name removed:
using System.IO;
using NPOI.XSSF.UserModel;
namespace NpoiTest
{
public sealed class NpoiTest
{
public static void Main(string[] args)
{
XSSFWorkbook workbook;
using (FileStream file = new FileStream(#"C:\Path\To\File.xlsx", FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(file);
}
using (FileStream file = new FileStream(#"C:\Path\To\File.xlsx", FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
workbook.Write(file);
}
}
}
}
As a test, I wrote pretty much the same program using Apache POI, to see if it was just a universal problem with my workbook, and the result was that POI didn't have any problems.
Here is the complete program:
package poitest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class PoiTest
{
public static void main(String[] args)
{
XSSFWorkbook workbook;
try (FileInputStream file = new FileInputStream(new File("C:\\Path\\To\\File.xlsx")))
{
workbook = new XSSFWorkbook(file);
}
catch (IOException e)
{
System.out.println(e.getMessage());
return;
}
try (FileOutputStream out = new FileOutputStream(new File("C:\\Path\\To\\File.xlsx")))
{
workbook.write(out);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}
So the question is why is NPOI leaving the bare ampersands? Is this just a bug in NPOI?

dynamic template generation and formatting using freemarker

My goal is to format a collection of java map to a string (basically a csv) using free marker or anything else that would do smartly. I want to generate the template using a configuration data stored in database and managed from an admin application.
The configuration will tell me at what position a given data (key in hash map) need to go and also if any script need to run on this data before applying it at a given position. Several positions may be blank if the data in not in map.
I am thinking to use free-marker to build this generic tool and would appreciate if you could share how I should go about this.
Also would like to know if there is any built is support in spring-integration for building such process as the application is a SI application.
I am no freemarker expert, but a quick look at their quick start docs led me here...
public class FreemarkerTransformerPojo {
private final Configuration configuration;
private final Template template;
public FreemarkerTransformerPojo(String ftl) throws Exception {
this.configuration = new Configuration(Configuration.VERSION_2_3_23);
this.configuration.setDirectoryForTemplateLoading(new File("/"));
this.configuration.setDefaultEncoding("UTF-8");
this.template = this.configuration.getTemplate(ftl);
}
public String transform(Map<?, ?> map) throws Exception {
StringWriter writer = new StringWriter();
this.template.process(map, writer);
return writer.toString();
}
}
and
public class FreemarkerTransformerPojoTests {
#Test
public void test() throws Exception {
String template = System.getProperty("user.home") + "/Development/tmp/test.ftl";
OutputStream os = new FileOutputStream(new File(template));
os.write("foo=${foo}, bar=${bar}".getBytes());
os.close();
FreemarkerTransformerPojo transformer = new FreemarkerTransformerPojo(template);
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "baz");
map.put("bar", "qux");
String result = transformer.transform(map);
assertEquals("foo=baz, bar=qux", result);
}
}
From a Spring Integration flow, send a message with a Map payload to
<int:transformer ... ref="fmTransformer" method="transform" />
Or you could do it with a groovy script (or other supported scripting language) using Spring Integration's existing scripting support without writing any code (except the script).

BeforeFeature/AfterFeature does not work using SpecFlow and Coded UI

I am not able to define a [BeforeFeature]/[AfterFeature] hook for my feature file. The application under test is WPF standalone desktop applications.
If I use [BeforeScenario]/[AfterScenario] everything works fine, the application starts without any problem, the designed steps are performed correctly and the app is closed.
Once I use the same steps with [BeforeFeature]/[AfterFeature] tags the application starts and the test fails with:
The following error occurred when this process was started: Object reference not set to an instance of an object.
Here is an example:
[Binding]
public class Setup
{
[BeforeScenario("setup_scenario")]
public static void BeforeAppScenario()
{
UILoader.General.StartApplication();
}
[AfterScenario("setup_scenario")]
public static void AfterAppScenario()
{
UILoader.General.CloseApplication();
}
[BeforeFeature("setup_feature")]
public static void BeforeAppFeature()
{
UILoader.General.StartApplication();
}
[AfterFeature("setup_feature")]
public static void AfterAppFeature()
{
UILoader.General.CloseApplication();
}
}
StartApplication/CloseApplication were recorded and auto-generated with Coded UI Test Builder:
public void StartApplication()
{
// Launch '%ProgramFiles%\...
ApplicationUnderTest Application = ApplicationUnderTest.Launch(this.StartApplicationParams.ExePath, this.StartApplicationParams.AlternateExePath);
}
public class StartApplicationParams
{
public string ExePath = "C:\\Program Files..."
public string AlternateExePath = "%ProgramFiles%\\..."
}
Noteworthy: I'm quite new with SpecFlow.
I can't figure it out why my test fails with [BeforeFeature] and works fine with [BeforeScenario].
It would be great if somebody could help me with this issue. Thanks!
I ran into a similar problem recently. Not sure if this can still help you, but it may be of use for people who stumble upon this question.
For BeforeFeature\AfterFeature to work, the feature itself needs to be tagged, tagging just specific scenarios will not work.
Your feature files should start like this:
#setup_feature
Feature: Name Of Your Feature
#setup_scenario
Scenario: ...

Exception when trying to show a form created in another (background) thread on .netCF with OAC

In a multi form .NetCF 3.5 application I'm trying create the forms in the background while the user is occupied with the previous form.
We're using Orientation Aware Control in the project
We use a wrapper class (FormController) (please let me know if I'm using the wrong terminology) to keep static references to the different forms in our application. Since we only want to create them once.
At the moment the Forms are created the first time they are used. But since this is a time consuming operation we'd like to do this in the background while the user
Application.Run(new FormController.StartUI());
class FormController{
private static object lockObj = new object();
private static bool secIsLoaded = false;
private static StartForm startForm = new StartForm();
private static SecForm m_SecForm;
static SecForm FormWorkOrderList
{
get
{
CreateSecForm();
return m_SecForm;
}
}
private static void StartUI(){
startForm.Show();
ThreadStart tsSecForm = CreateSecForm;
Thread trSecForm = new Thread(tsSecForm);
trSecForm.Priority = ThreadPriority.BelowNormal;
trSecForm.IsBackground = true;
trSecForm.Start();
return startForm;
}
private static void CreateSecForm()
{
Monitor.Enter(lockObj);
if(!secIsLoaded){
m_SecForm = new SecForm();
secIsLoaded = true;
}
Monitor.Exit(lockObj);
}
private static void GotoSecForm()
{
SecForm.Show();
StartForm.Hide();
}
When I call GotoSecForm() the program throws an excepton on SecForm.Show() with an exection with hResult: 2146233067 and no other valuable information.
The stacktrace of the exception is:
on Microsoft.AGL.Common.MISC.HandleAr(PAL_ERROR ar)
on System.Windows.Forms.Control.SuspendLayout()
on b..ctor(OrientationAwareControl control)
on Clarius.UI.OrientationAwareControl.ApplyResources(CultureInfo cultureInfo, Boolean skipThis)
on Clarius.UI.OrientationAwareControl.ApplyResources()
on Clarius.UI.OrientationAwareControl.OnLoad(EventArgs e)
on Clarius.UI.OrientationAwareControl.c(Object , EventArgs )
on System.Windows.Forms.Form.OnLoad(EventArgs e)
on System.Windows.Forms.Form._SetVisibleNotify(Boolean fVis)
on System.Windows.Forms.Control.set_Visible(Boolean value)
on System.Windows.Forms.Control.Show()
I'm quite qlueless about what's going wrong here. Can anyone help me out?
Or are there some better ways to load the forms in the background?
Let me know if any more information is needed.
You can't create forms (or safely do any manipulation of controls or forms) in background threads. They need to be created on the same thread that the message pump is running on - its just the way that Windows Forms work.
Creating the form itself shouldn't be in itself an expensive task. My advice would be to perform any expensive computations needed to display the form in a background thread, and then pass the result of those computations back to the main message pump in order to create and display the form itself.
(Half way through writing this I realised that this question is about windows mobile, however I'm 99% sure that the above still applies in this situation)

Resources