Code Not Getting Invoked After Loop Statement - java

In my jsf page I am calling a method called saveinsert and in my saveInsert method I have the following code.
try {
System.out.println("rchd 1");
for (Employees items : editCellItems) {
System.out.println("rchd 2");
items.setEmpId(empBean.getEmployeesId());
System.out.println("after assigning "+items.getEmployeesId());
} catch (Exception e) {
System.out.println("exception "+e.getMessage());
e.printStackTrace();
}
where editCellItems is declared like
List<Employees> editCellItems= new ArrayList<Employees>();
and empBean is declared like this
Employees empBean= new Employees();
My problem is when I run my jsf page rchd 2 and code after that is not getting invoked.
What could be the reason?

Make sure you add values into editCellItems using the List<?> add() meothod. Also When doing a for each loop make sure you do not add or remove items or you will get an Exception.
e.g.:
editCellItems.add(empBean);
edit: Also If you only have 1 element in your editCellItems, you might not want to use a list unless you are adding more,

If no objects are in editCellItems, then it will iterate through the for loop 0 times. Therefore, you need to add some objects first:
editCellItems.add(empBean);

Related

Selenium select class does NOT throw error when it does not find item in the drop down list

I have method to select the item by visible text using Select class. The item I am passing in the parameter is not in the list. I want the test to fail and give me the error no such element found, but the selenium keeps on waiting for the item to appear and does not fail. Is there a way to forcefully fail the test and print the exception.
public static void selectAnItem(String elemetLocator, String itemToSelect){
Select select = new Select(driver.findElement(By.xpath(elemetLocator)));
try {
select.selectByVisibleText(itemToSelect);
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is that you are eating the exception with the try-catch. If you remove that, it should throw the error you are expecting.
One suggestion... rather than passing in a String elementLocator, pass in a By class. That will allow you to use more than just XPaths, e.g.
public static void selectAnItem(By locator, String itemToSelect)
{
new Select(driver.findElement(locator)).selectByVisibleText(itemToSelect);
}
Now you can use By.id(), By.cssSelector(), and so on.

Java/Eclipse: Remove ArrayList element at specified index

I'm not sure if this is a duplicat or not (it probably is) but I can't find what I'm looking for.
I have a static ArrayList holding objects created from a constructor in that class, or any class extending it:
public static ArrayList<Person> PersonList = new ArrayList<>();
public Constructor(....){
PersonList.add(this);
}
Now I'm trying to delete objects from this arraylist by using index, but I'm getting ArrayIndexOutOfBounds: Array index out of range: (index).
Now I know this error is telling me there is no element in the specified position, but then I don't understand why PersonList.size() returns 4 (if there are 4 elements in the list).
I'm new to java, so I hope anyone here can help me. Here's the code:
list.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
if(SwingUtilities.isRightMouseButton(arg0)) {
try {
Person.PersonList.remove(list.getSelectedIndex());
list.remove(list.getSelectedIndex());
}catch (Exception e) {
System.out.println(e);
}
System.out.println("Index: " + list.getSelectedIndex());
updateData();
}
}
});
I'm confused by this:
public Constructor(....){
PersonList.add(this);
}
It looks like every time you create a new object of that class (a Person I'm assuming) you are adding it to a class variable list. I'm assuming that every time you create a new instance of that class, it's resetting the global list. Can you confirm that PersonList is not always size = 1? I'm suspecting it is, so move that list to a different class
Okay so after testing a little it seems it works just fine after all. It throws an error telling me its out of bounds, but after updating the .size() after each deletion, it decreases.
Though I have no clue why it works if it tells me it doesn't?

JComboBox error when items are added

I try to add some items to a JComboBox and I receive a NullPointerException error.
This is a sample of my code :
public adminPanel() {
fillComboTeacher();
initComponents();
}
public void fillComboTeacher(){
HashSet<Person> set = cont1.returnTeachers();
Iterator it = set.iterator();
try {
while (it.hasNext()) {
Person p = (Person) it.next();
String name = p.getName();
comboTeacher.addItem(name);
}
} catch (Exception e) {
System.out.println(e);
}
}
Person class - name, state (with getters and setters)
returnTeachers() - returns a HashSet containing Persons with state = "Teacher"
I don't understand why I'm receiving this error and why I can't fill the ComboBox, I followed a tutorial step-by-step and something is still not well.
Thanks!
You are calling fillComboTeacher before calling initComponents.
Looking at the method's name, I assumed that you initialized comboTeacher in the latter.
So at that point (comboTeacher.addItem(name);), comboTeacher is not yet initialized and hence the NullPointerException.
To fix this, just swap the two method calls in the constructor to initialize your components before trying to use them.
Few notes:
A NullPointerException is often easy to fix. Just look at the stacktrace (it indicates the line where the NPE occurs) and see what can be null and why at this line.
Don't use a raw iterator, but a generic one (Iterator<Person> it = set.iterator();), that will avoid you to cast the object returned by a next() call.
Since you are only reading the elements in the set, you can simply use a for-each loop for(Person p : cont1.returnTeachers()) comboTeacher.addItem(p.getName());

How to workaround readObject similar to readLine

I am reading a file which contain many serialized objects.
I want to deserialize them back and realized that we cannot use readObject like readLine ie
while (ois.readObject != null) {
}
would throw an exception. We also dont have hasNext and next sort of mechanism in place from my knowledge.
How is the problem of reading object fixed in real world ?
Catch EOFException, and close and break when you get it.
readObject() only returns null if you wrote a null, and that doesn't have to imply the end of the stream.
Assuming you're trying to load Person objects, you could try something like:
ArrayList<Person> persons = new ArrayList();
while (true) {
try {
persons.add((Person) ois.readObject());
} catch (EOFException e) {
break;
}
}
Or instead of serializing the individual object, you could add your objects to an array or arraylist and serialize the list object. Then you can easily deserialize the list object and you won't have to deal with EOFException. See the example in John Purcell's serialization tutorial.

How to track an object inside an ArrayList becoming null?

The structure that I have is:
Map<String, ArrayList<Bean>>
This Arraylist is modified (added/removed) from different locations within different threads.
At times, some bean inside the ArrayList is becoming null. How can I track when it becomes null? I want to track what makes the bean null, to fix the bug.
This happens when the scenario is tested with a huge data set.
Here's the exact code that's failing:
for (int i = 0; i < eventlogs.size(); i++) {
MessageEventLogBean msgEventLogBean = (MessageEventLogBean) eventlogs.get(i);
eventlogs.remove(i);
try {
logWriter.write(msgEventLogBean, context);
} catch (FusionException e) {
logger.error("Error While writing the event log bean ", e);
}
}
Instead of a standard list implementation, use an anonymous class that overrides the add method and adds special code to check if the added object is null, like this:
List<T> list = new ArrayList<T>() {
public boolean add(T e) {
if (e == null) {
throw new NullPointerException("Attempt to add null to list");
}
return super.add(e);
}
};
You should similarly override all "add" methods to be sure. When code adds a null, it will explode and you will see the exception in the log and be able to see who did it be examining the stacktrace.
EDITED
To be clear, it is impossible for an object in a List to "become null". You can add a null, or you can remove an object from the List, but an object already in the List will stay there until removed.
To be clear, the only way for a null to get in the list is by putting it there - ie adding it via one of the add() methods or the addAll() method. Concurrent modification issues can not cause this issue (you may get a ConcurrentModificationException, but that still won't put a null in there).
Code such as
Object o = list.get(1);
o = null;
has no effect because you're just nulling a copy of the reference to the object - list still a reference to the object.
However, depending on the design of the Bean objects, they might be mutable. While the reference to the Bean object would remain intact, it might be possible for some of the fields within the Bean to become null. To catch this, you would need to code the setters to explode when given a null argument, either by re-writing the class, or by overloading the setters via an anonymous class (similar to my initial suggestion above).
It's a bit of work, but you can create your own List interface implementation that delegates all methods to the ArrayList. In the accessor method where you would normally return the ArrayList, instead return your debug implementation with the ArrayList wrapped inside of it. Then just set a breakpoint on your set method, and you'll know exactly what code is calling set on the ArrayList.
Perhaps this is what you intended
private final Queue<MessageEventLogBean> eventlogs = new ConcurrentLinkedQueue<>();
// this loop stops when it runs out of objects.
MessageEventLogBean msgEventLogBean;
while ((msgEventLogBean = eventlogs.poll()) != null) {
try {
logWriter.write(msgEventLogBean, context);
} catch (FusionException e) {
logger.error("Error While writing the event log bean ", e);
}
}
or
// this loops until the thread is interrupted
private final BlockingQueue<MessageEventLogBean> eventlogs = new LinkedBlockingQueue<>();
while (true) {
MessageEventLogBean msgEventLogBean = eventlogs.take();
try {
logWriter.write(msgEventLogBean, context);
} catch (FusionException e) {
logger.error("Error While writing the event log bean ", e);
}
}
Both options are thread safe.
You can override the add() and set() methods for the list so that null is invalid and throws an exception.
List<MyType> list = new ArrayList<MyType>() {
public boolean add(MyType mt) {
if(mt == null) throw new IllegalArgumentException();
super.add(mt);
}
};
Consider the following code
String a = "hi"; // a => "hi"
String b = a; // a => "hi" and b => "hi"
a = null; // a => null and b => "hi"
String a is a reference to a String and when you assign null to it you change just the value of a and other references to the same object are unaffected.
A way to process every second entry, or why using remove(i) is unlikely to be what you want.
List<Integer> list = new ArrayList<>();
for(int i=0;i<10;i++) list.add(i);
for(int i=0;i<list.size();i++) {
System.out.println(list.get(i));
list.remove(i);
}
prints
0
2
4
6
8

Categories

Resources