StackOverflowError in equals method of bidirectional objects - java

I have to objects Client and Order and these objects are living in bidirectional relation and I try to write them to file, but I get StackOverflowError. I got this error because my equals methods are looped.
My classes which I try to serialize:
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public class Client implements Serializable {
private Long id;
private String name;
private List<Order> orders = new ArrayList<>();
public void addOrder(Order order) {
order.setClient(this);
orders.add(order);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Client client = (Client) o;
if (id != null ? !id.equals(client.id) : client.id != null) return false;
if (name != null ? !name.equals(client.name) : client.name != null) return false;
return orders != null ? orders.equals(client.orders) : client.orders == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (orders != null ? orders.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Client{" +
"id=" + id +
", name='" + name + '\'' +
// ", orders=" + orders.size() +
'}';
}
}
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public class Order implements Serializable {
private Long id;
private String name;
private Client client;
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Order order = (Order) o;
if (id != null ? !id.equals(order.id) : order.id != null) return false;
if (name != null ? !name.equals(order.name) : order.name != null) return false;
return client != null ? client.equals(order.client) : order.client == null;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (client != null ? client.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "Order{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
#Data
#AllArgsConstructor
public class MapDataSource implements Serializable {
private final Map<Date, List<Client>> clients = new HashMap<>();
private final Map<Date, List<Order>> orders = new HashMap<>();
}
#Slf4j
public class ObjectWriter {
private final String fileName = "data.obj";
public void write(String fileName, MapDataSource mapDataSource) {
try (
FileOutputStream fs = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fs)
) {
oos.writeObject(mapDataSource);
log.info("Object has been written.");
} catch (IOException ioe) {}
}
}
#Slf4j
public class ObjectReader {
private static final String fileName = "data.obj";
public MapDataSource readObj(String fileName) {
MapDataSource mapDataSource = null;
try (
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis)
) {
mapDataSource = ((MapDataSource) ois.readObject());
// log.info("Read object: {}", mapDataSource);
} catch (IOException ioe) {
} catch (ClassNotFoundException classEx) {
System.out.println();
}
return mapDataSource;
}
}
And when I try to run code below I get StackOVerflowError:
String testFile = "testFile.obj";
final DateTime time = new DateTime(2017, 12, 1, 10, 0);
final Client client1 = new Client(1L, "Client1", new ArrayList<>());
final Order order1 = new Order(1L, "Order1", null);
final MapDataSource mapDataSource = new MapDataSource();
mapDataSource.getClients().put(time.toDate(), new ArrayList<>());
mapDataSource.getClients().get(time.toDate()).add(client1);
mapDataSource.getOrders().put(time.toDate(), new ArrayList<>());
mapDataSource.getOrders().get(time.toDate()).add(order1);
new ObjectWriter().write(testFile, mapDataSource);
final MapDataSource found = new ObjectReader().readObj(testFile);
System.out.println(found);
Solution:
MapDataSource needs to have implemented equals() and hashcode() methods.

It seems like you need to sit down and seriously consider what it should even mean for two clients or orders to be equal in the first place. The Long id; makes me wonder whether you should really be comparing the object graphs in the first place. If e.g. clients have unique IDs, then it could make sense to just ensure that clients are unique object instances and then you do away with the problem entirely.
If you really do need to compare object graphs, you could use something like the following. We use an IdentityHashMap to record all of the objects we've seen, then if we detect a cycle, we just compare the previously-stored counter values which tells us if the two graphs have the same cycle.
Client and Order need to share code (so the maps can be passed around), so you just override equals in both to return ClientOrderEquality.equals(this, that).
import java.util.*;
public final class ClientOrderEquality {
private ClientOrderEquality() {}
private static final class Counter { long value; }
public static boolean equals(Client lhs, Client rhs) {
return equals(lhs, new IdentityHashMap<>(),
rhs, new IdentityHashMap<>(),
new Counter());
}
public static boolean equals(Order lhs, Order rhs) {
return equals(lhs, new IdentityHashMap<>(),
rhs, new IdentityHashMap<>(),
new Counter());
}
private static boolean equals(Client lhs,
Map<Object, Long> seenL,
Client rhs,
Map<Object, Long> seenR,
Counter counter) {
if (lhs == null || rhs == null)
return lhs == rhs;
Long countL = seenL.putIfAbsent(lhs, counter.value);
Long countR = seenR.putIfAbsent(rhs, counter.value);
if (countL != null || countR != null)
return Objects.equals(countL, countR);
counter.value++;
if (lhs == rhs)
return true;
if (!Objects.equals(lhs.id, rhs.id))
return false;
if (!Objects.equals(lhs.name, rhs.name))
return false;
if (lhs.orders.size() != rhs.orders.size())
return false;
Iterator<Order> itL = lhs.orders.iterator();
Iterator<Order> itR = rhs.orders.iterator();
while (itL.hasNext() && itR.hasNext())
if (!equals(itL.next(), seenL, itR.next(), seenR, counter))
return false;
return true;
}
private static boolean equals(Order lhs,
Map<Object, Long> seenL,
Order rhs,
Map<Object, Long> seenR,
Counter counter) {
if (lhs == null || rhs == null)
return lhs == rhs;
Long countL = seenL.putIfAbsent(lhs, counter.value);
Long countR = seenR.putIfAbsent(rhs, counter.value);
if (countL != null || countR != null)
return Objects.equals(countL, countR);
counter.value++;
if (lhs == rhs)
return true;
if (!Objects.equals(lhs.id, rhs.id))
return false;
if (!Objects.equals(lhs.name, rhs.name))
return false;
return equals(lhs.client, seenL, rhs.client, seenR, counter);
}
}
I assume if you want to actually use that code, you'll need to alter it to use whatever getter naming format you're using and write a hashCode implementation. You'll also need to consider subtypes correctly if you're extending Client and Order.

Related

Refactoring business logic validation

I'm trying to refactoring this code
private void validate(Customer customer) {
List<String> errors = new ArrayList<>();
if (customer == null) {
errors.add("Customer must not be null");
}
if (customer != null && customer.getName() == null) {
errors.add("Name must not be null");
}
if (customer != null && customer.getName().isEmpty()) {
errors.add("Name must not be empty");
}
if (customer != null) {
Customer customerFromDb = customerRepository.findByName(customer.getName());
if (customerFromDb != null) {
errors.add("Customer already present on db");
}
}
if (!errors.isEmpty()) {
throw new ValidationException(errors);
}
}
I read this post Business logic validation patterns & advices
I'd like to build a generic validator for my entities and fields of the entity, I wrote this
private void validate(Customer customer) {
List<ValidationRule> validationRules = new ArrayList<>();
validationRules.add(new NotNullValidationRule(customer));
validationRules.add(new NotNullValidationRule(customer, Customer::getName));
validationRules.add(new NotEmptyValidationRule(customer, Customer::getName));
validationRules.add(new NotExistValidationRule(customer -> customerRepository.findByName(customer.getName())));
Validator.validate(validationRules);
}
and the Validator class
public class Validator {
public static void validate(List<ValidationRule> validationRules) {
final List<String> errors = new ArrayList<>();
for (final ValidationRule rule : validationRules) {
final Optional<String> error = rule.validate();
if (error.isPresent()) {
errors.add(error.get());
}
}
if (!errors.isEmpty()) {
throw new ValidationException(errors);
}
}
}
but I don't know how to implement the interface ValidationRule and other classes (NotNullValidationRule, NotEmptyValidationRule, NotExistValidationRule)
I would write something like :
CommonValidations.notNull(errors, customer);
if (customer != null) {
CommonValidations.notEmpty(errors, customer.getName());
}
customerCustomeBeanValidations.validName(errors, customer.getName());
customerCustomeBeanValidations.notExist(errors, customer.getName());
In the link you reference, the accepted answer suggested using the Strategy design pattern, and then gave an example of both an interface and implementation. In your case, you would create a new interface ValidationRule, with at least one method validate(), and then you would create concrete classes that each implementat that interface (NotNullValidationRule, NotEmptyValidationRule, AlreadyExistValidationRule).
I found this solution:
I create an interface ValidationRule
import java.util.Optional;
public interface ValidationRule {
Optional<ValidationError> validate();
}
And some classes that implement the behaviours
public class NotNullValidationRule implements ValidationRule {
private Object object;
private String field;
public NotNullValidationRule(Object object, String field) {
this.object = object;
if (field == null || field.isEmpty()) {
throw new IllegalArgumentException("field must not be null or emtpy");
}
this.field = field;
}
#Override public Optional<ValidationError> validate() {
if (object == null) {
return Optional.empty();
}
try {
Object value = new PropertyDescriptor(field, object.getClass()).getReadMethod().invoke(object);
if (value == null) {
ValidationError validationError = new ValidationError();
validationError.setName(object.getClass().getSimpleName() + "." + field);
validationError.setError("Field " + field + " is null");
return Optional.of(validationError);
}
}
catch (Exception e) {
throw new IllegalStateException("error during retrieve of field value");
}
return Optional.empty();
}
}
Another where I pass a method to call:
package it.winetsolutions.winactitime.core.service.validation;
import java.beans.PropertyDescriptor;
import java.util.Optional;
import java.util.function.Function;
public class NotExistValidationRule implements ValidationRule {
Object object;
String field;
Function<? super String, ? super Object> function;
public NotExistValidationRule(Object object, String field, Function<? super String, ? super Object> function) {
this.object = object;
if (field == null || field.isEmpty() || function == null) {
throw new IllegalArgumentException("field and function must not be null or emtpy");
}
this.field = field;
this.function = function;
}
#Override public Optional<ValidationError> validate() {
if (object == null) {
return Optional.empty();
}
try {
Object value = new PropertyDescriptor(field, object.getClass()).getReadMethod().invoke(object);
Long id = (Long) new PropertyDescriptor("id", object.getClass()).getReadMethod().invoke(object);
Object result = function.apply(value == null ? (String) value : ((String) value).trim());
if (result != null &&
!id.equals((Long) new PropertyDescriptor("id", result.getClass()).getReadMethod().invoke(result))) {
ValidationError validationError = new ValidationError();
validationError.setName(object.getClass().getSimpleName() + "." + field);
validationError.setError("Element with " + field +": " + value + " already exists");
return Optional.of(validationError);
}
}
catch (Exception e) {
throw new IllegalStateException("error during retrieve of field value");
}
return Optional.empty();
}
}

