What is a good way to do multi-row updates in struts (with struts live)? - struts

Without using DynaForm and it's kin.
I would like to use a POJO data transfer object, e.g., Person:
public class Person {
private Long id;
private String firstName;
private String lastName;
// ... getters / setters for the fields
}
In the struts live action form we would have:
public class PersonUpdateForm extends SLActionForm {
String organization;
Person[] persons; // all the people will be changed to this organization; they're names and so forth can be updated at the same time (stupid, but a client might desire this)
// getters / setters + index setters / getters for persons
}
What would the corresponding html:text tags look like in the JSP to allow this? If I switch to a List persons field and use a lazy-loading list (in commons-collections) how would that change thinsg?
There seems to be no good way to do this in struts-1.2(.9?)
All help is greatly appreciated!!! If you need more context let me know and I can provide some.

Okay, I believe I've figured it out! The trick is to have your indexed getter create an element each time the getPersons() method is called by the populate method of BeanUtils. The code is completed yet, but I got a positive looking result. It's 3:30 and I've been stuck on this a while. Nobody seemded to know the answer, which makes me want to smack them in the head with a trout. As for my own ignorance ... I only have them to blame!
public List<Person> getPersons() {
persons.add(new Person()); // BeanUtils needs to know the list is large enough
return persons;
}
Add your indexed getters and setters too, of course.
I remember how I actually did this. You must pre-initialize the persons List above to the maximum size you expect to transfer. This is because the List is first converted to an array, the properties then set on each element of the array, and finally the List set back using setPersons(...). Therefore, using a lazy-loading List implementation or similar approach (such as that show above) will NOT work with struts live. Here's what you need to do in more detail:
private List<Person> persons = new ArrayList<Person>(MAX_PEOPLE);
public MyConstructor() { for(int i = 0; i < MAX_PEOPLE; i++) persons.add(new Person()); }
public List<Person> getPeopleSubmitted() {
List<Person> copy = new ArrayList<Person>();
for(Person p : persons) {
if(p.getId() != null) copy.add(p);
// id will be set for the submitted elements;
// the others will have a null id
}
return copy; // only the submitted persons returned - not the blank templates
}
That's basically what you have to do! But the real question is - who's using struts live anymore?!

Related

Auto generate unique IDs using the singleton pattern

