The problem described below relates to an inventory tracking Java program. There are multiple classes of inventory item and it is not possible to determine up front what properties of the intentory class are being tracked. Taking two classes for example:
InventoryClassOne {
String name;
Double price
}
InventoryClassTwo {
StockStatus status;
Long Quantity
}.
Storing the data is no problem, I can just define a
class InventoryProperty<T> {
T value;
}
and a
class InventoryClass {
Map<String, InventoryProperty<?>> inventoryPropertyMap;
}
The UI will be developed using the Wicket framework. I want to provide the administrator of the application with a means of adding new InventoryClasses and defining how the data gets laid out (tabular, list, etc...) on a per InventoryClass basis. Has anyone ever solved this type of problem before? What design patterns are available for achieving this. I don’t even know what words to type into Google in order get ideas for how to solve this.
As much as I love Wicket, I really don't think it is the best option for this kind of meta-website.
But if I absolutely had to do it in Wicket, this is what I'd do:
Create a Fragment for each basic UI widget.
On the admin page you create a mapping from each field of your inventory class to a pre-fab fragment. (You'll have to use reflection to query what fields are available.)
When you're constructing your UI page, you create a repeater (a ListView for example, but even a simple repeater will do) which for each entry in your Field->Fragment mapping adds the fragment with a model pointing at the field.
You might need to tweak it a bit, especially with tables but this is the basic idea.
However, and I have to repeat this, you're practically losing most of the advantages of Wicket, even worse, you'll have to put extra effort in to work your way around (or against) Wicket. It just doesn't seem to be worth it.
Related
We have an application that is composed of a number of independent components and sub-systems. We are looking at implementing a simple event logging mechanism where these components & sub-systems can log some events of interest. Events could be something like
New account created
Flight arrived
Weekly report dispatched to management etc.
As you can see, the event types are heterogeneous in nature and the attributes that needs to be logged differs based on the event types. New account created event, for example, will also log the account-id, the name of the user who created the new account etc. Whereas, the flight arrived event will be logging the flight number, arrived at, arrived from etc.
I'm wondering what is the good way of modelling the event types and the attributes.
One option is to do it object oriented way - to have an AbstractEvent that will have some common attributes (timestamp, message etc) and then create a full hierarchy of classes underneath. The flight events, for example, can look like
abstract class AbstractEvent;
abstract class FlightEvent extends AbstractEvent;
class FlightArrivedEvent extends FlightEvent;
class FlightCancelledEvent extends FlightEvent;
The problem I see with this approch is that we have hundreds of events which will result in class explosion. Also, whenever we add a new event (very likely), we have to create a class and distribute the new package to all the components and sub-systems.
The second option I can think of is on the other end of the spectrum. Have a simple Event class that contains the basic attributes and wrap a map inside it so that the clients can populate any data they want. The code in that case will look something like this.
class Event {
private timestamp;
private eventType;
private Map attributes;
public Event ( String eventType ) {
timestamp = System.nanoTime();
this.eventType = eventType;
attributes = new HashMap();
}
public Event add ( String key, String value ) {
attributes.put ( key, value );
return this;
}
}
//Client code.
Event e = new Event("FlightEvent:FlightArrived")
.add("FLIGHT_NUMBER", "ABC123")
.add("ARRIVED_AT", "12:34");
While this is flexible, it suffers from inconsitency. Two components can log the FLIGHT_NUMBER key in two different formats (FLIGHT_NUMBER & FLGT_NO) and I can't think of a good way to enforce some convention.
Any one have some suggestions that can provide a nice compromise between these two extreme options?
There is a Java event framework (see java.util.EventObject and the Beans framework) but the fundamental question you are asking is not connected with events. It is a design question, and it is this: do I use Java classes in my application to represent classes in my business domain?
It is clear that the different types of event are different "classes" of thing, but for maintainability reasons you are considering representing your business data in a map so that you don't have to write and distribute an actual class. If you take this to a logical extreme, you could design your whole application with no classes and just use maps and name-value pairs for everything - not just events. It would be a mess and you would be debugging it forever because you would have no type-safety whatsoever. The only way of finding what was in map would be to look up in some documentation somewhere what someone might have added to it and what type that object might be.
So, here is the thing - you would not have actually have gotten rid of your class definition.
You will have moved it into a Word document somewhere that people will have to refer to in order to understand what is in your map. The Word document will need to be maintained, verified and distributed but unlike the Java class, it won't be checked by the compiler and there is no guarantee that the programmers will interpret it correctly.
So I would say, if there is a class, put it in your code and then focus on solving the problems of distributing and versioning the Java classes instead of distributing and versioning Word documents.
I will mention versioning again as this is an issue if you might serialise the objects and restore them, so you need to think about that.
Some caveats:
If you are writing a piece of middleware software that routes events from one system to another system, it might be you don't need to know are care what the data is, and it might make sense to use a generic holder in this case. If you don't need to look at the data, you don't need a class for it.
You might get complaints from high-level designers and architects about the number of classes and the work they have to do in defining them compared with a map and name/value stuff. This is because putting classes (i.e., the real design) in Java is harder than putting them in a Word document. Easier, if you are high-level hand-waving type guy, to write something wishy-washy in Word that doesn't need to run or even compile and then give the real design work to the programmers to get working.
Can [someone] provide a nice compromise between these two extreme options?
No. There is no generic one-size-fits-all answer to this problem. You will have to find yourself a balance which fits the general design of your product. If you nail everything down, you will need thousands of classes. If you give a lot of leeway, you can get away with a few but you're paying your freedom with precision. See my blog post "Designing a Garbage Bin"
Do you have shared attributes? As in: Do you expect to define attributes of events like you define classes right now with very tight-fitting semantics?
That would mean you have a simple event and typed attributes (i.e. String value simply isn't sufficient). You need formatting and validation for attributes or ... attributes themselves need to be classes.
If this is the case, you can use my type-safe map pattern: http://blog.pdark.de/2010/05/28/type-safe-object-map/
Event type "explosion" is not a problem. In fact it is a desirable approach as it allows the components to be independent of one another. I wouldn't necessarily make all events inherit from a single superclass unless it gives you a lot of reusable code because it can cause dependencies to start proliferating.
I would put the event types in a separate project that will be a dependency of both the publisher and consumer.
What is your communication mechanism for these events between components? JMS? If so you could also consider making your messages XML and using JAXB.
I would definitely discount the map approach as it destroys any hope of polymorphism or any other oo niceties.
I'm doing a favor for an engineer friend by making him a program that helps him with the scheduling of his factory's production. Each type of product is broken down to a set of steps (they share a lot of them, but there are a few differences).
The programming issue:
Each time a new production process is registered I display a number of checkboxes representing the before mentioned steps. He can choose which steps he needs added for this particular product. If he checks a checkbox, two (or more) textfields appear where he can add additional information (starting date, duration, comments, etc...). My problem is that this is a lot of individual components and I am unsure how to handle them. Since I will need to have access to all of them at some point (the checkboxes to see if that step is needed and all the textfields for the data) I was thinking of having them all as fields, but that doesn't feel right...
Another approach could be to make a container class that groups the textfields together with the checkbox. Something like this:
ArrayList<MyComponentGroup> group;
for (MyComponentGroup cg : group) {
if (cg.getCheckBox().isSelected()) {
//access and read the data from all the textfields in this object
}
}
What is the Java programming convention or the most commonly used method to handle this situation?
Here's what I would do when dealing with tons of components and similar requirements:
I would model the relationship between options (available through checkbox selections) and the related data to fill (requirements). This model may already be available for you.
I would attempt to use PropertyEditor instances and map them to model elements.
When the time comes to save or use the data filled by the user, I would just walk the model represented on the screen, grab the associated editors and deal with the value of those editors.
I think that the approach that I described above will give you less work and potentially and it will bring more flexibility for your friend.
You'd only pay the initial cost of getting the components relationships/dependencies in a nice model as well as registering the relevant PropertyEditors for visual editing.
One approach is to consistently give each JComponent a unique name. Use something hierarchical to fit the complex process, like "Whites.Rinsecycle.enableCB". For completeness, store this String as a clientProperty in the JComponent. Then you can use that as a key in a large Map to access all the components.
Maybe not the most "elegant" (I'd tend to go with a hierarchy of JPanels with relevant fields) but for a slightly quick and dirty, moderate sized project this is reasonable.
Wicket has many implementations of AbstractRepeaters: ListView, DataView, GridView, Loop, PropertyListView etc.
Personally, I find it hard to determine which view would be ideal for which scenario. I usually stick to DataView but that's simply because I'm used to it. Maybe GridView would be better for scenario A, a PropertyListView for B, ....
Is anyone aware of a blog or any tutorial where the differences of the views are explained or anyone who can explain which view is best for which use case?
Wicket has a lot of additional, trivial classes, which is causing your confusion. Different components are better for different scenarios, but there are a lot of Wicket components for rare cases that don't add any real complexity.
For example, RequiredTextField is an entire class that is equivalent to:
TextField x = new TextField("text");
x.setRequired(true);
I presume this stems from an older version where setting required was more complicated, but it's still there to cause some confusion.
Many of your repeaters are similar. PropertyListView just wraps the model in a CompoundPropertyModel, making property expressions easier (see below). However, you could easily make this change yourself.
So, here is my quick summary as I have been unable to find an up-to-date blog post as you've described:
RepeatingView - very useful when you do not have a list or you are adding different types of components (and therefore different internal markup).
ListView - useful if you have a List and you're displaying the whole thing. Sadly, it does not work with other sorted collections.
DataView - useful if you are loading from a Database. Additional methods allow you to easily sort, page, and modify the data set.
PropertyListView - useful if you are simply displaying values via a property expression. Allows you to do
item.add(new Label("name"));
instead of
item.add(new Label("name", new PropertyModel<String>(item.getModel(), "name")))
Loop - useful if you want to repeat an Integer number of times instead of a set list of data. This would be equivalent to a ListView whose model object is a List<Integer> filled with integers from 0 to length
GridView - useful for taking a single list (e.g. 21 strings) and using two sets of markup (inner/outer) to display that list in groups (e.g. a 7x3 grid). It assumes, however, that your markup uses certain wicket:id's, which is not well documented. I think you would be better off with a pair of nested RepeatingView components, which accomplish the same thing.
Hope that helps!
Consider a simple POJO Java Object:
class MyObj {
String a, b;
Integer c;
}
My application executes a Struts action and sets a Collection of these on the Http Request:
request.setAttribute("myObjects", getCollectionOfMyObj());
The action then forwards to a JSP page, and this is where my questions centres:
What is the simplest way I can
bind this collection into a grid,
such that is renders a table with
three columns (a, b, c) and one row
per object in the passed collection.
A key characteristic I require,
is that I can add a new field to the
Java object and it requires no (or
minimal) changes to the UI code,
i.e. the object is being
introspected and displayed so that I don't have D-R-Y
violations in the UI?
How can I make the grid
editable, so that any changes to a
row are reflected back into a new (or the existing)
Collection of Java objects in the
request for use by other Actions
(e.g. to persist the changes)?
Many thanks in advance for your help, please let me know if you need further clarification.
Arun
If you need to display only your data without editing it I recommend using displaytag, its a custom tag that is used to render tabulated data, and its highly customizable.
However, If you want to edit your data, I advise you to move to some javascript solutions, dhtmlxgrid is one good option, there are many many other solutions in javascript that you could use, however here you will be working with XML data and AJAX, this would be easier to you, and it will make your table more dynamic to changes. After mastering your chosen javascript-solution that best fits you, you could wrap it into a custom tag and generalize it ;-).
There are tons of different ways you can achieve the above. But since you are already using Struts I would recommend stick to Struts UI Tags . It will make things little bit easy to start with
Say, You have an application which lists down users in your application. Ideally, if you were writing code to achieve this in Java, irrespective of what your UI layer is, I would think that you would write code which retrieves result set from the database and maps it to your application object. So, in this scenario, you are looking at your ORM / Data layer doing its thing and creating a list of "User" objects.
Let's assume that your User object looks as follows:
public class User {
private String userName;
private int userid;
}
You can now use this list of "User" objects, in any UI. (Swing / Webapp).
Now, imagine a scenario, where you have to list down the userName and a count of say, departments or whatever and this is a very specific screen in a webapp. So you are looking a object structure like this:
public class UserViewBean {
private String userName;
private int countDepartments;
}
The easiest way of doing this is writing SQL for retrieving department count along with user name in one query. If I you to write such a query, where would you have this query? In your jsp? But, if you were doing this in a MVC framework, would you move this query to your data layer, get the result set, convert it to UserViewBean and send it to your jsp in request scope? If you write queries directly into jsps/if you are making use of connections directly in JSP, isn't that a bad practice?
I know, some of you might say, 'hey, you got your object composition wrong! if department is linked to user, you would want to create a list of departments in your User object' - Yes, I agree. But, think of this scenario - Say, I don't need this department count information anywhere else in my application other than this one screen. Are you saying that whereever I load my User object from the database, I would have to load a list of dependency objects, even if I won't be using them? How long will your object graph get with all the relational integrity? Yes, I do know that you have ORMs for this very reason, so that you get benefits of lazy loading and stuff, but I dont have the privilage to use one.
The bottom line question here is:
Would you write sqls in to your JSP if it serves just one screen? OR
Would you compose an anemic object
that caters to your view and make
your business layer return this
object for this screen - just to make
it look a bit OOish? OR
irrespective of what your screen
demands, would you compose your
objects such that an object graph
is loaded and you would get the
size of that list?
What is the best practice here?
I would never put SQL in a JSP. I would use Spring MVC or Struts controllers, or servlets to contain all of that type of logic. It allows for better error handling among other things (you can forward to error pages when queries fail).
If you really must do this, use the JSTL SQL tags.
Personally, I take a simple pragmatic approach. If I was writing screen that just displays a list of users with their deparment count, so that the entire code is maybe a page, and I don't expect this code to be used on any other screen, I'd probably just throw it all in the JSP. Yes, I know there are all the MVC purists who will say, "business logic should never go in a JSP". But aside from a dogmatic rule, why not? What would it hurt in a case like this?
If I found that I had two screens, maybe one where I had to simply display the list and another where I had to do some additional processing on the list, then I would certainly pull the common code out into a class that was called from both places.
I believe that the criteria should be: What produces the most maintainable code? What is shortest and easiest to understand? What produces the least linkages between modules? etc.
I adamantly refuse to accept the principle: "In some cases this approach leads to problems, therefore never use it." If sometimes it leads to problems, then don't use it in the cases where it leads to problems. Or worse, "Somebody wrote it in a book, therefore it cannot be questioned." Sure, there are some rules that are valid 99.99% of the time, so it gets to be pointless to check if this particular case is an exception. But there are lots of rules that are good 51% of the time and people leap from "mostly" to "always".
Would you write sqls in to your JSP if it serves just one screen?
In a prototype, just as a quick hack - maybe. In any other situation, not to mention a production environment - NEVER.
Use a proper MVC framework to separate business logic from presentation.
I am not even sure that JSP should be used, but for trivial applications. If you really have to use them, use MVC pattern or encapsulate your logic in a JavaBean.
Have a look at JPA which allow you to do object manipulations which then is persisted in the database
I wouldn't put SQL in a jsp for fear of forgetting it in future maintenance. Think of the poor guy maintaining your code-- poor guy = you in 10 months or whenever the database is restructured-- and at least put all SQL in the same general region.