How to write common custom GSON deserializer for all fields of a class?

I have a class MySimpleObject that have various member fields. Given a json, it will populate the field accordingly. However if the json is stated as "nil", I plan to set it to null instead of string "nil".
The below example should result is an MySimpleObject with null for all it's fields, and a 0 length list of subItemList. myObj1 should be equal to myObj2.
#Test
public void myTestFunction() {
String myJson1 = "{\"item1\":\"nil\",\"item2\":\"nil\",\"subItemList\":[{\"subItem1\":\"nil\",\"subItem2\":\"nil\"}]}";
String myJson2 = "{\"subItemList\":[]}";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken<List<MySubItems>>(){ }.getType(), new MyOwnListDeserializer());
gsonBuilder.registerTypeAdapter(String.class, new MyOwnStringDeserializer());
Gson gson = gsonBuilder.create();
MySimpleObject myObj1 = gson.fromJson(myJson1, MySimpleObject.class);
MySimpleObject myObj2 = gson.fromJson(myJson2, MySimpleObject.class);
assertThat(myObj1.equals((myObj2))).isTrue();
}
class MySimpleObject implements Serializable {
String item1 = null;
String item2 = null;
List<MySubItems> subItemList;
#Override
public int hashCode() {
int hash = 17;
hash = 31*hash + ((item1 == null)? 0 :item1.hashCode());
hash = 31*hash + ((item2 == null)? 0 :item2.hashCode());
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof MySimpleObject) {
return this.hashCode() == obj.hashCode();
}
return super.equals(obj);
}
}
class MySubItems implements Serializable {
String subItem1 = null;
String subItem2 = null;
#Override
public int hashCode() {
int hash = 17;
hash = 31*hash + ((subItem1 == null)? 0 :subItem1.hashCode());
hash = 31*hash + ((subItem2 == null)? 0 :subItem2.hashCode());
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof MySubItems) {
return this.hashCode() == obj.hashCode();
}
return super.equals(obj);
}
}
How to write the custom serializer without having to loop through each jsonObject and check for "nil" to set to null?
I looked at the Gson library and also the gson-fire project, but none of them seem to allow for a real generic (and performant) solution.
One way to go is to systematically replace "nil" by "null" in the json string before passing it to the gson object. It is not very clean, but it is quite performant and could work.
Here is a basic method (must be refined):
public static String convertNil( String json ){
return json.replaceAll( ":\\s*\"nil\"", ": null" );
}
Then use it like:
MySimpleObject myObj1 = gson.fromJson( convertNil( myJson1 ), MySimpleObject.class );
MySimpleObject myObj2 = gson.fromJson( convertNil( myJson2 ), MySimpleObject.class );
I manage to come up with some custom deserialization that do the job as below.
#Test
public void myTestFunction() {
String myJson1 = "{\"item1\":\"nil\",\"item2\":\"nil\",\"subItemList\":[{\"subItem1\":\"nil\",\"subItem2\":\"nil\"}]}";
String myJson2 = "{\"subItemList\":[]}";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(new TypeToken<List<MySubItems>>(){ }.getType(), new MyOwnListDeserializer());
gsonBuilder.registerTypeAdapter(String.class, new MyOwnStringDeserializer());
Gson gson = gsonBuilder.create();
MySimpleObject myObj1 = gson.fromJson(myJson1, MySimpleObject.class);
MySimpleObject myObj2 = gson.fromJson(myJson2, MySimpleObject.class);
assertThat(myObj1.equals((myObj2))).isTrue();
}
class MySimpleObject implements Serializable {
String item1 = null;
String item2 = null;
List<MySubItems> subItemList;
#Override
public int hashCode() {
int hash = 17;
hash = 31*hash + ((item1 == null)? 0 :item1.hashCode());
hash = 31*hash + ((item2 == null)? 0 :item2.hashCode());
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof MySimpleObject) {
return this.hashCode() == obj.hashCode();
}
return super.equals(obj);
}
}
class MySubItems implements Serializable {
String subItem1 = null;
String subItem2 = null;
#Override
public int hashCode() {
int hash = 17;
hash = 31*hash + ((subItem1 == null)? 0 :subItem1.hashCode());
hash = 31*hash + ((subItem2 == null)? 0 :subItem2.hashCode());
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof MySubItems) {
return this.hashCode() == obj.hashCode();
}
return super.equals(obj);
}
}
class MyOwnStringDeserializer implements JsonDeserializer<String> {
#Override
public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return (json.getAsString().equals("nil"))? null : json.getAsString();
}
}
class MyOwnListDeserializer implements JsonDeserializer<List<MySubItems>> {
#Override
public List<MySubItems> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List<MySubItems> list = new ArrayList<>();
for (JsonElement element : json.getAsJsonArray()) {
JsonObject subObj = element.getAsJsonObject();
MySubItems subItems = new MySubItems();
if (!subObj.get("subItem1").getAsString().equals("nil")) {
subItems.subItem1 = subObj.get("subItem1").getAsString();
}
if (!subObj.get("subItem2").getAsString().equals("nil")) {
subItems.subItem2 = subObj.get("subItem1").getAsString();
}
if (subItems.subItem1 != null || subItems.subItem2 != null) {
list.add(subItems);
}
}
return (list.size() == 0)? null : list;
}
}
I'm still not very happy that MyOwnListDeserializer, has to manually handle subItem1 and subItem2, despite they should have the same rule as defined by MyOwnStringDeserializer. But I just don't know how to apply MyOwnStringDeserializer to MyOwnListDeserializer.
Would be still open for other better answers than mine.
Update A more optimized answer could be found in
https://stackoverflow.com/a/39671580/3286489

