Let's say i have a listbox that contain ten items, and then i set five items for every page, so now the listbox have two pages
and the problem is everytime i want to get the value in listbox it only get five items instead ten items.
im using ListItemRenderer on My Listbox
below is my code :
AnnotationConfiguration config = new AnnotationConfiguration();
SessionFactory sessionFactory = config.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
String str = "from Users";
Query q = session.createQuery(str);
List<Users> user = q.list();
session.close();
sessionFactory.close();
list.setModel(new ListModelList<Users>(user));
list.setItemRenderer(new ListitemRenderer() {
#Override
public void render(Listitem item, Object data, int index)
throws Exception {
Users user = (Users) data;
item.setValue(user);
new Listcell(user.getUsername()).setParent(item);
new Listcell(user.getUserrole()).setParent(item);
}
});
}
below my code to get the value :
String name ="";
String role ="";
Users user = new Users();
Listbox box = (Listbox) list.getFellow("win").getFellow("list");
List<Listitem> lists = box.getItems();
//membaca setiap row yang ada pada list
for(Listitem currentList : lists){
List<Component> com = currentList.getChildren();
//membaca setiap column pada row
for (Component currentComp : com){
Listcell lc = (Listcell) currentComp;
if(lc.getColumnIndex() == 0){
name = lc.getLabel();
System.out.println("name = " + name);
}
if(lc.getColumnIndex()==1){
role = lc.getLabel();
System.out.println("role = " + role);
}
}
}
This is the correct behavior. The List is the View and the View
never has more then 5 Items as you discribed.
You want to get the Model so get the Model.
ListModelList lists = (ListModelList)box.getModel();
Related
I am trying to get all users from my active directory however my code is returning just one row. I have tried the below which is currently only outputting one user.
private void getUserBasicAttributes(String username, LdapContext ctx) {
try {
List<String> usersList = new ArrayList<String>();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
//First input parameter is search bas, it can be "CN=Users,DC=YourDomain,DC=com"
//Second Attribute can be uid=username
NamingEnumeration<SearchResult> answer = ctx.search("DC=domain,DC=com", "(&(objectCategory=user))"
, constraints);
if (answer.hasMoreElements()) {
Person person = new Person();
SearchResult attrs = ((SearchResult) answer.next());
String names[] = attrs.getName().split(",");
String name[] = names[0].split("=");
usersList.add(name[1]);
}else{
throw new Exception("Invalid User");
}
System.out.println(usersList.size());
} catch (Exception ex) {
ex.printStackTrace();
}
}
You are not looping over all the results, add a while loop inside the if
if (answer.hasMoreElements()) {
while(answer.hasMoreElements()) {
Person person = new Person();
SearchResult attrs = ((SearchResult) answer.next());
String names[] = attrs.getName().split(",");
String name[] = names[0].split("=");
usersList.add(name[1]);
}
}else{
throw new Exception("Invalid User");
}
You need while instead of if:
while (answer.hasMoreElements()) {
Person person = new Person();
SearchResult attrs = ((SearchResult) answer.next());
String names[] = attrs.getName().split(",");
String name[] = names[0].split("=");
usersList.add(name[1]);
}
if (usersList.size() == 0) {
throw new Exception("Invalid User");
}
You can simplify the name-element handling as well. No need to parse the DN. Just specify the attribute(s) you want returned up front and retrieve them directly.
You are making this too hard. No reason to perform any "splitting" pf values.
// Specify the ids of the attributes to return
String[] attrIDs = { "uid" };
// Get ONLY the attributes desired
Attributes answer = ctx.getAttributes("CN=Users,DC=YourDomain,DC=com", attrIDs);
for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) {
Attribute attr = (Attribute)ae.next();
System.out.println("attribute: " + attr.getID());
/* Print each value */
for (NamingEnumeration e = attr.getAll(); e.hasMore();
System.out.println(e.next()))
;
}
Let me know how I can help.
I have a value in excel and checking the existence in array of elements in drop down. Where the condition passes, I want to store that and click. I tried to store it in a string but, it is not clickable. I tried to store in a web element but failed. kindly help.
List<WebElement> countrylist = driver.findElements(By.cssSelector("ul.ui-multiselect-checkboxes li label[for*='ddlBU'] span"));
List<String> all_countrylist = new ArrayList<>();
Thread.sleep(1000);
String selectedcountry = driver.findElement(By.xpath("html/body/div[9]/ul/li[2]/label/span")).getText();
WebElement clickselectedcountry = driver.findElement(By.xpath("html/body/div[9]/ul/li[2]/label/span"));
Thread.sleep(1000);
for(int cui = 0; cui < countrylist.size(); cui++)
{
all_countrylist.add(countrylist.get(cui).getText());
if((countrylist.get(cui).getText()).equalsIgnoreCase(countrysheet.getCell(0, 2).getContents()))
{
System.out.println("the Country " + (countrysheet.getCell(0, 2).getContents()) + " which is existing");
String clickcountry = (countrylist.get(cui).getText());
}
else
{
System.out.println("\nSelected Country " + (countrysheet.getCell(0, 2).getContents()) + " which is not existing");
}
}
Try below code.
String countryToBeSelected = countrysheet.getCell(0, 2).getContents();
By selectedCountryLocator = By.xpath("html/body/div[9]/ul/li[2]/label/span");
String selectedcountry=driver.findElement(selectedCountryLocator).getText();
//If Country is other than selected country, then click and open the list
if(!countryToBeSelected.equals(selectedcountry)){
WebElement clickselectedcountry=driver.findElement(selectedCountryLocator);
clickselectedcountry.click();
//Get List Of All Countries In WebElement List
List<WebElement> countrylist = driver.findElements(By.cssSelector("ul.ui-multiselect-checkboxes li label[for*='ddlBU'] span"));
//Store all country details in list
List<String> all_countrylist=new ArrayList<String>();
//Iterate over WebElement list and store country values in string list
for(WebElement country : countrylist){
all_countrylist.add(country.getText());
}
//Get the expected country index
int elementIndex = all_countrylist.indexOf(countryToBeSelected);
//Click on After finding the Country Index
countrylist.get(elementIndex).click();
}
I have a list of Objects which is filled dynamically and I want to keep only the last duplicated Object. I tried the HashSet to remove duplicates but it's not doing big thing in my case.Can anyone help with this ?
My User Object shown below:
public class User {
public int id,score
public String firstName, lastName;
Getters and Setters ...
}
class getLasDuplicate {
public static void main(String[] args) {
List<User> a = new ArrayList<User>();
User u = new User();
u.setId(1);
u.setScore(2);
u.setFirstName("Mike");
u.setLastName("Jordon");
a.add(u);
User u = new User();
u.setId(1);
u.setScore(3);
u.setFirstName("Mike");
u.setLastName("Jordon");
a.add(u);
User u = new User();
u.setId(1);
u.setScore(4);
u.setFirstName("Mike");
u.setLastName("Jordon");
a.add(u);
User u = new User();
u.setId(2);
u.setScore(3);
u.setFirstName("kaos");
u.setLastName("family");
a.add(u);
User u = new User();
u.setId(1);
u.setScore(3);
u.setFirstName("Mike");
u.setLastName("Jordon");
a.add(u);
User u = new User();
u.setId(2);
u.setScore(2);
u.setFirstName("kaos");
u.setLastName("family");
a.add(u);
for(User us: a){
System.out.println( "Name:"+us.getFirstName +" "+us.getLastName+", Score:"+us.getScore()+", Id:"+us.getId());
}
}
In this case I want to find by Id the duplicated Objects and get only the last Object of duplicated ones in the List, so if I print the final List content I want to have something like this:
Name: Mike Jordon, Score: 3, Id: 1
Name: kaos family, Score: 2, Id: 2
If List is your input and you want to get last duplicates, you can try converting it to Map and change it back to List again as below:
Map<Integer, User> amap = new HashMap<Integer, User>();
for(User i: a){
amap.put(i.getId(), i); //when duplicate User with same Id is added, new User value will replace old one.
//So Id will always be mapped to last User with that Id
}
List<User> newA = new ArrayList(amap.values());
Then printing newA should give you intended result.
I am having a lot of trouble iterating through all my records. Perhaps, by reading my code someone could help.
private String saveData(Handle handle, String username, String name, String prof, String table) {
String sqlCommand;
Map<String, Object> userResults;
for (Integer tableNum = 1; tableNum < 5; tableNum++) {
//query all tables
sqlCommand = String.format("SELECT varname FROM s" + tableNum.toString());
userResults = handle.createQuery(sqlCommand)
.bind("username", username)
.first();
//attempt to ierate all records
for (Map.Entry<String, Object> entry : userResults.entrySet()) {
Object obj = entry.getValue(); // doesnt have .get(string) as below
}
//get the desired field
logger.debug("Results: " + userResults.toString());
String varname = (String) userResults.get("varname");
if ((varname.toLowerCase()).matches(name.toLowerCase()))
return "";
}
//save data
return name;
}
How do I iterate through each record of the table?
You say this works for row1. You cannot go to the next row as there is .first(); in your handle and you have not tried to fetch next record. Modify your query - the documentation here says you can use .list(maxRows);
I am new to programming world, and i love it.
I have some problem on Query.Filter Operator by different roles.
Admin - Admin can view all leave history
Supervisor - Supervisor can view own and all employee under he/she
Employee - Employee only able to view own leave history
From the testing i has done. Admin and Employee is working fine and the problem I has faced is Supervisor, Supervisor able to view employee under he/she but unable to view own leave history.
here are part of the code, appreciate anyone can help me. Thank you
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
log.debug(ViewHistory.class);
DataTableModel dataTableModel = DataTablesUtility.getParam(request);
String regionSelected = request.getParameter("cri_region");
String sEcho = dataTableModel.sEcho;
int iTotalRecords = 0; // total number of records (unfiltered)
int iTotalDisplayRecords = 0; //value will be set when code filters companies by keyword
JsonArray data = new JsonArray(); //data that will be shown in the table
String emailAddress = (String)request.getSession().getAttribute("emailAdd");
Boolean isAdmin = false;
Boolean isSupervisor = false;
AdministratorService as = new AdministratorService();
for(Administrator admin : as.getAdministrators()){
if(admin.getEmailAddress().equalsIgnoreCase(emailAddress)){
isAdmin = true;
}
}
SupervisorService ss = new SupervisorService();
for(Supervisor s : ss.getSupervisors()){
if(s.getEmailAddress().equalsIgnoreCase(emailAddress)){
isSupervisor = true;
}
}
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query q = new Query(History.class.getSimpleName());
// only admin can view all leave history
if(!isAdmin && !isSupervisor){
Filter emailFilter = new FilterPredicate("emailAdd",
FilterOperator.EQUAL,
emailAddress);
Filter regionFilter = new FilterPredicate("region",
FilterOperator.EQUAL,
StringUtils.defaultString(regionSelected, "Singapore"));
Filter filter = CompositeFilterOperator.and(emailFilter, regionFilter);
q.setFilter(filter);
}
else if(!isAdmin && isSupervisor){
List<String> list = new ArrayList<String>();
EmployeeService es = new EmployeeService();
for(Employee emp : es.getEmployees()){
if(emailAddress.equalsIgnoreCase(emp.getSupervisor())){
list.add(emp.getEmailAddress());
}
}
// if some one under this supervisor
if(list != null && !list.isEmpty()){
Filter filter = new FilterPredicate("emailAdd",
FilterOperator.IN,
list);
q.setFilter(filter);
}
else{
// if not one under this supervisor , put update it self to avoid illegal argument
Filter filter = new FilterPredicate("emailAdd",
FilterOperator.EQUAL,
emailAddress);
q.setFilter(filter);
}
}
List<History> historyList = new LinkedList<History>();
List<History> entityList = new LinkedList<History>();
EDIT: Updated suggestion.
If currently for a supervisor you are able to correctly get the list of all employees who have him as the supervisor, then just add the supervisor's email also to the list which you will be using as a filter for querying leave history. So after finding the list of employee emails, also add:
list.add(emailAddress); //since emailAddress will be the email of the supervisor