GWT-Platform revealing presenters together - java

Hey so I am just learning the gwtp framework and I have come across a bit of a dilemma. I have a LayoutPresenter at the top level that has a main content slot and menu content slot and I am trying to find a way to bind my presenters for each slot together if possible so when the main content is revealed it will automatically show the correct side menu. Currently I have a static boolean in the Menu's Presenter that get updated onReveal and onHide. I can then check if the menu is visible when the main content is revealed and if not I reveal it.
public class MenuPresenter extends Presenter<MenuPresenter.MyView, MenuPresenter.MyProxy> {
private static boolean hidden = true;
...
#Override
protected void revealInParent() {
RevealContentEvent.fire(this, LayoutPresenter.SIDE, this);
}
#Override
protected void onReveal(){
super.onReveal();
hidden = false;
}
#Override
protected void onHide(){
super.onHide();
hidden = true;
}
public static boolean isHidden(){
return hidden;
}
}
Then in The main content Presenter:
public class ContentPresenter extends
Presenter<ContentPresenter.MyView, ContentPresenter.MyProxy> {
...
private final DispatchAsync dispather;
private final PlaceManager placeManager;
#Inject
public PhoneCallPresenter(final EventBus eventBus, final MyView view, final MyProxy proxy, final DispatchAsync dispatcher, final PlaceManager placeManager) {
super(eventBus, view, proxy);
this.dispather = dispatcher;
this.placeManager = placeManager;
}
#Override
protected void revealInParent() {
RevealContentEvent.fire(this, LayoutPresenter.CONTENT, this);
}
#Override
protected void onReveal() {
super.onReveal();
if (MenuPresenter.isHidden()){
placeManager.revealPlace(new PlaceRequest(NameTokens.menu));
}
}
}

