How to model POJO from Vaadin UI? (Best practice) - java

I am working on a PDF Invoice generator in Vaadin 7. The code as it stands at the time of this writing can be found here. The repo includes a crude class diagram.
My question concerns the best practice of collecting the user input from the TextField and other Vaadin components to create an instance of Invoice.
Currently it works like this:
When the user clicks the button to generate the pdf, the class VaadinInvoiceGui (a Panel) calls the method createPdf(VaadinInvoiceGui gui) in the class VaadinInvoiceController.
VaadinInvoiceController calls method getInvoiceFromForm(VaadinInvoiceGui gui) in class InvoiceMapperImpl.
InvoiceMapperIml creates and returns an Invoice (POJO) by calling get methods in the VaadinInvoiceGui that gets passed to it. These getters return the values of the components in the view.
VaadinInvoiceController takes the Invoice returned by InvoiceMapperImpl and goes on to create pdf from it etc..
The getters in VaadinInvoiceGui look like this.
public String getCustomerName() {
return infoPanel.getCustomerNameTextField().getValue().toString();
}
public String getCustomerStreet() {
return infoPanel.getCustomerStreetTextField().getValue().toString();
}
public String getCustomerCity() {
return infoPanel.getCustomerCityTextField().getValue().toString();
}
...
I really don't feel like it's a good idea to pass the whole gui class to the controller and especially to the mapper, but I'm not sure what would be a better way of doing it. I could change the method createPdf(VaadinInvoiceGui gui) to something like createPdf(String customer name, String customerStreet, ...) but the number of parameters of the method would grow huge. I could do it using setters but then it would basically be doing the object mapping in the gui which doesn't seem like a very clean idea either.
What is the proper way of doing this?

Write a bean for the data to pass around as your model. Then use the FieldGroup to bind between model and form. Wrap the model as BeanItem<Model>. Binding is either done by name (convention) or by annotation #PropertyId.
master-detail-example: https://vaadin.com/wiki/-/wiki/Main/Creating+a+master-details+view+for+editing+persons
general infos: https://vaadin.com/book/vaadin7/-/page/datamodel.html
binding in forms: https://vaadin.com/book/vaadin7/-/page/datamodel.itembinding.html

Related

Accessing static form from GUIbuilder via code

I am a total newbie with Codename One and have been studying up by watching the various tutorials etc. But there is a basic concept that I just can't seem to grasp.
When I design a form in the GUIBuilder, how do I reference the form from my code?
I.e. I designed my form in the UI Builder. Now in my main source code, I would like to add a toolbar to the form. Inside the GUIBuilder the form is called "Main", but statements such as Main.show(), Main.hide() etc do not work.
I managed to get the form "imported" for lack of a better word by using
private Form home;
...
...
home=Display.getInstance().getCurrent();
...
home.getToolbar().addCommandToOverflowMenu(edit);
Which works, but surely there must be a way of accessing the form directly without having to get the currently active instance? i.e. Something like
Main.getToolbar().addCommandToOverflowMenu(edit);
You can override the beforeShow() and postShow() of your form and just reference the parameter which represents the form.
To add commands, it's advisable that you do that in the beforeShow() method and long process like remote data fetching should be done in postShow().
For instance, let's say your form name is Main and was created in GUI Builder, you can do the following:
#Override
protected void beforeMain(final Form f) {
f.removeAllCommands();
Toolbar toolbar = new Toolbar();
f.setToolbar(toolbar);
toolbar.setTitleComponent(new Label("My Form Name", "Title"));
toolbar.addCommandToOverflowMenu(edit);
toolbar.addCommandToRightBar(backCommand);
f.setBackCommand(backCommand);
...
}
#Override
protected void postMain(final Form f) {
//fetch remote data here
...
}

How to put DAO and GUI together with MVC