Java: Set.contains() gives wrong result

Since Set.contains(Object o) should just use equals to check if an object is in a Set, how can the following two methods produce different results? In my project, method 1 does not throw an exception, but method 2 does throw an exception.
For information, the object "group" is in the set "groups", so Method 1 works like I would expect it.
boolean java.util.Set.contains(Object o)
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
Method 1:
boolean ex = true;
for (AccessControlGroup acg : groups) {
if ((acg.equals(group))) {
ex = false;
}
}
if (ex) {
throw new IllegalStateException("Invalid group");
}
Method 2:
if (!(groups.contains(group))) {
throw new IllegalStateException("Invalid group");
}
Further information:
HashSet is used.
AccessControlGroup:
public List<AccessControlGroup> getInherits() {
if (this.inherits == null) {
this.inherits = new ArrayList<>();
}
return this.inherits;
}
public void setInherits(List<AccessControlGroup> inherits) {
this.inherits = inherits;
}
public List<AccessControlPermission> getPermissions() {
if (this.permissions == null) {
this.permissions = new ArrayList<>();
}
return this.permissions;
}
public void setPermissions(List<AccessControlPermission> permissions) {
this.permissions = permissions;
}
#Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
// prevent infinity loops or other sick effects
// result = prime * result + ((this.inherits == null) ? 0 : this.inherits.hashCode());
result = prime * result + ((this.permissions == null) ? 0 : this.permissions.hashCode());
result = prime * result + ((this.type == null) ? 0 : this.type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AccessControlGroup other = (AccessControlGroup) obj;
// prevent infinity loops or other sick effects...
// if (!Objects.equal(this.inherits, other.inherits)) {
// return false;
// }
if (!Objects.equals(this.permissions, other.permissions)) {
return false;
}
if (!Objects.equals(this.type, other.type)) {
return false;
}
return true;
}
AccessControl:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AccessControl other = (AccessControl) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
I'll lay odds that you modified group after adding it to the set groups. That would change its hashCode, which would leave it in the wrong bucket in groups, which would mean contains would not find it anymore unless the new hashCode happened to collide with the old one.
Set< AccessControlGroups > groups = new HashSet<>();
AccessControlGroup group = new AccessControlGroup();
groups.add( group );
groups.contains( group ); // true
group.setPermissions( new ArrayList<>() );
groups.contains( group ); // false

