Selenium Webdriver - Apache POI - XSSF - 2nd loop is not getting executed - loops

I’m using Apache POI to read data from multiple excel but my code doesn’t recognize the value from 2nd excel, It’s not even getting inside my 2nd FOR loop
Excel 1 – Test Data to login
Excel 2 – Course Details
My Login credentials is present in the 1st excel, It has 5 data in it. I would like to login with that user and add course for that user. Appreciate your help on this!!
Note # please suggest if you have any concerns on this piece of code
Below is the code that I’m using
package M1.Testcases;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import Helper.BrowserFactory;
import M1.Pages.Add_Course;
import M1.Pages.LoginPage;
public class CopyOfVerifyAdd_Course
{
WebDriver driver;
#Test
#Parameters("browser")
public void checkValidUser(String browser) throws IOException, InterruptedException
{
try
{
FileInputStream file = new FileInputStream(new File("File1Path"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
FileInputStream file1 = new FileInputStream(new File("File2Path"));
XSSFWorkbook workbook1 = new XSSFWorkbook(file1);
XSSFSheet sheet1 = workbook1.getSheetAt(0);
String url= "1st URL";
for (int i=1; i <= sheet.getLastRowNum(); i++)
{
String uid = sheet.getRow(i).getCell(0).getStringCellValue();
String pass = sheet.getRow(i).getCell(1).getStringCellValue();
WebDriver driver=BrowserFactory.startBrowser(browser,url);
LoginPage login_page=PageFactory.initElements(driver, LoginPage.class);
login_page.login_MI(uid,pass);
driver.get("2nd URL");
driver.manage().timeouts().implicitlyWait(10000, TimeUnit.MILLISECONDS);
for (int j=1; j <= sheet1.getLastRowNum(); j++)
{
Thread.sleep(10000);
String course_title = sheet1.getRow(j).getCell(0).getStringCellValue();
String course_code = sheet1.getRow(j).getCell(1).getStringCellValue();
String course_cat_desc = sheet1.getRow(j).getCell(2).getStringCellValue();
String course_full_desc = sheet1.getRow(j).getCell(3).getStringCellValue();
String course_price = sheet1.getRow(j).getCell(4).getStringCellValue();
String course_target_audience = sheet1.getRow(j).getCell(5).getStringCellValue();
String course_learner_assess = sheet1.getRow(j).getCell(6).getStringCellValue();
String course_copyright = sheet1.getRow(j).getCell(7).getStringCellValue();
String course_release_date = sheet1.getRow(j).getCell(8).getStringCellValue();
String course_review_date = sheet1.getRow(j).getCell(9).getStringCellValue();
String course_expiration_date = sheet1.getRow(j).getCell(10).getStringCellValue();
String course_state_req = sheet1.getRow(j).getCell(11).getStringCellValue();
String course_bibi = sheet1.getRow(j).getCell(12).getStringCellValue();
Add_Course add_course_page=PageFactory.initElements(driver, Add_Course.class);
driver.switchTo().frame(course_cat_desc);
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
driver.switchTo().frame(course_full_desc);
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
driver.switchTo().frame(course_target_audience);
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
driver.switchTo().frame(course_learner_assess);
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
driver.switchTo().frame(course_state_req);
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
driver.switchTo().frame(course_bibi);
driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
add_course_page.AddCourse(course_title,course_code,course_cat_desc,course_full_desc,course_price,course_target_audience,course_learner_assess,
course_copyright,course_release_date,course_review_date,course_expiration_date,course_state_req,course_bibi);
Thread.sleep(10000);
}
driver.manage().deleteAllCookies();
driver.quit();
}
workbook.close();
file.close();
workbook1.close();
file1.close();
}
catch (FileNotFoundException fnfe)
{
fnfe.printStackTrace();
}
}
}

Related

Passing values from database to the UI using Automation Selenium WebDriver with Java?

I am trying to pass values from my MySQL database to the UI using Automation Selenium WebDriver with Java? The code is returning only the first row.
Here are the database values:
I have changed the code many times using for int loop and have received different kind of errors such as:
before start of result set
after end of result set
I am unable to figure it out. I am not sure what I am doing wrong.
Basically, In this case I have firstName and lastName which are passed via the database to the UI. I want to pass those values to my test case. I do not want to hard code. Currently, I have a table with 2 columns and one column is firstName and second column is lastName.
I want to Iterate through the database and pick these values wherever I want. SendKeys.
Here is my test case code file.
FacebookTest file code below.
import static org.testng.Assert.assertThrows;
import java.sql.Array;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import selenium.ReadExcel;
public class FacebookTest
{
#SuppressWarnings({ "static-access", "unchecked" })
public static void main(String[] args) throws Exception
//public static void facebookTest()
{
// pointing to the file, now FF must have pointer as well in Selenium 3.0
// WebDriver
System.setProperty("webdriver.gecko.driver","geckodriver.exe");
// OPEN FF
FirefoxDriver driver = new FirefoxDriver();
DBTestData db = new DBTestData();
// ENTER URL
driver.get("http://www.facebook.com/");
try
{
ResultSet testData = db.data("","");
for(int i = 0; i < 10; i++)
{
String firstName = testData.getString("firstName");
String lastName = testData.getString("lastName");
System.out.println(firstName);
System.out.println(lastName);
driver.findElement(By.id("u_0_e")).clear();
driver.findElement(By.id("u_0_e")).sendKeys(firstName);
driver.findElement(By.id("u_0_g")).clear();
driver.findElement(By.id("u_0_g")).sendKeys(lastName);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
driver.quit();
}
}
}
Here is my DB file where I am getting the values from database and returning it to the test case 101 - see code below.
DBTestData code file below.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
public class DBTestData {
// public static void main(String[] args) throws Exception
#SuppressWarnings({ "unused" })
// public static String data() throws Exception
public static ResultSet data(String firstName, String lastName) throws ClassNotFoundException, SQLException
{
// Accessing driver from the JAR file
Class.forName("com.mysql.jdbc.Driver");
// Creating a variable for the connection called "con"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "username", "password");
// after localhost:3306 is where you will put the name of the database
// jdbc:mysql://localhost:3606/testdb ---> this is a database
// root is a database user and password too
// our query below
PreparedStatement statement = con.prepareStatement("SELECT firstName, lastName FROM test_data");
// creating variable to execute query
ResultSet result = statement.executeQuery();
// List sqlData = new ArrayList();
ArrayList<String> sqlData = new ArrayList<String>();
while (result.next())
{
sqlData.add(firstName = result.getString(firstName));
sqlData.add(lastName = result.getString(lastName));
}
return result;
}
}
Let me know how I can achieve this concept. Once I get the basics I will utilize the same file other test cases. Why can't we use the same concept 2D array to pass the values from database to UI?
Here is how I resolved my issue. I used a do while loop in my test case and It was able to fetch all the data from all rows and Iterate it in my webpage.
Here is the code below.
FacebookTest code file:
import static org.testng.Assert.assertThrows;
import java.sql.Array;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import selenium.ReadExcel;
public class FacebookTest
{
#SuppressWarnings({ "static-access", "unchecked" })
public static void main(String[] args) throws Exception
{
// pointing to the file, now FF must have pointer as well in Selenium 3.0 WebDriver
System.setProperty("webdriver.gecko.driver","geckodriver.exe");
// OPEN FF
FirefoxDriver driver = new FirefoxDriver();
DBTestData db = new DBTestData();
// ENTER URL
driver.get("http://www.facebook.com/");
try
{
ResultSet testData = db.data("","");
do
{
String firstName = testData.getString(1);
String lastName = testData.getString(2);
driver.findElement(By.id("u_0_e")).clear();
driver.findElement(By.id("u_0_e")).sendKeys(firstName);
driver.findElement(By.id("u_0_g")).clear();
driver.findElement(By.id("u_0_g")).sendKeys(lastName);
}
while(testData.next());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
driver.quit();
}
}
}
Here is my DBTestData file:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
public class DBTestData
{
public static ResultSet data(String firstName, String lastName) throws ClassNotFoundException, SQLException
{
// Accessing driver from the JAR file
Class.forName("com.mysql.jdbc.Driver");
// Creating a variable for the connection called "con"
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "username", "password");
// after localhost:3306 is where you will put the name of the database
// jdbc:mysql://localhost:3606/testdb ---> this is a database
// root is a database user and password too
// our query below
PreparedStatement statement = con.prepareStatement("SELECT firstName, lastName FROM test_data");
// creating variable to execute query
ResultSet result = statement.executeQuery();
// store all the rows data into one variable
ArrayList<String> sqlData = new ArrayList<String>();
while(result.next())
{
sqlData.add(firstName= result.getString("firstName"));
sqlData.add(lastName = result.getString("lastName"));
break;
}
return result;
}
}
So, how do I properly close the database connection?
And how do I Iterate until n number of rows?
Thanks
con.close(); is command for closing db

Read Excel data and use it in selenium

This script is to read data from excel and use it in selenium script. This uses Apache POI to read the data, store it in variables and use it.
You can try following code. I have taken facebook as sample application.
package testPackage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;
import org.testng.annotations.DataProvider;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ExcelReadingwithDP {
WebDriver driver;
#BeforeTest
public void OpenApp()
{
System.setProperty("webdriver.chrome.driver", "E:/Selenium/Webdriver/Softwares/chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://facebook.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Test(dataProvider="empLogin")
public void login(String username, String password)
{
WebElement login1 = driver.findElement(By.id("email"));
login1.clear();
login1.sendKeys(username);
WebElement passwd=driver.findElement(By.id("pass"));
passwd.clear();
passwd.sendKeys(password);
driver.findElement(By.xpath("//*[#id='u_0_q']")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement back = driver.findElement(By.xpath("//*[#id='blueBarDOMInspector']/div/div[1]/div/div/h1/a/i"));
back.click();
}
#DataProvider(name="empLogin")
public Object[][] logindata()
{
Object[][] arrayobject = getexceldata("E://Deepak/IntranetLogin.xls","Sheet1");
return arrayobject;
}
public String[][] getexceldata(String filename, String sheetname)
{
String[][] arrayexceldata = null;
try
{
FileInputStream fis = new FileInputStream(filename);
Workbook wb = Workbook.getWorkbook(fis);
Sheet sh = wb.getSheet(sheetname);
int row = sh.getRows();
int col = sh.getColumns();
arrayexceldata = new String[row-1][col];
for (int i=1;i< row;i++)
{
for(int j=0;j<col;j++)
{
arrayexceldata[i-1][j]=sh.getCell(j,i).getContents();
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayexceldata;
}
}
/*
* Download Apache POI from https://www.apache.org/dyn/closer.lua/poi/release/bin/poi-bin-3.16-20170419.zip
*
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FormFill {
public static void main(String[] args) throws Exception {
try {
FileInputStream fileInputStream = new FileInputStream("C:\\data.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("sheet1");
HSSFRow row1 = worksheet.getRow(0);
HSSFCell cellA1 = row1.getCell((short) 0);
String a1Val = cellA1.getStringCellValue();
HSSFCell cellB1 = row1.getCell((short) 1);
String b1Val = cellB1.getStringCellValue();
System.out.println("A1: " + a1Val);
System.out.println("B1: " + b1Val);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String url = "http://thedemosite.co.uk/addauser.php";
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(url);
//Thread.sleep(30000);
driver.findElement(By.name("username")).sendKeys(a1Val);
driver.findElement(By.name("password")).sendKeys(b1Val);
}
}
I feel csv is better than Excel because Excel more time to read the data but csv is fast.
private static final String CSV_SEPARATOR = ",(?=(?:[^\"]\"[^\"]\")[^\"]$)";
public List<String[]> parseFile(String fileName) {
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
br.readLine(); // skip header;
String line = br.readLine();
List<String[]> lines = new ArrayList();
while (line != null) {
//System.out.println(line.toString());
lines.add(line.split(CSV_SEPARATOR));
line = br.readLine();
}
return lines;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Null Pointer Exception when using Apache POI

I am trying to input the values to excel from web, having 2 columns and 9 rows, so that I will get the price and the description of 10 products from the web.
but Iam getting the Null pointer exception. Please any one help me out in clearing this error.
package samples;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//import org.apache.commons.io.FileUtils;
//import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
//import org.openqa.selenium.OutputType;
//import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class A1 {
public static void main(String[] args) throws InterruptedException, ParseException, IOException, EncryptedDocumentException, InvalidFormatException
{
System.out.println("selenium");
WebDriver webdriver = new FirefoxDriver();
webdriver.manage().window().maximize();
webdriver.get("http://www.snapdeal.com");
webdriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> alllinks = webdriver.findElements(By.tagName("a"));
int linkcnt = alllinks.size();
System.out.println("total links=" +linkcnt);
Actions action = new Actions(webdriver);
WebElement COG = webdriver.findElement(By.xpath("//span[text()='Computers, Office & Gaming']"));
WebElement EHD = webdriver.findElement(By.xpath("//span[text()='External Hard Drives']"));
action.moveToElement(COG).build().perform();
Thread.sleep(5000);
EHD.click();
webdriver.findElement(By.xpath("//label[#for='Capacity_s-1 TB']")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("//a[contains(text(),'500 GB')]/..")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("(//span[#class='price-collapse-arrow'])[1]/..")).click();
WebElement totalitems = webdriver.findElement(By.xpath("//span[#class='category-count']"));
String totalitemsvalue=totalitems.getText();
System.out.println(totalitemsvalue);
String value=totalitemsvalue.replaceAll(" Items","");
System.out.println(value);
try{
List<WebElement> productprice = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[2]"));
List<WebElement> productTitle = webdriver.findElements(By.xpath("//div[#class='product-desc-rating title-section-collapse']"));
int count=productprice.size();
int count1=productTitle.size();
System.out.println(count);
System.out.println(count1);
//int i=9;
// int j=9;
Thread.sleep(2000);
for (count=0;count<10;count++)
{
productprice = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[2]"));
// File srcfile=((TakesScreenshot)webdriver).getScreenshotAs(OutputType.FILE);
// FileUtils.copyFile(srcfile, new File("c:\\screenshot.png"));
Thread.sleep(2000);
String RupeesValue= productprice.get(count).getText();
System.out.println(RupeesValue);
Thread.sleep(2000);
productTitle = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[1]"));
Thread.sleep(2000);
String TitleValue= productTitle.get(count1).getText();
System.out.println(TitleValue);
Thread.sleep(2000);
FileInputStream fis = new FileInputStream("C:\\Users\\aa74231\\Desktop\\abc.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheet("Sheet1");
// Sheet sheet1 = wb.getSheet("Sheet1");
for (int i=0;i<2;i++)
{
Row row=sheet.getRow(count);
// Row row1=sheet.getRow(j);
Cell cell = row.createCell(count);
// Cell cell1 = row1.createCell(count1);
cell.setCellType(cell.CELL_TYPE_STRING);
//cell1.setCellType(cell1.CELL_TYPE_STRING);
if(i==0){
cell.setCellValue(productprice.get(count).getText());
}
else
{
cell.setCellValue(productTitle.get(count).getText());
}
//cell1.setCellValue(productTitle.get(count1).getText());
FileOutputStream fos=new FileOutputStream("C:\\Users\\aa74231\\Desktop\\abc.xlsx");
wb.write(fos);
fos.close();
wb.close();
}
}
} catch(Exception e){
e.printStackTrace();
}
}
}
exception which am getting is :
Exception in thread "main" java.lang.NullPointerException
at samples.learningold.main(learningold.java:97)
First of all your ProductTitle Xpath is not fetching all the product names from the list. I have updated that too.
Following code works well.
package samples;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class X
{
#SuppressWarnings("resource")
public static void main(String[] args) throws InterruptedException, ParseException, IOException, EncryptedDocumentException, InvalidFormatException
{
System.out.println("selenium");
WebDriver webdriver = new FirefoxDriver();
webdriver.manage().window().maximize();
webdriver.get("http://www.snapdeal.com");
webdriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> alllinks = webdriver.findElements(By.tagName("a"));
int linkcnt = alllinks.size();
System.out.println("total links=" +linkcnt);
Actions action = new Actions(webdriver);
WebElement COG = webdriver.findElement(By.xpath("//span[text()='Computers, Office & Gaming']"));
WebElement EHD = webdriver.findElement(By.xpath("//span[text()='External Hard Drives']"));
action.moveToElement(COG).build().perform();
Thread.sleep(5000);
EHD.click();
webdriver.findElement(By.xpath("//label[#for='Capacity_s-1 TB']")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("//a[contains(text(),'500 GB')]/..")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("(//span[#class='price-collapse-arrow'])[1]/..")).click();
Thread.sleep(5000);
WebElement totalitems = webdriver.findElement(By.xpath("//span[#class='category-count']"));
String totalitemsvalue=totalitems.getText();
System.out.println(totalitemsvalue);
String value=totalitemsvalue.replaceAll(" Items","");
System.out.println(value);
try
{
List<WebElement> productprice = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[2]"));
List<WebElement> productTitle = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[1]"));
int count=productprice.size();
int count1=productTitle.size();
System.out.println(count);
System.out.println(count1);
String[] productPriceList = new String[count];
String[] productTitleList = new String[count];
Thread.sleep(2000);
for(int k =0; k<count; k++)
{
System.out.println(productprice.get(k).getText());
productPriceList[k]=productprice.get(k).getText();
System.out.println(productTitle.get(k).getText());
productTitleList[k]=productTitle.get(k).getText();
}
File file= new File("C:\\Users\\XX\\Downloads\\snapdeal.xlsx"); // give your file path
FileInputStream inputStream = new FileInputStream(file);
Workbook sampleWorkbook=null;
sampleWorkbook=new XSSFWorkbook(inputStream);
Sheet sheet = sampleWorkbook.getSheet("Sheet1");
for(int t=0;t<count;t++)
{
Row row = sheet.createRow(t);
Cell cell = row.createCell(0); // create column 1
cell.setCellValue(productPriceList[t].toString());
Cell cell1 = row.createCell(1); // create column 2
cell1.setCellValue(productTitleList[t].toString());
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(file);
sampleWorkbook.write(outputStream);
System.out.println("Data written to Excel successful");
outputStream.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

MULE HTTP listener attachment with rest web service

I am New to MULE ESB I am tryting to handle file attachment with http listener using rest web service.
I am created a simple flow but dont know how to handle attachment in mule to pass rest ful web service .
Any help greatly appreciated!!
:(
Given is simple flow waht i am assuming to be work !!
rest web service code ::
package com.one.file;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#Path("/upload")
public class RESTMultipleFileUpload {
private static final String FILE_UPLOAD_PATH = "C:\\Users\\charan\\Documents\\webservice\\";
//private static final String CANDIDATE_NAME = "candidateName";
private static final String SUCCESS_RESPONSE = "Successful";
private static final String FAILED_RESPONSE = "Failed";
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("text/plain")
#Path("/multipleFiles")
public String registerWebService(#Context HttpServletRequest request)
{
String responseStatus = SUCCESS_RESPONSE;
String candidateName = null;
System.out.println("first ");
System.out.println("Two::"+request);
//checks whether there is a file upload request or not
if (ServletFileUpload.isMultipartContent(request))
{
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
try
{
System.out.println("t ");
/*
* parseRequest returns a list of FileItem
* but in old (pre-java5) style
*/
final List items = fileUpload.parseRequest(request);
if (items != null)
{
final Iterator iter = items.iterator();
while (iter.hasNext())
{
final FileItem item = (FileItem) iter.next();
final String itemName = item.getName();
final String fieldName = item.getFieldName();
final String fieldValue = item.getString();
if (item.isFormField())
{
candidateName = fieldValue;
System.out.println("Field Name: " + fieldName + ", Field Value: " + fieldValue);
System.out.println("Candidate Name: " + candidateName);
}
else
{
final File savedFile = new File(FILE_UPLOAD_PATH + File.separator
+ itemName);
System.out.println("Saving the file: " + savedFile.getName());
item.write(savedFile);
}
}
}
}
catch (FileUploadException fue)
{
responseStatus = FAILED_RESPONSE;
fue.printStackTrace();
}
catch (Exception e)
{
responseStatus = FAILED_RESPONSE;
e.printStackTrace();
}
}
System.out.println("Returned Response Status: " + responseStatus);
return responseStatus;
}
}

Execute lucene booleanquery in file huge problems

I 've a problem with my huge nquad file (about 4000 lines) when i execute a boolenquery,
i try a query as:
Query query1 = new TermQuery(new Term(FIELD_CONTENTS, "Albania"));
Query query2 = new TermQuery(new Term(FIELD_CONTENTS, "Hitchcock"));
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.add(query1, BooleanClause.Occur.MUST);
booleanQuery.add(query2, BooleanClause.Occur.MUST);
This query performs correctly when the words that I try to search in the line number<780, then >780 failed.
This is a snippet of my nquad file:
<http://dbpedia.org/resource/A_Clockwork_Orange> <http://dbpedia.org/ontology/numberOfPages> "192"^^<http://www.w3.org/2001/XMLSchema#positiveInteger> <http://en.wikipedia.org/wiki/A_Clockwork_Orange?oldid=606117686#absolute-line=12> .
I make a custom analyzer for distinguer tokens:
import java.io.Reader;
import java.util.Set;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.StopFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
class TestAnalyzer1 extends Analyzer {
public static final String[] TEST_STOP_WORDS = { "http", "https",
"resource", "foaf/0.1", "dbpedia.org", "en.wikipedia.org",
"xmlns.com", "purl.org", "elements/1.1",
"www.w3.org/2001/XMLSchema", "www.w3.org/1999/02/22-rdf",
"www.w3.org/2003/01", "oldid", "wiki" };
#SuppressWarnings("rawtypes")
private Set stopWords = StopFilter.makeStopSet(TEST_STOP_WORDS);
public TokenStream tokenStream(String fieldName, Reader reader) {
TokenStream ts = new StandardTokenizer(reader);
ts = new StandardFilter(ts);
ts = new StopFilter(ts, stopWords);
return ts;
}
}
This is main class:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermFreqVector;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hit;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
#SuppressWarnings("deprecation")
public class TestPreFinal {
public static final String FILES_TO_INDEX_DIRECTORY = "filesToIndex_1";
public static final String INDEX_DIRECTORY = "indexDirectory";
public static final String FIELD_PATH = "path";
public static final String FIELD_CONTENTS = "contents";
public static void main(String[] args) throws CorruptIndexException,
LockObtainFailedException, IOException, ParseException {
long startTime = System.currentTimeMillis();
Analyzer analyzer = new TestAnalyzer1();
IndexWriter indexWriter = new IndexWriter(INDEX_DIRECTORY, analyzer,
true);
File dir = new File(FILES_TO_INDEX_DIRECTORY);
File[] files = dir.listFiles();
for (File file : files) {
Reader reader = new FileReader(file);
Document document = new Document();
String path = file.getCanonicalPath();
Field fieldPath = new Field(FIELD_PATH, path, Field.Store.YES,
Field.Index.UN_TOKENIZED);
Field fieldContents = new Field(FIELD_CONTENTS, reader,
Field.TermVector.WITH_POSITIONS_OFFSETS);
document.add(fieldPath);
document.add(fieldContents);
indexWriter.addDocument(document);
}
indexWriter.commit();
indexWriter.close();
Directory directory = FSDirectory.getDirectory(INDEX_DIRECTORY);
IndexSearcher indexSearcher = new IndexSearcher(directory);
IndexReader indexReader = IndexReader.open(directory);
Query query1 = new TermQuery(new Term(FIELD_CONTENTS, "Albania"));
Query query2 = new TermQuery(new Term(FIELD_CONTENTS, "Hitchcock"));
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.add(query1, BooleanClause.Occur.MUST);
booleanQuery.add(query2, BooleanClause.Occur.MUST);
Hits hits = indexSearcher.search(booleanQuery);
#SuppressWarnings({ "unchecked" })
Iterator<Hit> it = hits.iterator();
TermFreqVector tfv = null;
while (it.hasNext()) {
Hit hit = it.next();
Document document = hit.getDocument();
String path = document.get(FIELD_PATH);
System.out.println("Hit: " + path);
}
for (int i = 0; i < hits.length(); i++) {
tfv = indexReader.getTermFreqVector(i, FIELD_CONTENTS);
System.out.println(tfv);
}
}
}
I do not know what else to do. You can help please. Thanks in advance.

Resources