I'm creating a Java Application that represents a school. My aim is to keep the application open for new features, so I'm trying to apply some Design Patterns to it.
What I have so far is a HSQLDB connected to my program.
In the database one can store
pupils
courses
years
exams
grades
The current structure is as follows:
there are classes for each of the objects that contain the attributes + setters and getters
for each object there is a DAO that manages the CRUD operations on the DB
each DAO implements a GenericDAO interface
If i want to create a new pupil i can call:
PupilDao pupil = new PupilDao();
pupil.connectToDB();
pupil.add(new Pupil(name, age,...));
pupil.disconnectDB();
Every DAOs connectToDB() and disconnectDB() methods point to a DBuser-Classes connect() and disconnect() methods. So if I want to change the connection, there's only one place to do so.
So far, those operations work.
My questions are the:
1.) Is the current design a proper use of DAOs? I'm asking because i would rather have one
Dao for all objects because right now there's a lot of repetitive code in the DAOs. (e.g. get, update, delete...)
Now that the DB-Access works, I want to create a GUI using Swing. I have some experience doing this although not with the MVC-Pattern.
2.) As far as I understand, the DAOs + my object classes would be the Model here. Is that correct?
3.) My understanding of MVC is that in my View-Class (i.e. the GUI) I set listeners for my actions which point to different Controller-Classes implementing the ActionListener interface and in my Controller-Classes I would for example have a actionPerformed() that creates a new Pupil (using the DAO / Model - Classes). Am I on the right track here?
4.) Is it favourable to have one big Controller managing all actions over having different Controllers?
I'm asking those questions because I read/watched a lot about patterns/OO-Design and want to make sure my understanding is correct.
Furthermore I highly appreciate your thoughts on my design! What could be done more flexible or better to maintain later?
Thanks in advance for every suggestion and sorry for the somewhat long explanation!
Felix
While I still can't answer my questions for sure, I think I found a suitable way
for me and want to share the design (suggestions/answers are still appreciated!).
1) The applications entry-point is the main-application class (MVC.class). This class creates the
view using a main-controller. Here's the code:
public static void main(String[] args) {
// view is declared as class-variable
view = new View();
MainController mcontroll = new MainController(view);
view.getFrame().setVisible(true);
}
The main-controller only takes the view as parameter as its only purpose is to display the view.
As stated in my post above my aim was to display different database tables from a HSQLDB and modify them.
2) In the menubar there are entries for managing years, courses, etc. If one entry is clicked, the controller for the clicked category (e.g. years) takes control. Here is, how the controller is changed:
public void addManageYearsListener(ActionListener listener) {
mntmYears.addActionListener(listener);
}
The above method is located in the view class (i.e. the GUI class) but the main-controller implements the actionPerformed()-method. To do that, the main-controller calls the method defined in the view in his constructor like that:
public MainController(View view) {
this.view = view;
this.view.addManageCoursesListener(new ManageCourses());
this.view.addManageYearsListener(new ManageYears());
}
The corresponding class "ManageYears" is then defined as inner class:
class ManageYears implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
MVC mvc = new MVC("years");
}
}
What happens here is that when the menuitem is clicked, the main-controller "hears" the click (cause he is listening to it) and calls the main class again, although this time with a string as parameter. The constructor of the main class checks the string and sets the model and the controller that is needed. See here:
if (controller.equals("year")) {
YearDaoImpl yearDao = new YearDaoImpl();
YearController ycontroller = new YearController(view, yearDao);
}
"controller" is the string that is passed with the constructor and "yearDao" is the Data Access Object that handles the CRUD-operations which have to do with the object "year" (which is a class itself).
So now it's possible to switch controllers at runtime.
3) The year controller sets the ActionListeners for a add and remove button in his constructor (just like the main controller did for the menu item), get's the data from the database (via the yearDao) and sets the table model in the view (view has a setTableModel()-method for that) passing the returned ResultSet as parameter of the table Model class:
public void showYears() {
try {
con = yearDao.connectToDB();
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM YEARS;");
view.setTableModel(new YearTableModel(rs));
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
As you can see, the yearDao has a connectToDB()-method that returns a connection (the connection is actually gotten from a c3p0 connection pool) which is then used to get a ResulSet of years from the database. The setTableModel()-method is then called setting the YearTableModel - a custom class extending AbstractTableModel and passing the ResulSet as parameter.
With the explained design it is now possible to:
1.) only have one table in the GUI that is populated with different database outputs.
2.) seperate the view from the data (which is what this whole fuss is about ;-)).
3.) add new controllers or models when needed without changing a lot of code.
As mentioned at the beginning I still appreciate every suggestion or improvement!
If you made it till the end of this post, I hope you found something to use in your own program!
regards,
Felix

