I need to do a search with Selenium and display the results. Actually, I have a program in selenium to display a table and put a search word in the text field. And when the word is written automatically, tabulate the columns containing those words.
Here’s a code from my program.
private static String searchName = "//*[#id=\"searchName\"]";
private static String tableExist = "//table[#role='table']/tbody/tr";
//return if exist elements in the table
public static Boolean elementExistsInTheTableCustomer() {
return (driver.findElements(By.xpath(tableExist)).size() > 0);
}
// here i put the text search
public static void enterSearchName(String nameSearchTxt) {
driver.findElement(By.xpath(searchName)).sendKeys(nameSearchTxt);
}
// this function to put 2 char to search in the table
public static void searchStringName() {
String strSearch = RandomStringUtils.randomAlphabetic(2);
System.out.println("The String search : " + strSearch);
Customer.enterSearchName(strSearch);
}
public static WebElement displayElementTables() {
WebElement list = webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(tableExist)));
return list;
}
//here the test of element after and before the search name
#Test
public void GIVEN_Customers_On_Database() throws InterruptedException {
Customer.clickCustomers();
Thread.sleep(3000);
if (Customer.elementExistsInTheTableCustomer()) {
System.out.println("\t===============================");
for (WebElement detail : Customer.displayElementTables()) {
System.out.println("\t The elements in the table : " + detail.getText());
}
System.out.println("\t===============================");
}
Customer.searchStringName();
// here to display if i have elements or no
for (WebElement detail : Customer.displayElementTables()) {
System.out.println("\t The elements in the table : " + detail.getText());
}
}
In the last part, I will check if he has any lines to publish. the displayElementTables() function in which I can receive the search result. whether I have items or not and put the result in a variable to display.
public static List<WebElement> displayElementTables() {
List<WebElement> list = webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(tableExist)));
return list;
}
I have a very strange problem. I'm trying to show in a basket the price of products. When I run the code and add a product to the basket, I can see the name of the product but I can't see its price. When I click back to a previous page and add another product, I am able to see its price. There is no error message.
Also, when I try to debug this program, everything works. The problem appears only when I'm not debugging. The problem is closely connected with these two variables as indicated below. I think that these variables are 0 which is later printed on the screen. But I don't know why they are sometimes 0 and sometimes not. I also tried to set breakpoints on:
dataService.getQuantityOfDays();
dataService.getQuantityOfBreakfasts();
When I assign values to these two variables in Data class everything is ok (not 0).
Controller code:
#RequestMapping("/basket/{roomName}")
public String createBasket(Model model, #PathVariable("roomName") String roomName){
Floor currentFloor = floorService.getCurrentFloor();
User currentUser = userService.getCurrentUser();
this.roomName = roomName;
if(currentFloor != null){
Room currentRoom = roomService.getRoomByName(roomName, currentFloor);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
if(currentUser == null){
userService.setCurrentUser(userService.getUserByName(name)); // wykona sie jesli nie zakladamy konta w danej sesji
}
Basket basketToSave = new Basket(userService.getCurrentUser());
BasketItem basketItem = new BasketItem(currentRoom);
int quantityOfDays = dataService.getQuantityOfDays(); //<--problem
int quantityOfBreakfast = dataService.getQuantityOfBreakfasts(); //<--problem
int priceForOneBreakfast = 17;
int priceForOneDay = currentRoom.getPriceForOneDay();
int wholePrice = quantityOfDays * priceForOneDay + quantityOfBreakfast * priceForOneBreakfast;
basketItem.setPrice(wholePrice);
basketItem.setQuantityOfDays(quantityOfDays);
basketItem.setQuantityOfBreakfast(quantityOfBreakfast);
Set<BasketItem> basketItemList = new HashSet<BasketItem>();
basketItemList.add(basketItem);
basketService.countBasketPrice(basketItemList, basketToSave);
basketToSave.setBasketItems(basketItemList);
basketItem.setBasket(basketToSave);
currentRoom.setBasketItemList(basketItemList);
boolean ifWasAnUpdate = basketService.save(basketToSave); // metoda save oprócz zapisu lub nadpisania zwraca co się wydarzyło (true - jesli nadpisywaliśmy koszyk)
if(ifWasAnUpdate){
basketItem.setBasket(basketService.get(basketToSave.getUser())); // jeżeli dodaje coś do koszyka (a nie tworzę go od nowa), muszę ustawić basketItemowi
} // koszyk, który już istnieje, a nie ten, który stworzyłem wcześniej w klasie BasketController.
// W tym celu pobieram go z bazy.
basketItemService.save(basketItem);
}
model.addAttribute("basket", basketService.get(currentUser));
model.addAttribute("days", dataService.getQuantityOfDays());
return "basket";
}
EDIT:
It's a repository code.
#Repository
public class DataRepositoryImpl implements DataRepository {
private int quantityOfDays;
private int quantityOfBreakfasts;
public void setQuantityOfDaysAndBreakfasts(String text) {
List<Integer> listOfIndexes = new ArrayList<Integer>();
for(int i=0;i<text.length();i++){
if(text.charAt(i) != '1'){
listOfIndexes.add(i);
}
}
char znak = text.charAt(listOfIndexes.get(0));
this.quantityOfDays = Character.getNumericValue(text.charAt(listOfIndexes.get(0))); // <- I put breakpoint here
this.quantityOfBreakfasts = Character.getNumericValue(text.charAt(listOfIndexes.get(1))); // <- I put breakpoint here
}
public int getQuantityOfDays() {
return this.quantityOfDays;
}
public int getQuantityOfBreakfasts() {
return this.quantityOfBreakfasts;
}
}
A problem can be also in basket save. Firslty when I can see only zeros I persist basket, then I'm only updating it.
Save & update methods:
public boolean save(Basket basketToSave) {
List<Basket> listOfAllBaskets = getAll();
boolean save = true;
boolean ifWasAnUpdate = false;
for(Basket basket: listOfAllBaskets){
if(basketToSave.getUser().equals(basket.getUser())){
save = false;
}
}
if(save){
emManager.persist(basketToSave);
}else{
updateBasket(basketToSave);
ifWasAnUpdate = true;
}
return ifWasAnUpdate;
}
public void updateBasket(Basket basket) {
Basket basketFromDatabase = get(basket.getUser());
basketFromDatabase.setBasketItems(basket.getBasketItems());
basketFromDatabase.setPrice(basket.getPrice());
emManager.merge(basketFromDatabase);
}
EDIT
I'm calling setQuantityOfDaysAndBreakfasts(text) earlier in this apllication. In this controller I'm only setting these values to basketItem class. I'll change this controller. Here another controller where I call setQuantityOfDaysAndBreakfasts(text).
#RequestMapping(value = "/room/rest", method = RequestMethod.POST, consumes = {"application/json"})
public void data(#RequestBody Data request){
String text = request.getText();
dataService.setQuantityOfDaysAndBreakfasts(text);
}
You are calling setQuantityOfDaysAndBreakfasts() after you get the value from your dataService. The value for quantityOfDays and quantityOfBreakfasts are only set when that method is called.
There are several things you should also examine.
As #NathanHughes points out, it's best to put your complex logic in your service layer and leave the controller to simply route requests. This is also true of your repository class. You should keep this very simple as the next developer reading your code is not going to expect to find any logic that doesn't simply read or write to your data source. (See Single Responsibility Principle.) It will also reduce code duplication in the future and as a result, reduce your time maintaining and fixing bugs.
For example, this code:
List<Integer> listOfIndexes = new ArrayList<Integer>();
for(int i=0;i<text.length();i++){
if(text.charAt(i) != '1'){
listOfIndexes.add(i);
}
}
char znak = text.charAt(listOfIndexes.get(0));
Should be refactored to a separate method entirely that can be made static and would not belong in that class.
I want to check if the value does exist or not in Tree when trying to add node from Tree. The value does not match in the case that I got Object instead of String.
Here is the action code for calling existsInTable()
try {
DefaultMutableTreeNode selectedElement = (DefaultMutableTreeNode) TestTree.getSelectionPath().getLastPathComponent();
Object[] row = {selectedElement};
DefaultTableModel model = (DefaultTableModel) myTests_table.getModel();
if (selectedElement.isLeaf() == true && existsInTable(myTests_table, row) == false) {
model.addRow(row);
} else {
JOptionPane.showMessageDialog(null, "Please Choose Test name!", "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
Here are the check method
public boolean existsInTable(JTable table, Object[] testname) {
int row = table.getRowCount();
for (int i = 0; i < row; i++) {
String str = "";
str = table.getValueAt(i, 0).toString();
if (testname.equals(str)) {
System.out.println(str);
JOptionPane.showMessageDialog(null, "data alreadyexist.", "message", JOptionPane.PLAIN_MESSAGE);
return true;
}
}
return false;
}
the result is this : [Ljava.lang.Object;#11da1f8
but it should be : Test
If you add an instance of Object to your TableModel, that is what getValueAt() will return. Given an Object, the result returned by toString() is entirely expected—"a string consisting of the name of the class of which the object is an instance, the at-sign character #, and the unsigned hexadecimal representation of the hash code of the object."
Looking closer, you appear to have added an array of Object instances. Given a default table model,
DefaultTableModel model = new DefaultTableModel(1, 1);
the following lines
model.setValueAt(new Object[1], 0, 0);
System.out.println(model.getValueAt(0, 0));
produce this output:
[Ljava.lang.Object;#330bedb4
To see a string, such as "Test", add a corresponding instance of String to your TableModel:
model.setValueAt("Test", 0, 0);
System.out.println(model.getValueAt(0, 0));
which produces the desired output:
Test
For best results, verify that your implementation of getColumnClass() is compatible, as suggested in How to Use Tables: Concepts: Editors and Renderers.
I have a hbase table where all keys have the following structure ID,DATE,OTHER_DETAILS
For example:
10,2012-05-01,"some details"
10,2012-05-02,"some details"
10,2012-05-03,"some details"
10,2012-05-04,"some details"
...
How can I write a scan that get all the rows that older than some date?
For example 2012-05-01 and 2012-05-02 are older than 2012-05-03.
Scan scan = new Scan();
Filter f = ???
scan.setFilter(f);
scan.setCaching(1000);
ResultScanner rs = table.getScanner(scan);
You can create your own Filter and implement the method filterRowKey. To make scan more faster you can also implement the method getNextKeyHint, but this is a bit complicated. The disadvantage of this approach is that you need to put jar file with your filter into the HBase classpath and restart cluster.
This approximate implementation of this filter.
#Override
public void reset() {
this.filterOutRow = false;
}
#Override
public Filter.ReturnCode filterKeyValue(KeyValue v) {
if(this.filterOutRow) {
return ReturnCode.SEEK_NEXT_USING_HINT;
}
return Filter.ReturnCode.INCLUDE;
}
#Override
public boolean filterRowKey(byte[] data, int offset, int length) {
if(startDate < getDate(data) && endDate > getDate(data)) {
this.filterOutRow = true;
}
return this.filterOutRow;
}
#Override
public KeyValue getNextKeyHint(KeyValue currentKV) {
if(getDate(currentKV) < startDate){
String nextKey = getId(currentKV)+","+startDate.getTime();
return KeyValue.createFirstOnRow(Bytes.toBytes(nextKey));
}
if(getDate(currentKV) > endDate){
String nextKey = (getId(currentKV)+1)+","+startDate.getTime();
return KeyValue.createFirstOnRow(Bytes.toBytes(nextKey));
}
return null;
}
#Override
public boolean filterRow() {
return this.filterOutRow;
}
store the key of the very first row somewhere. it will always be there in your final resultset, being the 'first' row, which makes it older than all other rows(am i correct??)
now take the date, which you want to use to filter out the results and create a RowFilter with RegexStringComparator using this date. this will give the row matching the specified criteria. now, using this row and the first row, which you had store earlier, do a range query.
and if you have multiple rows having the same date, say:
10,2012-05-04,"some details"
10,2012-05-04,"some new details"
take the last row, which you would have got after the RowFilter, and use the same technique.
HTH
i was trying to say that you can use range query to achieve this. where the "startrowkey" will be the first row of your table. being the first row it'll always be the oldest row which means you will always have this row in your result. and the "stoprowkey" for your range query will be the row which contains the given date. to find the stoprowkey you can set a "RowFilter" with "RegexStringComparator".
byte[] startRowKey = FIRST_ROW_OF_THE_TABLE;
Scan scan = new Scan();
Filter rowFilter = new RowFilter(CompareFilter.CompareOp.EQUAL,new RegexStringComparator("YOUR_REGEX"));
scan.setFilter(filter);
ResultScanner scanner1 = table.getScanner(scan);
for (Result res : scanner1) {
byte[] stopRowKey = res.getRow();
}
scanner1.close();
scan.setStartRow(startRowKey);
scan.setStopRow(stopRowKey);
ResultScanner scanner2 = table.getScanner(scan);
for (Result res : scanner2) {
//you final result
}
I have been reading and searching for quite some time and can't seem to wrap my head around how to use Lucene in my Java program that contains a jTable.
What I want to be able to do is search the table when submitting a new row entry. Do I simply create a TableModel from my jTable and pass it into the TableSearcher constructor if I include the 3.3 Lucene jar file in my path? I have included some of my code...please, I welcome any direction! Thanks.
Here is my method for populating my jTable from data stored in vectors:
...
public static boolean hasSearchResults = false;
public String selectedRequirementName;
public TableSearcher ts;
DefaultTableModel sc;
public TablePanel(int z, String name, String reason) { //pulls in panel number, project name, and whether the project was new or opened, from the MainGUI class
initComponents();
sc=(DefaultTableModel) reqTable.getModel();
ts = new TableSearcher(sc);
aProject = new Project(reason, name); //calls Project class to control the project
try{
requirementsVector = new Vector(aProject.getRequirementsList());
requirementsList =new String[requirementsVector.size()];
for(int i=0; i < requirementsVector.size(); i++){
requirementsList[i] = requirementsVector.get(i).getName();
System.out.println(requirementsList[i]);
sc.addRow(new Object[]{
requirementsVector.get(i).getName(),
requirementsVector.get(i).getDefinition(),
requirementsVector.get(i).getType(),
requirementsVector.get(i).getPriority(),
requirementsVector.get(i).getAssigned(),
requirementsVector.get(i).getDue(),
requirementsVector.get(i).getStatus()});
//this.editingProjectName = name;
}
}catch(NullPointerException e1){
System.out.println(e1);
} ....
Here is my code that inserts a new row into the jTable:
private void ConfirmActionPerformed(java.awt.event.ActionEvent evt) {
String ReqName = nameTextField.getText();
String ReqDescription = descriptionTextField.getText();
String Type = (String)jType.getSelectedItem();
String Priority = (String)PriorityComboBox.getSelectedItem();
String Assigned = (String)jDateAssignedMonth.getSelectedItem() + "/" + (String)jDateAssignedDay.getSelectedItem() + "/" + (String)jDateAssignedYear.getSelectedItem();
String Due = (String)jDateDueMonth.getSelectedItem() + "/" + (String)jDateDueDay.getSelectedItem() + "/" + (String)jDateDueYear.getSelectedItem();
String Status = (String)jStatus.getSelectedItem();
// search string pass to TableSearcher
ts.search(ReqDescription);
if (editingaRow == false && !hasSearchResults){
sc.addRow(new Object[]{
ReqName,ReqDescription,Type,Priority,Assigned, Due, Status
});
requirementsVector.add(new Requirement(ReqName, ReqDescription, Type, Priority, Assigned, Due,Status));
aProject.saveRevision(requirementsVector, name);
}else if (editingaRow == true){
sc.setValueAt(ReqName,selectedRow,0);
sc.setValueAt(ReqDescription,selectedRow,1);
sc.setValueAt(Type,selectedRow,2);
sc.setValueAt(Priority,selectedRow,3);
sc.setValueAt(Assigned,selectedRow,4);
sc.setValueAt(Due,selectedRow,5);
sc.setValueAt(Status,selectedRow,6);
requirementsVector.setElementAt(new Requirement(ReqName, ReqDescription, Type, Priority, Assigned, Due,Status),(selectedRow));
aProject.saveRevision(requirementsVector, name);
editingaRow = false;
}
disableRequirementEditor();
newReq.setEnabled(true);
reqTable.clearSelection();
}
And here is the TableSearcher model that I am using (I added new functionality to the search method). What is happening is when I enter a new entry, the search finds that entry as a duplicate and returns it in my jFrame I implement within search method of the TableSearcher. This only happens with a unique entry that has no match in the indexed table. If there is a search result in the index that matches my new entry, then only the existing entry displays in my jFrame, not the new one I am attempting.
// provided by Jonathan Simon <jonathan_s_simon#yahoo.com>
class TableSearcher extends AbstractTableModel {
/**
* The inner table model we are decorating
*/
protected TableModel tableModel;
/**
* This listener is used to register this class as a listener to
* the decorated table model for update events
*/
private TableModelListener tableModelListener;
/**
* these keeps reference to the decorated table model for data
* only rows that match the search criteria are linked
*/
private ArrayList rowToModelIndex = new ArrayList();
//Lucene stuff.
/**
* In memory lucene index
*/
private RAMDirectory directory;
/**
* Cached lucene analyzer
*/
private Analyzer analyzer;
/**
* Links between this table model and the decorated table model
* are maintained through links based on row number. This is a
* key constant to denote "row number" for indexing
*/
private static final String ROW_NUMBER = "ROW_NUMBER";
/**
* Cache the current search String. Also used internally to
* key whether there is an active search running or not. i.e. if
* searchString is null, there is no active search.
*/
private String searchString = null;
/**
* #param tableModel The table model to decorate
*/
public TableSearcher(TableModel tableModel) {
analyzer = new WhitespaceAnalyzer();
tableModelListener = new TableModelHandler();
setTableModel(tableModel);
tableModel.addTableModelListener(tableModelListener);
clearSearchingState();
}
/**
*
* #return The inner table model this table model is decorating
*/
public TableModel getTableModel() {
return tableModel;
}
/**
* Set the table model used by this table model
* #param tableModel The new table model to decorate
*/
public final void setTableModel(TableModel tableModel) {
//remove listeners if there...
if (this.tableModel != null) {
this.tableModel.removeTableModelListener(tableModelListener);
}
this.tableModel = tableModel;
if (this.tableModel != null) {
this.tableModel.addTableModelListener(tableModelListener);
}
//recalculate the links between this table model and
//the inner table model since the decorated model just changed
reindex();
// let all listeners know the table has changed
fireTableStructureChanged();
}
/**
* Reset the search results and links to the decorated (inner) table
* model from this table model.
*/
private void reindex() {
try {
// recreate the RAMDirectory
directory = new RAMDirectory();
IndexWriter writer = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
// iterate through all rows
for (int row=0; row < tableModel.getRowCount(); row++){
//for each row make a new document
Document document = new Document();
//add the row number of this row in the decorated table model
//this will allow us to retrive the results later
//and map this table model's row to a row in the decorated
//table model
document.add(new Field(ROW_NUMBER, "" + row, Field.Store.YES, Field.Index.ANALYZED));
//iterate through all columns
//index the value keyed by the column name
//NOTE: there could be a problem with using column names with spaces
for (int column=0; column < tableModel.getColumnCount(); column++){
String columnName = tableModel.getColumnName(column);
String columnValue = String.valueOf(tableModel.getValueAt(row, column)).toLowerCase();
document.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.ANALYZED));
}
writer.addDocument(document);
}
writer.optimize();
writer.close();
} catch (Exception e){
e.printStackTrace();
}
}
/**
* #return The current lucene analyzer
*/
public Analyzer getAnalyzer() {
return analyzer;
}
/**
* #param analyzer The new analyzer to use
*/
public void setAnalyzer(Analyzer analyzer) {
this.analyzer = analyzer;
//reindex from the model with the new analyzer
reindex();
//rerun the search if there is an active search
if (isSearching()){
search(searchString);
}
}
/**
* Run a new search.
*
* #param searchString Any valid lucene search string
*/
public void search(String searchString){
// to store row numbers of results rows to display later
Vector<String> rowNums = new Vector();
//if search string is null or empty, clear the search == search all
if (searchString == null || searchString.equals("")){
clearSearchingState();
fireTableDataChanged();
return;
}
try {
//cache search String
this.searchString = searchString;
//make a new index searcher with the in memory (RAM) index.
IndexSearcher is = new IndexSearcher(directory);
//make an array of fields - one for each column
String[] fields = new String[tableModel.getColumnCount()];
for (int t=0; t<tableModel.getColumnCount(); t++){
fields[t]=tableModel.getColumnName(t);
}
//build a query based on the fields, searchString and cached analyzer
//NOTE: This is an area for improvement since the MultiFieldQueryParser
// has some weirdness.
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
Query query = parser.parse(searchString);
//run the search
Hits hits = is.search(query);
for (int t=0; t<hits.length(); t++){
Document document = hits.doc(t);
Fieldable field = document.getField(ROW_NUMBER);
// adding row numbers to vector
rowNums.add(field.stringValue());
}
// trying to display search results in new table
if(!rowNums.isEmpty()){
TablePanel.hasSearchResults = true;
for (int v=0; v<rowNums.size(); v++){
System.out.println("Match in row number " + rowNums.elementAt(v));
}
JFrame frame = new JFrame("Possible Duplicates");
String colNames[] = {"Name", "Definition", "Type", "Priority", "Date Assigned", "Due Date", "Status"};
DefaultTableModel dtm = new DefaultTableModel(null,colNames);
for (int r = 0; r<rowNums.size(); r++){
String ReqName = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 0);
String ReqDescription = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 1);
String Type = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 2);
String Priority = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 3);
String Assigned = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 4);
String Due = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 5);
String Status = (String) tableModel.getValueAt(Integer.parseInt(rowNums.elementAt(r)), 6);
dtm.addRow(new Object[]{
ReqName,ReqDescription,Type,Priority,Assigned, Due, Status
});
}
JTable tblResults = new JTable(dtm);
JScrollPane sp = new JScrollPane(tblResults);
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(900,300));
panel.add(sp,BorderLayout.CENTER);
panel.add(new JLabel("Possible Duplicates",JLabel.CENTER),BorderLayout.SOUTH);
JOptionPane.showConfirmDialog(null,panel);
}
//reset this table model with the new results
resetSearchResults(hits);
} catch (Exception e){
e.printStackTrace();
}
//notify all listeners that the table has been changed
fireTableStructureChanged();
}
/**
*
* #param hits The new result set to set this table to.
*/
private void resetSearchResults(Hits hits) {
try {
//clear our index mapping this table model rows to
//the decorated inner table model
rowToModelIndex.clear();
//iterate through the hits
//get the row number stored at the index
//that number is the row number of the decorated
//tabble model row that we are mapping to
for (int t=0; t<hits.length(); t++){
Document document = hits.doc(t);
Fieldable field = document.getField(ROW_NUMBER);
rowToModelIndex.add(new Integer(field.stringValue()));
System.out.println("Something " + rowToModelIndex.add(new Integer(field.stringValue())));
clearSearchingState();
}
} catch (Exception e){
e.printStackTrace();
}
}
private int getModelRow(int row){
return ((Integer) rowToModelIndex.get(row)).intValue();
}
/**
* Clear the currently active search
* Resets the complete dataset of the decorated
* table model.
*/
private void clearSearchingState(){
searchString = null;
rowToModelIndex.clear();
for (int t=0; t<tableModel.getRowCount(); t++){
rowToModelIndex.add(new Integer(t));
}
}
// TableModel interface methods
public int getRowCount() {
return (tableModel == null) ? 0 : rowToModelIndex.size();
}
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
}
public String getColumnName(int column) {
return tableModel.getColumnName(column);
}
public Class getColumnClass(int column) {
return tableModel.getColumnClass(column);
}
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(getModelRow(row), column);
}
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(getModelRow(row), column);
}
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, getModelRow(row), column);
}
private boolean isSearching() {
return searchString != null;
}
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not searching, just pass the event along.
if (!isSearching()) {
clearSearchingState();
reindex();
fireTableChanged(e);
return;
}
// Something has happened to the data that may have invalidated the search.
reindex();
search(searchString);
fireTableDataChanged();
return;
}
}
It looks like your code doesn't index the table data with Lucene. One easy way to do this is to make your own table model that indexes internally, with an exposed search function that you can connect to limit the data displayed. This is what I wrote about in Swing Hacks a few years back.
Without the indexing, Lucene won't just automatically 'work' because it's in your classpath.
Jonathan
take a look at the very simple example
in your case, you would do something like this to create the document, that would get saved in the index.
this code is not complete or necessarily error free,; but is more of a starting point to get you going
Document doc = new Document();
doc.add(new Field("ReqName", ReqName, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("ReqDescription", ReqDescription, Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("Type", Type, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("Priority", Priority, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("Assigned", Assigned, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("Due", Due, Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("Status", Status, Field.Store.YES, Field.Index.NOT_ANALYZED));
writer.addDocument(doc);
writer.close();