Compare two list objects in java

I have the following simple java program to compare two objects in list.
public static void main( String[] args )
{
UserInfo user=new UserInfo();
user.setDomainId(2);
user.setId("sxpadmin");
user.setStatus("active");
UserInfo user1=new UserInfo();
user1.setDomainId(2);
user1.setId("sxpadmin");
user1.setStatus("active");
System.out.println(user.equals(user1));
List<UserInfo> userinfo=new ArrayList<UserInfo>();
userinfo.add(user);
userinfo.add(user1);
HashSet<UserInfo> set = new HashSet<UserInfo>();
for (UserInfo temp : userinfo)
{
if(set.contains(temp)){
System.out.println("same");
}
else{
System.out.println("different");
set.add(temp);
}
}
}
Now I am comparing the two objects and it should take to if block as the content in both the objects is same.
I am iterating the userinfo object and comapring its elements and also I am adding it to set hoping to avoid the duplicates.But none of them worked. Help me in solving this.
Hashcode and equals methods in UserInfo are
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + customer_id;
result = prime * result
+ ((domainId == null) ? 0 : domainId.hashCode());
result = prime * result
+ ((last_name == null) ? 0 : last_name.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((first_name == null) ? 0 : first_name.hashCode());
// Added by Sandip on 04 Jan 2013 for 2 FA
result = prime * result
+ ((seed_value == null) ? 0 : seed_value.hashCode());
// End added by Sandip on 04 Jan 2013 for 2 FA
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserInfo other = (UserInfo) obj;
if (customer_id != other.customer_id)
return false;
if (last_name == null) {
if (other.last_name != null)
return false;
} else if (!last_name.equals(other.last_name))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (first_name == null) {
if (other.first_name != null)
return false;
} else if (!first_name.equals(other.first_name))
return false;
// Added by Sandip on 04 Jan 2013 for 2 FA
if (seed_value == null) {
if (other.seed_value != null)
return false;
} else if (!seed_value.equals(other.seed_value))
return false;
// End added by Sandip on 04 Jan 2013 for 2 FA
if (domainId == null) {
if (other.domainId != null)
return false;
} else if (!domainId.equals(other.domainId))
return false;
return true;
}
If you want to create working solution here's what you have to override equals and hashCode method.
Many IDE's have feature to autogenerate those methods for chosen class. Following code of UserInfo shows methods generated by IntelliJ:
public class UserInfo {
private int domainId;
private String id;
private String status;
public void setDomainId(int domainId) {
this.domainId = domainId;
}
public void setId(String id) {
this.id = id;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserInfo userInfo = (UserInfo) o;
if (domainId != userInfo.domainId) return false;
if (id != null ? !id.equals(userInfo.id) : userInfo.id != null) return false;
if (status != null ? !status.equals(userInfo.status) : userInfo.status != null) return false;
return true;
}
#Override
public int hashCode() {
int result = domainId;
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (status != null ? status.hashCode() : 0);
return result;
}
}
It's important to remember that if certain class doesn't implement those methods then hashCode is returning hash of objects address in memory and equals is using this default version of hashCode.
Code pasted above is working with code pasted by you. My output is:
true
different
same