How to cleanly deal with structured selections in eclipse?

I'm writing an eclipse plugin, where I want to contribute an action to the JDT package explorer. In order for the action to be executed, there must be two different files selected. Therefore I retrieve the active selection of the JDT package explorer in the command handler for that action. That is where my problem is.
Currently the code that extracts the selected files from IStructuredSelection involves multiple local variables with multiple if statements and multiple returns in about 30 lines of code. And of course this code looks at least a bit ugly.
What concept(s) and or patterns should I use to make this code more cleaner?
The eclipse platform recommends to use the adapter pattern. So I thought of creating a pojo like this:
public class FooCommandArgs {
private IFile xmlFile;
private IFile csvFile;
//getters and setters here ...
}
and creating the necessary adapters for it from IStructuredSelection. However doing this would just move the ugly code to some other places.
So as the field names suggest, each item I want to extract from the IStructuredSelection has to fulfill some conditions. My idea is to use bean validation api for this. The pojo would then look like this:
public class FooCommandArgs {
#NotNull
#FileExtension("xml")
#Content(type=ContentType.XML, value="http://my.schema.location/schema.xsd")
private IFile xmlFile;
#NotNull
#FileExtension("csv")
private IFile csvFile;
//getters and setters here ...
}
The Validator interface of the bean validation api provides the method <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) which I could use for that. I just would have to introspect the java bean properties and then invoke that method for every combination of an IStructuredSelection item and pojo property. If the result is that every item could be assigned to a bean property with no constraint violations than I can just go on with handling the actual command. Ambiguities might as well be handled.
EDIT:
I have implemented this suggestion and it works out quite nice. Using this technique, it is also very easy to explain to a user programmatically, why a certain command isn't enabled or can not be executed.
I don't want to forget to mention JCommander at this point, which is the inspiration for this idea.

Using Stripes, what is the best pattern for Show/Update/etc Action Beans?

I have been wrestling with this problem for a while. I would like to use the same Stripes ActionBean for show and update actions. However, I have not been able to figure out how to do this in a clean way that allows reliable binding, validation, and verification of object ownership by the current user.
For example, lets say our action bean takes a postingId. The posting belongs to a user, which is logged in. We might have something like this:
#UrlBinding("/posting/{postingId}")
#RolesAllowed({ "USER" })
public class PostingActionBean extends BaseActionBean
Now, for the show action, we could define:
private int postingId; // assume the parameter in #UrlBinding above was renamed
private Posting posting;
And now use #After(stages = LifecycleStage.BindingAndValidation) to fetch the Posting. Our #After function can verify that the currently logged in user owns the posting. We must use #After, not #Before, because the postingId won't have been bound to the parameter before hand.
However, for an update function, you want to bind the Posting object to the Posting variable using #Before, not #After, so that the returned form entries get applied on top of the existing Posting object, instead of onto an empty stub.
A custom TypeConverter<T> would work well here, but because the session isn't available from the TypeConverter interface, its difficult to validate ownership of the object during binding.
The only solution I can see is to use two separate action beans, one for show, and one for update. If you do this however, the <stripes:form> tag and its downstream tags won't correctly populate the values of the form, because the beanclass or action tags must map back to the same ActionBean.
As far as I can see, the Stripes model only holds together when manipulating simple (none POJO) parameters. In any other case, you seem to run into a catch-22 of binding your object from your data store and overwriting it with updates sent from the client.
I've got to be missing something. What is the best practice from experienced Stripes users?
In my opinion, authorisation is orthogonal to object hydration. By this, I mean that you should separate the concerns of object hydration (in this case, using a postingId and turning it into a Posting) away from determining whether a user has authorisation to perform operations on that object (like show, update, delete, etc.,).
For object hydration, I use a TypeConverter<T>, and I hydrate the object without regard to the session user. Then inside my ActionBean I have a guard around the setter, thus...
public void setPosting(Posting posting) {
if (accessible(posting)) this.posting = posting;
}
where accessible(posting) looks something like this...
private boolean accessible(Posting posting) {
return authorisationChecker.isAuthorised(whoAmI(), posting);
}
Then your show() event method would look like this...
public Resolution show() {
if (posting == null) return NOT_FOUND;
return new ForwardResolution("/WEB-INF/jsp/posting.jsp");
}
Separately, when I use Stripes I often have multiple events (like "show", or "update") within the same Stripes ActionBean. For me it makes sense to group operations (verbs) around a related noun.
Using clean URLs, your ActionBean annotations would look like this...
#UrlBinding("/posting/{$event}/{posting}")
#RolesAllowed({ "USER" })
public class PostingActionBean extends BaseActionBean
...where {$event} is the name of your event method (i.e. "show" or "update"). Note that I am using {posting}, and not {postingId}.
For completeness, here is what your update() event method might look like...
public Resolution update() {
if (posting == null) throw new UnauthorisedAccessException();
postingService.saveOrUpdate(posting);
message("posting.save.confirmation");
return new RedirectResolution(PostingsAction.class);
}