The small piece of code I present is in C#, but the question is more about theory and design (I think) than about code itself.
In my application, a user can add items (let's say it is a wish list manager and the user can add his wishes). I am required to auto generate IDs for this entries.
They gave us an example about how to do this and we have to use it (from what I've read around here, GUIDs are a great way of doing this and I'll have gone for that if the choice was mine, but this is irrelevant here).
The given example:
class IDGenerator
{
private static IDGenerator instance;
private int nextID;
private IDGenerator() { nextID = 1; }
[MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
public static IDGenerator getGenerator()
{
if (instance == null)
{
instance = new IDGenerator();
}
return instance;
}
public int nextId()
{
return nextID++;
}
}
Then, the teacher has a IdObject class from which Wish inherits and every time a new instance of Wish is created, a unique ID is generated using the above IdGenerator. Pretty simple. It is basically like a wrapper around a global variable.
I have some problems with this: the IDs are not reusable (not such a big problem), if I want to have another class that extends IdObject I need another id generator (done by simply copy pasting the code or I can just live with the fact that I'll have IDs all over the place).
But the biggest problem I have: if I save the wish list (simply text file, serialization, it doesn't matter) I can end up with duplicate IDs. I could work around this by enforcing a file reading every time the program starts, check the IDs, and then initialize the first next ID with a value outside the range of already used IDs and then enforce a file save every time a item is added. Or I can just keep generating IDs until a valid one is generated. But I don't want to do it like this. There must be a better way of doing it.
So any good ways of doing this by still using the singleton pattern and not doing "magic tricks" like the ones I described above?
OK. So the question is how do I ensure that the IDGenerator will not repeat the initial sequence over and over again every time it is resumed, right? As you pointed it out, one solution would be to use a sufficiently strong random generator; the other one would require persisting its state.
So the question becomes: persist or randomize, isn't there any other solution? And the answer is yes.
For instance, every time you resume your generator you could initialize its nextId variable to the current timestamp expressed in seconds (I don't think milliseconds would be necessary.) That way there won't be any repetitions. Of course, you would leave large intervals of unused ids between sessions, but this could be seen as the price you would be glad to pay if you want to keep the generator's code as simple as possible.
public sealed class SingletonIdGenerator
{
private static long _id;
private SingletonIdGenerator()
{
}
public string Id
{
get { return _id++.ToString().Substring(8); }
}
public static SingletonIdGenerator Instance { get { return Nested.instance; } }
private class Nested
{
static Nested()
{
_id = DateTime.Now.Ticks;
}
internal static readonly SingletonIdGenerator instance = new SingletonIdGenerator();
}
}

How to easily access widely different subsets of fields of related objects/DB tables?

Imagine we have a number of related objects (equivalently DB tables), for example:
public class Person {
private String name;
private Date birthday;
private int height;
private Job job;
private House house;
..
}
public class Job {
private String company;
private int salary;
..
}
public class House {
private Address address;
private int age;
private int numRooms;
..
}
public class Address {
private String town;
private String street;
..
}
How to best design a system for easily defining and accessing widely varying subsets of data on these objects/tables? Design patterns, pros and cons, are very welcome. I'm using Java, but this is a more general problem.
For example, I want to easily say:
I'd like some object with (Person.name, Person.height, Job.company, Address.street)
I'd like some object with (Job.company, House.numRooms, Address.town)
Etc.
Other assumptions:
We can assume that we're always getting a known structure of objects on the input, e.g. a Person with its Job, House, and Address.
The resulting object doesn't necessarily need to know the names of the fields it was constructed from, i.e. for subset defined as (Person.name, Person.height, Job.company, Address.street) it can be the array of Objects {"Joe Doe", 180, "ACompany Inc.", "Main Street"}.
The object/table hierarchy is complex, so there are hundreds of data fields.
There may be hundreds of subsets that need to be defined.
A minority of fields to obtain may be computed from actual fields, e.g. I may want to get a person's age, computed as (now().getYear() - Person.birtday.getYear()).
Here are some options I see:
A SQL view for each subset.
Minuses:
They will be almost the same for similar subsets. This is OK just for field names, but not great for the joins part, which could ideally be refactored out to a common place.
Less testable than a solution in code.
Using a DTO assembler, e.g. http://www.genericdtoassembler.org/
This could be used to flatten the complex structure of input objects into a single DTO.
Minuses:
I'm not sure how I'd then proceed to easily define subsets of fields on this DTO. Perhaps if I could somehow set the ones irrelevant to the current subset to null? Not sure how.
Not sure if I can do computed fields easily in this way.
A custom mapper I came up with.
Relevant code:
// The enum has a value for each field in the Person objects hierarchy
// that we may be interested in.
public enum DataField {
PERSON_NAME(new PersonNameExtractor()),
..
PERSON_AGE(new PersonAgeExtractor()),
..
COMPANY(new CompanyExtractor()),
..
}
// This is the container for field-value pairs from a given instance of
// the object hierarchy.
public class Vector {
private Map<DataField, Object> fields;
..
}
// Extractors know how to get the value for a given DataField
// from the object hierarchy. There's one extractor per each field.
public interface Extractor<T> {
public T extract(Person person);
}
public class PersonNameExtractor implements Extractor<String> {
public String extract(Person person) {
return person.getName();
}
}
public class PersonAgeExtractor implements Extractor<Integer> {
public int extract(Person person) {
return now().getYear() - person.getBirthday().getYear();
}
}
public class CompanyExtractor implements Extractor<String> {
public String extract(Person person) {
return person.getJob().getCompany();
}
}
// Building the Vector using all the fields from the DataField enum
// and the extractors.
public class FullVectorBuilder {
public Vector buildVector(Person person) {
Vector vector = new Vector();
for (DataField field : DataField.values()) {
vector.addField(field, field.getExtractor().extract(person));
}
return vector;
}
}
// Definition of a subset of fields on the Vector.
public interface Selector {
public List<DataField> getFields();
}
public class SampleSubsetSelector implements Selector {
private List<DataField> fields = ImmutableList.of(PERSON_NAME, COMPANY);
...
}
// Finally, a builder for the subset Vector, choosing only
// fields pointed to by the selector.
public class SubsetVectorBuilder {
public Vector buildSubsetVector(Vector fullVector, Selector selector) {
Vector subsetVector = new Vector();
for (DataField field : selector.getFields()) {
subsetVector.addField(field, fullVector.getValue(field));
}
return subsetVector;
}
}
Minuses:
Need to create a tiny Extractor class for each of hundreds of data fields.
This is a custom solution that I came up with, seems to work and I like it, but I feel this problem must have been encountered and solved before, likely in a better way.. Has it?
Edit
Each object knows how to turn itself into a Map of fields, keyed on an enum of all fields.
E.g.
public enum DataField {
PERSON_NAME,
..
PERSON_AGE,
..
COMPANY,
..
}
public class Person {
private String name;
private Date birthday;
private int height;
private Job job;
private House house;
..
public Map<DataField, Object> toMap() {
return ImmutableMap
.add(DataField.PERSON_NAME, name)
.add(DataField.BIRTHDAY, birthday)
.add(DataField.HEIGHT, height)
.add(DataField.AGE, now().getYear() - birthday.getYear())
.build();
}
}
Then, I could build a Vector combining all the Maps, and select subsets from it like in 3.
Minuses:
Enum name clashes, e.g. if Job has an Address and House has an Address, then I want to be able to specify a subset taking street name of both. But how do I then define the toMap() method in the Address class?
No obvious place to put code doing computed fields requiring data from more than one object, e.g. physical distance from Address of House to Address of Company.
Many thanks!
Over in-memory object mapping in the application, I would favor database processing of the data for better performance. Views, or more elaborate OLAP/datawarehouse tooling could do the trick. If the calculated fields remain basic, as in "age = now - birth", I see nothing wrong with having that logic in the DB.
On the code side, given the large number of DTOs you have to deal with, you could use classless dynamic (available in some JVM languages) or JSON objects. The idea is that when a data structure changes, you only need to modify the DB and the UI, saving you the cost of changing a whole bunch of classes in between.

Creating objects with very many optional fields

I'm trying to recreate Hearthstone cards as objects in Java, but I'm having trouble doing this in a good and efficient way.
All cards have some common properties like a 'name'. But the problem is that there is about 300 cards to generate, and there is about 30 different abilities that each card may or may not have. Now, do I have to create a basic card class with all the possible abilities set to false and then set all its specific ability parameters to true? This approach seems to get very messy with all the getters and all the extra information that some abilities needs to specify... So my question is if there's there a better way to solve this kind of problem?
I would like to create these card objects so that I'm only 'adding' the specific abilities as fields, but I can't figure out how to do this in a good way.
Thankful for help!
Like Dave said, it's a little difficult to be sure what the best solution to your problem is without more context. However, from what I can gather, your problem is a pretty common one. For common problems, programmers often create efficient solutions that can be used over and over again called design patterns.
Design patterns aren't needed in every case, so be careful not to overuse them, but it seems like they could help you here. Both solutions mentioned by Dave may work, but the problem with making each ability an object is that it requires you to make as many classes as you have abilities. Furthermore, if each ability is a simple variable, it may be overkill to create classes for all of them, particularly since so many classes can become difficult to maintain. Although having these abilities inherit from an interface somewhat helps with maintainability, I think an easier solution can probably be found in the builder pattern.
I won't explain it in detail here, but here's a tutorial that seems reasonably simple. It's basic purpose is to
For your particular example it would look something like this:
public class Card
{
private final String name;
private final Ability soundAbility;
private final Ability animationAbility;
private final Ability customMessageAbility;
private final String technology;
// The constructor is private in this case to restrict instantiation to the builder.
private Card(CardBuilder builder)
{
this.name = builder.name;
this.soundAbility = builder.soundAbility;
this.animationAbility = builder.animationAbility;
this.customMessageAbility = builder.customMessageAbility;
this.technology = builder.technology;
}
// Getters
public String getName()
{
return this.name;
}
public Ability getSoundAbility()
{
return this.soundAbility;
}
// ... More getters and stuff ...
#Override
public String toString()
{
String text = "";
text += this.name + ":";
text += "\n\t" + this.soundAbility;
text += "\n\t" + this.animationAbility;
text += "\n\t" + this.customMessageAbility;
text += "\n\tI have the ability of " + this.technology + "!";
return text;
}
// Nested builder class
public static class CardBuilder
{
private final String name;
private Ability soundAbility;
private Ability animationAbility;
private Ability customMessageAbility;
private String technology;
public CardBuilder(String name)
{
this.name = name;
}
public CardBuilder soundAbility(Ability soundAbility)
{
this.soundAbility = soundAbility;
return this;
}
public CardBuilder animationAbility(Ability animationAbility)
{
this.animationAbility = animationAbility;
return this;
}
public CardBuilder customMessageAbility(Ability customMessageAbility)
{
this.customMessageAbility = customMessageAbility;
return this;
}
public CardBuilder technology(String technology)
{
this.technology = technology;
return this;
}
public Card build()
{
return new Card(this);
}
}
}
Then to run the program:
package builderTest;
class BuilderMain
{
public static void main(String[] args)
{
// Initialize ability objects.
Ability a1 = new SoundAbility();
Ability a2 = new AnimationAbility();
Ability a3 = new CustomMessageAbility();
// Build card
Card card = new Card.CardBuilder("Birthday Card")
.soundAbility(a1)
.animationAbility(a2)
.customMessageAbility(a3)
.technology("Flash")
.build();
System.out.println(card);
}
}
The output would be something along the lines of:
Birthday Card:
I have the ability of sound!
I have the ability of animation!
I have the ability of customizing messages!
I have the ability of Flash!
Keep in mind that I'm working without much context, so what you need might be significantly different.
Although previous answers are very good, there is still another way of achieve this Object creation
with very many optional fields
I found myself in similar situation when dealing with DB complexity and Command design pattern. As you know some table columns values are mandatory - some are not. I'm using this Effective Java book
for such cases.
So, useful here is the Consider a builder when faced with many constructor parameters. By doing so, you avoid
first, the Telescoping constructor pattern (does not scale well) - it works, but it is hard to write client code when there are many parameters, and harder still to read it.
second, the JavaBeans Pattern, which is good, but allows inconsistency and mandates mutability. It may be in an inconsistent state partway through its construction and precludes the possibility of making a class immutable too.
The Builder pattern as used simulates named optional parameters as found in Ada and Python.Like a constructor, a builder can impose invariants on its parameters. But it is critical that they be checked after copying the parameters from the builder to the object, and that they be checked on
the object fields rather than the builder fields.
Cheers.

How do I make a well designed validation for a complex collection model?

As input I have a list of Books. As output I expect a SimilarBookCollection.
A SimilarBookCollection has an author, publishYear and list of Books. The SimilarBookCollection can't be created if the author of the books is different or if the publishYear is different.
The solution so far in PHP:
client.php
----
$arrBook = array(...); // array of books
$objValidator = new SimilarBookCollectionValidator($arrBook);
if ($objValidator->IsValid()) {
$objSimilarBookCollection = new SimilarBookCollection($arrBook);
echo $objSimilarBookCollection->GetAuthor();
}
else {
echo 'Invalid input';
}
SimilarBookCollection.php
---
class SimilarBookCollection() {
public function SimilarBookCollection(array $arrBook) {
$objValidator = new SimilarBookCollectionValidator($arrBook);
if ($objValidator->IsValid()) {
throw new Exception('Invalid books to create collection');
}
$this->author = $arrBook[0]->GetAuthor();
$this->publishYear = $arrBook[0]->GetPublishYear();
$this->books = $arrBook;
}
public function GetAuthor() {
return $this->author;
}
public function GetPublishYear() {
return $this->publishYear;
}
public function GetBooks() {
return $this->books;
}
}
SimilarBookCollectionValidator.php
---
class SimilarBookCollectionValidator() {
public function IsValid() {
$this->ValidateAtLeastOneBook();
$this->ValidateSameAuthor();
$this->ValidateSameYear();
return $this->blnValid;
}
... //actual validation routines
}
The goal is to have a "special" collection with only books that have the same author and publishYear. The idea is to easily access the repeating information like author or year from the object.
How would you name the SimilarBookCollection? The current name is to
generic. Using a name like SameYearAuthorBookCollection looks a bit
long and strange(if more conditions will be added then name will increase)
Would you use a Validator in SimilarBookCollection constructor using a
defensive programming style?
Would you change the design of the code? If yes how?
It all depends ;)
So if I were to aim for a generic adaptable solution I would do the following:
Validator in constructor
On one hand you are validating twice; that is informative in case of a broken precondition/contract (not giving a valid list), but is double the code to run - for what purpose exactly?
If you want to use this in a system depends on its size, how critical it is, product phase, and likely more criterias.
But then it also is controller logic fitted into a model meaning you are spreading your code around.
I would not put it in the constructor.
Name / Design
I would say keep the BookCollection generic as it is, and have any validation strictly in the controller space, instead of bloating the collection which essentially seems to be an array with the extra field of author.
If you want to differentiate between different collection types use either (multiple) inheritance or some sort of additional field "collectionType"; the former if you expect many derivatives or varying functionality to come (also keeps the logic where different nicely separated).
You could also consider your collection as a set on which you perform queries and for convenience's sake you could maintain some sort of meta data like $AuthorCount = N, $publicationDates = array(...) from which you can quickly derive the collection's nature. This approach would also keep your validator-code minimal (or non-existent), as it'd be implicitly in the collection and you could just do the validation in the controller keeping the effective logic behind it clearly visible.
That would also make it more comfortable for you in the future. But the question really is what you want and need it for, and what changes you expect, because you are supposed to fit your design to your requirements and likely changes.
For your very particular problem the constraints as I understand are as follows:
There is only one collection type class in the system at any given
point in time.
The class's items have several attributes, and for a particular, possibly changing subset of these (called identical attributes), the collection only accepts item lists where the chosen attributes of all items are identical.
The class provides getters for all identical attributes
The class must not be usable in any other way than the intended way.
If not for point 1 I would use a generic base class that is either parametrized (ie you tell it upon instantiation which is the set of identical attributes) or uses multiple inheritance (or in php traits) to compose arbitrary combinations with the needed interfaces. Children might rely on the base class but use a predefined subset of the identical attributes.
The parametrized variant might look something as follows:
class BookCollection {
public function __construct($book_list, $identical_fields=array())
{
if (empty($book_list))
{
throw new EmptyCollectionException("Empty book list");
}
$default = $book_list[0];
$this->ia = array();
foreach($identical_fields as $f)
{
$this->ia[$f] = $default->$f;
}
foreach($book_list as $book)
{
foreach($identical_fields as $f)
{
if ($this->ia[$f] !== $book->$f)
{
throw new NotIdenticalFieldException("Field $f is not identical for all");
}
}
}
$this->book_list = $book_list;
}
public function getIdentical($key)
{
$this->ia[$key];
}
}
final class BC_by_Author extends BookCollection{
public function __construct($book_list)
{
parent::__construct($book_list,array('author'));
}
public function getAuthor(){ $this->ia['author']; }
}
or fooling around with abstract and final types (not sure if it's valid like this)
abstract class BookCollection{
public final function __construct($book_list){...}
abstract public function getIdenticalAttributes();
}
final class BC_by_Author {
public function getIdenticalAttributes(){ return array('author'); }
public function getAuthor(){ return $this->ia['author']; }
}
If you rely on getters that do not necessarily match the field names I would go for multiple inheritance/traits.
The naming then would be something like BC_Field1Field2Field3.
Alternatively or additionally, you could also use exactly the same classname but develop your solutions in different namespaces, which would mean you wouldn't have to change your code when you change the namespace, plus you can keep it short in the controllers.
But because there will only ever be one class, I would name it BookCollection and not unnecessarily discuss it any further.
Because of constraint 4, the white box constraint, the given book list must be validated by the class itself, ie in the constructor.

NHibernate : Root collection with an root object

I want to track a list of root objects which are not contained by any element. I want the following pseudo code to work:
using (session1 = [...]) {
IList<FavoriteItem>list = session1.Linq<FavoriteItem>().ToList();
}
list.Add(item1);
list.Add(item2);
list.Remove(item3);
list.Remove(item4);
var item5 = list.First(i => i.Name = "Foo");
item5.Name = "Bar";
using (session2 = [...]) {
session2.Save(list);
}
This should automatically insert item1 and item2, delete item3 and item3 and update item5 (i.e. I don't want to call sesssion.SaveOrUpdate() for all items separately.
Is it possible to define a pseudo entity that is not associated with a table? For example I want to define the class Favorites and map 2 collection properties of it and than I want to write code like this:
using (session1 = [...]) {
var favs = session1.Linq<Favorites>();
}
favs.FavoriteColors.Add(new FavoriteColor(...));
favs.FavoriteMovies.Add(new FavoriteMovie(...));
using (session2 = [...]) {
session.SaveOrUpdate(favs);
}
FavoriteColors and FavoriteMovies are the only properties of the Favorites class and are of type IList and IList. I do only want to persist the these two collection properties but not the Favorites class.
Actually I want a IPersistentCollection object that tracks adds and removes that belongs to no parent entity and stands for itself (the same stuff that happens to collection properties of entities, only in my case I have no parent entity). This works perfectly well if the collections belong to an entity in which case I can add and remove items between two sessions.
Any help is much appreciated.
A simpler solution than a pseudo entity would be to wrap the list in an object that manages the things you want.
public class FavoriteList : IEnumerable
{
private List<FavoriteItem> list;
private ISession session;
public FavoriteList(ISession session)
{
list = session.Linq<FavoriteItem>().ToList();
this.session = session;
}
public void Add(FavoriteItem item)
{
session.SaveOrUpdate(item);
list.Add(item);
}
public void Remove(FavoriteItem item)
{
session.Delete(item); //or something like that
list.Remove(item);
}
public IEnumerator GetEnumerator()
{
return (list as IEnumerable).GetEnumerator();
}
}
I still have not found a real solution to this problem. My work around so far is that I have added the collection as a child collection property to another entity from which only one instance exists so far. But this solution breaks if there will be more instances of this entity and it has the disadvantage that the version of it is incremented every time a item is added or removed.
The other work around would have been to create a pseudo entity with no properties/columns (except an ID).
The third alternative I could think of is recreating the whole collection every time which is quite slow and does not work if other entities are referencing one of the items.
The last alternative would be to reimplement the dirty checking functionality myself but this would add some complexity and code duplication.
If somebody knows better alternatives I would be glad for any comments.