As far as I understood the question, you want to have different side-menus for different main contents.
In this case there are two solutions:
Treat the menu as a normal Presenter (you will probably have multiple of them for each main content type). You just need to annotate the corresponding MenuPresenter with the same history token as your main content Presenter. So for the above example you would have a PhoneCallMenuPresenter that is annotated with the same history token as your PhoneCallPresenter. When you navigate to /phonecall (or whatever your history token is), both PhoneCallPresenter and PhoneCallMenuPresenter will be revealed automatically . (you don't have to do anything).
In case you want to have only one MenuPresenter and put the logic what to display in the Presenter itself, I would recommend to use a PresenterWidget instead of a normal Presenter. The MenuPresenterWidget will be injected into the LayoutPresenter and will be added to the LayoutPresenter.SIDE slot. You can define a setter for the MenuPresenterWidget to specify which main content is currently displayed (the setter will be called from the LayoutPresenter or you can override the onReset() method and check the current place request and decide what to display in the menu.
For solution 1 you have to have one MenuPresenter for each main content Presenter and potentially many code lines will be redundant (you could create a base MenuPresenter and derive from it). So in case you have a lot of business logic in the side-menu which is quite different from main content to main content, I would go with solution 1. In case you only display different links the overhead of creating a MenuPresenter per main content Presenter might be to high and I would go with solution 2 and create only one MenuPresenterWidget for all main content types and always show it.

Related

Is this approach bad practice (memory leaking?)

I have created a class that extends Android's WebViewClient so I can make it a 'preview' only client - i.e. most navigation is not allowed.
When a user tries to navigate, I want to pop up a toast to remind them that they are in a limited preview view and that they can't navigate further.
BUT toast requires an activity Context.
In order to make the Context available I assign a context to a variable (appContext)in the class's constructor as follows:
public class nonInteractiveWebViewClient extends WebViewClient {
public boolean canBrowse = false;
public Context appContext;
public nonInteractiveWebViewClient(Context context) {
appContext = context;
}
#Override
public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
return true;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String host = Uri.parse(view.getUrl()).getHost();
canBrowse = // logic here to determine whether to allow navigation
if (canBrowse) {
return false;
} else {
Toast.makeText(appContext, appContext.getString(R.string.link_test_preview_only), Toast.LENGTH_SHORT).show();
return true;
}
}
}
When I create the nonInteractiveWebViewClient object in the calling activity I call it with getApplicationContext() to pass the context to the constructor.
Is this a bad idea?
As #sajjad has noted before, shouldOverrideUrlLoading has access to a view and getContext() can be run on a view, so the appContext variable is redundant in this exmaple, however...
I am also intending to use this pattern in another class which houses a number of methods that are used by multiple activities and that needs access to the activity context in a number of it's methods. These methods are standalone functions that do not extend any existing methods that might have access to a context. Using the approach above in this other class will both simplify my code and cut down on the number of calls to getApplicationContext that the calling activities need to make, but I am concerned that it may cause a memory leak or something.
Is this a bad approach?
(When answering, please appreciate that I am an engineer and while I have some understanding of the underlying theories of programming I am by no means a CS. I like to write code to be as modular as possibel and to avoid duplication of code as much as possible, hence my tackling this issue this way.)

Java / Android - How can I know that a variable from any instance of a class is true?

This question is not manly for Android, but I will use an android example to explain.
I want to create a class that should override the method onTouchListener, to be used on any object that uses those touch methods.
Since after a touch input, the method starts a function, and since it's a class, it can be instantiate several times (and I want to be instantiate several times), I want to prevent that two instances are called at the same time.
I guess I could create a variable inside the class, that assured that if it's true, it can run the method, but I need to check it for all of the class instances.
And since I want to make this a library, I need to do this inside the class itself.
So my question is,
(Java Question) How can I know that a variable from any instance of a class is true?
(Android Question) Or if this is not possible, How can I prevent multiple touch events at the same time?
You could achieve that with static data and/or method for this class. A static element can be accessible from anywhere using the class name:
ex: MyClass.isAlreadyRunning();
you could for example store in an array all the running status of the instances, and create a static method that checks the array if one is already running.
You can think about making a Singleton Class. Wiki Link
Singleton classes allows to create ONLY one instance/object of that class and then reuse it.
You can use a static field in this context. A static field is identicaly for all instances of an class.
You can do it maybe like this:
public Example implements TouchInterface{
private static boolean actuallyRunning = false;
public void touchExecute(){
if(!actuallyRunning){
actuallyRunning = true;
callYourFunction();
actuallyRunning = false;
}
}
}
You can use singleton class if you want one one instance and if you want to handle the multiple touch events
you can disable as soon as your handler start and enable after that.
you can add a time span in normal practice it is one sec but it depends on you handler's complexity
Like this example:
// Make ur activity class to implement View.OnClickListener
public class MenuPricipalScreen extends Activity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
// setup listeners.
findViewById(R.id.imageView2).setOnClickListener(MenuPricipalScreen.this);
findViewById(R.id.imageView3).setOnClickListener(MenuPricipalScreen.this);
....
}
.
.
.
// variable to track event time
private long mLastClickTime = 0;
//View.OnClickListener.onClick method defination
#Override
public void onClick(View v) {
// Preventing multiple clicks, using threshold of 1 second
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
// Handle button clicks
if (v == R.id.imageView2) {
// Do ur stuff.
}
else if (v == R.id.imageView2) {
// Do ur stuff.
}
...
}
.
.`.
You should put "public synchronized" void, so it will prevent to be called in parallel. If you must override, then put a synchronized object in the method so it will do the same.

Passing the Model to the View in MVC

I've always understood MVC to mean the Model shouldn't know anything about the View and vice versa. However in my university course an example of a View using the MVC pattern is given like:
class View implements Updatable {
private final JButton button = new JButton("Press Me!");
private final JTextField textField = new JTextField(10);
//some setup of the button and textfield
public void update(Model model) {
if (model.morePressesAllowed()) {
textField.setText(String.valueOf(model.count()));
} else {
textField.setText("Too Many!");
button.setEnabled(false);
}
}
}
It seems odd to me that the view must know what methods the model has. It seems like it would be better in terms of the MVC pattern to expose the button and textfield to the controller, and have the update method on the controller?
The model just increments a number and if it gets to 5 then the morePressesAllowed returns false.
Also the model has a list of Updatable, and when the counter changes it loops through the updatables and calls update, while this is better than having a list Views, it still seems like the Controller should be responsible for telling the view when the model changes?
EDIT: The model is:
class Model {
private final List<Updatable> views = new ArrayList<Updatable>();
private int count;
private boolean morePressesAllowed = true;
public void addObserver(Updatable observer) {
views.add(observer);
}
public void increment() {
count++;
if (count >= 5) {
morePressesAllowed = false;
}
notifyObservers();
}
private void notifyObservers() {
for (Updatable view : views) {
view.update(this);
}
}
}
The Controller/Main class: (also shouldn't the controller create the model and view and be normal public class?)
public class GuiApp {
private View view = new View(new Controller());
private Model pressCounter = new Model();
class Controller implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
pressCounter.increment();
}
}
GuiApp() {
pressCounter.addObserver(view);
}
}
Also I actually prefer this to something like this: http://www.tutorialspoint.com/design_pattern/mvc_pattern.htm Because in that the controller is just wrapping a bunch of methods of the view and model, which while it seems more MVC like in that the Model and View don't know anything about each other, it just seems less efficient and more complex?
It seems like it would be better in terms of the MVC pattern to expose the button and textfield to the controller, and have the update method on the controller?
This would create a coupling between the view and the controller. It is important that each layer knows as little about one another as possible. You don't want a controller that is dependant on the existence of some text boxes or buttons. You want the controller to pass the data back to the view, and not care what happens to it beyond then. That is the job of the view. That is the whole point of delegation.
Also the model has a list of Updatable, and when the counter changes it loops through the updatables and calls update, while this is better than having a list Views, it still seems like the Controller should be responsible for telling the view when the model changes?
You're correct. It is not the role of the view to call a method on the Model. Again, this creates an undesirable coupling.
also shouldn't the controller create the model and view and be normal public class?
Yes. More often than not, I see the controller communicate with the model layer, or some service, that then returns the models that are then delegated to the view.
Because in that the controller is just wrapping a bunch of methods of the view and model, which while it seems more MVC like in that the Model and View don't know anything about each other, it just seems less efficient and more complex?
These methods are known as Proxy Methods. Methods that simply delegate the call to something else. It's helpful when you're trying to maintain an appropriate separation of concerns in your architecture. It depends on your definition of complex. Yes, it adds more methods to your controller. Then again, when the next developer comes along, if he or she can make the assumption, safely, that your application strictly follows an MVC architecture, they will have a much easier time developing against your code, as opposed to having to work out your micro-optimisations and "work arounds".

Testing Presenters in MVP GWT application

I have a simple application and want to make it testable. I m new in this area.
Here is a simple Presenter, taking in mind this code ,could you advice or give me some example how to test it.
public class SomePresenter extends Presenter<MainPanelPresenter.Display>
{
public interface Display extends WidgetDisplay
{
HasClickHandlers getAddButton();
HasClickHandlers getDeleteButton();
void setData(ArrayList<Person> data);
ArrayList<String> getSelectedRows();
Widget asWidget();
}
private final DispatchAsync dispatcher;
public static final Place PLACE = new Place("main");
#Inject
public SomePresenter(DispatchAsync dispatcher, EventBus eventBus, Display display)
{
super(display, eventBus);
this.dispatcher = dispatcher;
bind();
}
protected void onBind()
{
display.getAddButton().addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
eventBus.fireEvent(new AddButtonEvent());
}
});
display.getDeleteButton().addClickHandler(new ClickHandler()
{
public void onClick(ClickEvent event)
{
ArrayList<String> list = display.getSelectedRows();
deletePerson(list);
}
});
}
....
private void loadDbData()
{
..........
}
private void deletePerson(ArrayList<String> ids)
{
..........
}
}
Edit:
What does the Presenter is, load initial data from db, have 2 buttons add and delete.
When add is press then a new form is load and user is able to input data and save to the db,
delete button just delete person from db.
Thanks
The general idea of unit testing such a class would be, like for any other class :
create Mock version of the dependencies (Display, EventBus, etc...)
set expectations on what the depdencies should do when the Presenter works
exercice the Presenter and check the expectations
However there are a couple of issues with your version of the Presenter :
The loadDbData() method is not showed, but I assumed it means the Presenter also has access to some other component that does the fetching. Can this component be abtracted in a dependency, and mocked liked the rest ?
Then there is the testing of bind(). The only responsibility of your Presenter in this method is to set up callbacks on some buttons provided by the Display. What you want to test is both :
That the callbacks are set
That the set callbacks do the expected things
A few ideas to help with the later :
You can reduce the coupling between Presenter and Button. If possible, change the Display interface from :
Button getAddButton();
to
addAddButtonClickedHandler(ClickHandler);
This means your Presenter does not have to use a Display object that returns actual BUtton
You can reduce the callbacks content to calling a single method, that you can then test in isolation
protected void bind() {
display.addAddButtonClickHandler(new ClickHandler() {
public void onClick(ClickEvent) {
fireAdded();
}
});
}
// The fireAdded function can be tested independenty of the Display, potentially with
// a mock EventBus
protected void fireAdded() {
event.fireEvent(....)
}
If you really want to check that the callbacks are properly set, than you can use a 'Dummy' implementation of the Display class, that provides you a list of all the callbacks, and let you call them
private class DummyDisplay implements Display {
private List<ClickHandler> addButtonClickHandlers;
public void addAddButtonClickHandler(ClickHandler handler) {
addButtonClickHandlers.add(handler);
}
public void fireAddButtonClick() {
for (ClickHandler h in addButtonClickHandlers) {
h.onClick(new ClickEvent());
}
}
// ....
}
Then your test would :
create a presenter with such a dummy display
use bind to set the callbacks
use display.fireAddButtonClick() to simulate a user clicking
check that has the result of the click, the effects of fireAdded are seen
This type of class (that mostly glue other classes together) can tend to be hard to test ; at some point, it the other classes are thoroughly tested it can become slightly counter productive to concentrate on the gluers, rather than the glued.
Hoping this helps.

progress bars + MVC in Java =?

So I have this nice spiffy MVC-architected application in Java Swing, and now I want to add a progress bar, and I'm confused about Good Design Methods to incorporate a JProgressBar into my view. Should I:
add a DefaultBoundedRangeModel to my controller's state, and export it?
class Model {
final private DefaultBoundedRangeModel progress
= new DefaultBoundedRangeModel();
public void getProgressModel() { return progress; }
public void setProgressCount(int i) { progress.setValue(i); }
}
class Controller {
Model model;
int progressCount;
void doSomething()
{
model.setProgressCount(++progressCount);
}
}
class View {
void setup(Model m)
{
JProgressBar progressBar = /* get or create progress bar */ ;
progressBar.setModel(m.getProgressModel());
}
}
/* dilemma: Model allows progress to be exported so technically
all of the progress state could be set by someone else; should it be put
into a read-only wrapper? */
use JGoodies Binding to try to connect the JProgressBar's visual state to my model's state?
class Model {
private int progress;
public void getProgressCount() { return progress; }
public void setProgressCount(int i) { progress = i; }
}
class View {
void setup(Model m)
{
ProgressBar progressBar = /* get or create progress bar */ ;
CallSomeMagicMethodToConnect(m, "progressCount", progressBar, "value");
// is there something that works like the above?
// how do I get it to automatically update???
}
}
or something else???
edit: more specifically: could someone point me to a Good Example of realistic source for an application in Java that has a status bar that includes a progress bar, and has a decent MVC implementation of it?
No (to 1) and NOOOO (to 2). At least in my opinion.
No (to 1): First, DefaultBoundedRangeModel is a javax.swing class. In my opinion, these classes have no place in models. For example, think about the model living on the server, being accessed via RMI - All of the sudden putting a javax.swing class there seems "not right".
However, the real problem is that you're giving a part of your model (the bounded model) to someone else, with no control over events fired or queries made.
No (to 2): Ugh. Binding is fun but (at least in my opinion) should be used to synchronize between UI model and UI components, not between data model and UI model. Again, think what would happen if your data model lived on a remote server, accessed by RMI.
So what? Well, this is only a suggestion, but I'd add an event listener interface and add the standard event listener subscription methods (addListner(...), removeListener(...)). I'd call these listeners from within my model when I have updates going on. Of course, I'd make sure to document the calling thread (or say it cannot be determined) in order for the client (the UI in this case) to be able to synchronize correctly (invokeLater and friends). Since the listener service will be exposed by the controller, this will allow the model to live anywhere (even allowing for listeners to be remotely invoked or pooled). Also, this would decouple the model from the UI, making it possible to build more models containing it (translators / decorators / depending models).
Hope this helps.
I would say, something else.
The problem I have had with MVC, is to define the level of abstraction of the model.
Model could be some sort of objects for the UI components
Model could also be some other sort of objects for the program it self.
and
Model could be as high as business models.
In this case I would have separated model/component pairs for the progress bar and handle them in a separate controller class.
This article describes swing architecture and might clarify the way it uses models inside.
In our app (MVC, about 100 KLOC) we have it like that (pattern Observer, actually):
/**
* Observer on progress changes
*/
public interface IProgressListener {
public void setProgress(ProgressEvent e);
}
public class ProgressEvent extends ... {
private int progressCount;
// setter + getter
...
}
class Model {
public void addProgressListener(IProgressListener l);
protected void fireProgressChange(ProgressEvent e); // call .setProgress() on listeners
}
class Controller {
private Model model;
}
class View extends ProgressBar implements IProgressListener {
...
// IProgressListener implementation
public void setProgress(ProgressEvent e) {
this.setValue(e.getProgress());
}
...
}

Categories