Example of Passive View design pattern using JSP and POJOs

Im trying to understand how the Passive View design pattern works for simple web apps.
Can someone provide a simple example of this pattern using these requirements:
View is a JSP that prints HELLO WORLD!
Data is persisted in the data store as "hello world", call to retrieve data can be a stub
Provide example files for pieces (presenter, view, etc) and denote which piece of the pattern each file represents.
No frameworks/DSLs should be used other than jstl/el (which are optional)
Thanks
UPDATE 1: Adding my understanding of how this would be structured.
// Presenter; responsible for multiple "rendtions" of a particular view (show, index, edit, summary, etc.)
public class HelloWorldPresenter {
private HttpServletRequest request;
private DataStore dateStore;
public HelloWorldPresenter(HttpServletRequest request) {
this.request = request;
this.dataStore = DataStoreUtil.getDataStore(request);
// Do a bunch of other inits that all getXXXModels() will use
}
public getShowModel() {
HelloWorldShowModel model = new HelloWorldShowModel();
String tmp = makeLoud(this.dataStore.getMyData()); // Stub method
model.setText(tmp);
return model;
}
private String makeLoud(String str) {
return str.toUpperCase() + "!";
}
}
// Model used by view
public class HelloWorldShowModel {
private String text;
public getText() { return this.text };
public setText(String text) { this.text = text; }
}
// View
show.jsp
<c:set var="model" value="new HelloWorldPresenter.getShowModel()"/>
${model.text} -> HELLO WORLD!
or
<% HelloWorldShowModel model = new HelloWorldPresenter(request).getShowModel() %>
<%= model.getText() %>
The things I'm unsure about are:
How the Presenter would be exposed to the View (JSP) since the View shouldnt know about the presenter. I may be mixing semantics though, and the HelloWorldShowModel (which is acting as a "ViewModel" of sorts, is what shouldnt know about the Presenter).
Should I even have the HelloViewShowModel abstraction, or should I simply have a method getText() on my Presenter which is called within the JSP to get the requested text.
If I do have multiple "views" for a resource (ex. Show, Index, Edit, Summary, etc.), should I have multiple Presenters? How should this logic be broken up? Multiple presenters that inherit from a Shared presenter? Should each presenter only be responsible for returning one ViewModel?
I've read through Fowlers articles as well as a number of other write-ups - the problem (for me) is they are written in the context of .NET apps, and I dont understand how all their objects get wired up.
I hope this will aleve concerns of me being "lazy" and looking for a "hand-out" answer :)
With the requirements you state I would say the pattern can't be implemented. If you consider the view to be a JSP then there are no means a controller could actively set any values of UI components. (To me this is the core of the pattern: the controller actually updates the view actively by setting values of input / output UI components, not the other way round (view getting fields from a model object). This can't be done with the above techniques as a JSP has no means to be accessesd this way.
It could be implemented in a web environment based on Javascript though. Consider your view being the DOM and your controller being a Javascript component. The JS controller has direct write access to the DOM and therefore could update single fields actively like the pattern suggests. To update / get the model the JS controller could talk to a server-side system e. g. based on a REST API via Ajax.
A plain templating solution like JSP cannot be used to offload all logic to controller, at least in real world cases. I think this kind of thing can be achieved with JSF.
If you want to learn about how things are done I recommend you to take a look at Spring MVC. It's source code can teach you a lot.

Categories

Resources