Why is listShuttle component in richFaces not getting updated?

I am a newbie for Richfaces components. When I am using the <rich:listShuttle>, the Arraylist specified in the targetValue is now getting updated with the latest data?
MyJSF File
<a4j:region>
<rich:listShuttle sourceValue="#{bean.selectItems}" id="one"
targetValue="#{bean.selectItemsone}" var="items" listsHeight="150"
sourceListWidth="130" targetListWidth="130"
sourceCaptionLabel="Intial Items"
targetCaptionLabel="Selected Items" converter="Listconverter">
<rich:column>
<h:outputText value="#{items.value}"></h:outputText>
</rich:column>
</rich:listShuttle>
</a4j:region>
<a4j:region>
<a4j:commandButton value="Submit" action="#{bean.action}" />
</a4j:region>
My Managed Bean
private List<String> selectedData;
private List<BeanItems> selectItems;
private List<BeanItems> selectItemsone;
public String action() {
System.out.println(selectItems);
System.out.println(selectItemsone);
System.out.println("Select Item List");
Iterator<BeanItems> iterator = selectItems.iterator();
while (iterator.hasNext()) {
BeanItems item = (BeanItems) iterator.next();
System.out.println(item.getValue());
}
System.out.println("/nSelect Item one list ");
Iterator<BeanItems> iterator2 = selectItemsone.iterator();
while (iterator2.hasNext()) {
BeanItems item = (BeanItems) iterator2.next();
System.out.println(item.getValue());
}
return "";
}
public void setSelectedData(List<String> selectedData) {
this.selectedData = selectedData;
}
public List<String> getSelectedData() {
return selectedData;
}
/**
* #return the selectItems
*/
public List<BeanItems> getSelectItems() {
if (selectItems == null) {
selectItems = new ArrayList<BeanItems>();
selectItems.add(new BeanItems("value4", "label4"));
selectItems.add(new BeanItems("value5", "label5"));
selectItems.add(new BeanItems("value6", "label6"));
selectItems.add(new BeanItems("value7", "label7"));
selectItems.add(new BeanItems("value8", "label8"));
selectItems.add(new BeanItems("value9", "label9"));
selectItems.add(new BeanItems("value10", "label10"));
}
return selectItems;
}
/**
* #return the selectItemsone
*/
public List<BeanItems> getSelectItemsone() {
if (selectItemsone == null) {
selectItemsone = new ArrayList<BeanItems>();
selectItemsone.add(new BeanItems("value1", "label1"));
selectItemsone.add(new BeanItems("value2", "label2"));
selectItemsone.add(new BeanItems("value3", "label3"));
}
return selectItemsone;
}
My Converter Class
public Object getAsObject(FacesContext context, UIComponent component,String value) {
int index = value.indexOf(':');
return new BeanItems(value.substring(0, index), value.substring(index + 1));
}
public String getAsString(FacesContext context, UIComponent component,Object value) {
BeanItems beanItems = (BeanItems) value;
return beanItems.getValue() + ":" + beanItems.getData();
}
My BeanItems Class
private String data; //Getter & setter
private String value; //Getter & setter
public BeanItems() {
}
public BeanItems(String value, String data) {
this.value = value;
this.data = data;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((data == null) ? 0 : data.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final BeanItems other = (BeanItems) obj;
if (data == null) {
if (other.data != null)
return false;
} else if (!data.equals(other.data))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
If your question is that the target list is not getitng populated then i think you are supposed to override equals , hash code method for the wrapper object[BeanItem] since in the converter you are constructing new object every time in getAsObject method.
Also try putting a h:message tag wrapped in --a4j:outputPanel ajaxRendered="true"-- in your page to print any conversion errors that might be getting generated.

Categories