Breaking cyclic dependency in Dagger - dagger

I am very new to dagger--I don't even know yet if it will work for my application
I have a search page that returns the latest news about a given celebrity.
I have written a test to verify that results appear on the page when we search for a popular celebrity.
The page has a searchField, which requires page in its constructor so the web driver I use for my tests can select it.
Celebrity Search Page Test
public class CelebritySearchPageTest {
#Test
public void testSearchResultsForKevinBaconVerifyHisPopularity() {
CelebritySearchPage searchPage = new CelebritySearchPage();
searchPage.searchFor("Kevin Bacon");
Assert.assertTrue(searchPage.getNumberOfResults() > 9999999, "Verify that Kevin Bacon is still relevant");
}
}
Celebrity Search Page
public class CelebritySearchPage extends Page {
#Inject
#Named("search field")
TextField searchField;
public void searchFor(String text) {
searchField.setText(text);
// ...
}
public int getNumberOfResults() {
// ...
}
}
Celebrity Search Page Module
#Module(injects = CelebritySearchPage.class)
public class CelebritySearchPageModule {
#Provides
#Named("search field")
public TextField provideSearchField() {
return new TextField(/* How do I get the page? */, "#searchField");
}
}
Page
public abstract class Page {
// ...
}
Text Field
public class TextField {
protected Page page;
protected String selector;
public TextField(Page page, String selector) {
this.page = page;
this.selector = selector;
}
public void setText(String text) {
// ...
}
}
The problem is that page needs searchField, but searchField needs page. How do I get over this cyclic dependency?
I can't initialize searchField inside of CelebritySearchPage

Consider this:
CelebritySearchPage
public class CelebritySearchPage extends Page {
private final Lazy<TextField> searchField;
// always prefer constructor injection
// avoid #Named if possible, since the compiler cannot check the string
#Inject
CelebritySearchPage(#Named("search field") Lazy<TextField> searchField) {
this.searchField = searchField;
}
}
Text Field
public class TextField {
protected final Lazy<Page> page;
protected final String selector;
#Inject TextField(Lazy<Page> page, String selector) {
this.page = page;
this.selector = selector;
}
/*
Lazy::get()
Return the underlying value, computing the value if necessary. All calls to the same Lazy instance will return the same result.
*/
}
I guess one Lazy should suffice as well.

Related

GWT: Adding a SubmitHandler to a Form without putting logic in View

I have a GWTP PresenterWidget and View pair that contains a simple search form.
Currently I am adding the SubmitHandler to the form by calling the getSearchForm() method of my View, which is bad practice as it references the actual class instead of an interface:
public class HeaderPresenter extends PresenterWidget<HeaderPresenter.MyView>
{
public interface MyView extends View
{
void submitForm();
Form getSearchForm();
}
// ...omitted for brevity
#Inject
public HeaderPresenter(EventBus eventBus, DispatchAsync dispatchAsync, MyView view, PlaceManager placeManager)
{
// ...omitted for brevity
}
#Override
protected void onBind()
{
super.onBind();
getView().getSearchForm().addSubmitHandler(new SubmitHandler()
{
#Override
public void onSubmit(SubmitEvent event)
{
// stops the form submission
event.cancel();
// now we can do our stuff
String query = getView().getSearchQuery();
if(query != "") // don't search for a blank string
{
PlaceRequest request = new PlaceRequest.Builder().nameToken(NameTokens.search).with("q", query).build();
placeManager.revealPlace(request);
}
}
});
}
Is there a way to add the SubmitHandler in the HeaderPresenter, or will I have to put that code in the View?
I'd like to keep as much logic in the Presenter as possible.
I found a discussion on this here, and ended up using option 4 as suggested by Thomas Broyer:
https://groups.google.com/forum/#!topic/google-web-toolkit/Fbo-SEDjRa4

GWT's Editor Framework and GWTP

building on this answer, i try to integrate the GWT editors into a popup presenter widget. What is the right way to do that?
My view looks like this:
public class DeviceEditorDialogView extends
PopupViewWithUiHandlers<DeviceEditorDialogUiHandlers> implements
DeviceEditorDialogPresenterWidget.MyView {
interface Binder extends UiBinder<PopupPanel, DeviceEditorDialogView> {
}
public interface Driver extends SimpleBeanEditorDriver<DeviceDto, DeviceEditorDialogView> {
}
#Inject
DeviceEditorDialogView(Binder uiBinder, EventBus eventBus) {
super(eventBus);
initWidget(uiBinder.createAndBindUi(this));
}
#Override
public SimpleBeanEditorDriver<DeviceDto, ?> createEditorDriver() {
Driver driver = GWT.create(Driver.class);
driver.initialize(this);
return driver;
}
}
and my presenter looks like this:
public class DeviceEditorDialogPresenterWidget extends PresenterWidget<DeviceEditorDialogPresenterWidget.MyView> implements
DeviceEditorDialogUiHandlers {
#Inject
DeviceEditorDialogPresenterWidget(EventBus eventBus,
MyView view) {
super(eventBus, view);
getView().setUiHandlers(this);
}
/**
* {#link LocalDialogPresenterWidget}'s PopupView.
*/
public interface MyView extends PopupView, DevicesEditView<DeviceDto>, HasUiHandlers<DeviceEditorDialogUiHandlers> {
}
private DeviceDto currentDeviceDTO = null;
private SimpleBeanEditorDriver<DeviceDto, ?> driver;
public DeviceDto getCurrentDeviceDTO() {
return currentDeviceDTO;
}
public void setCurrentDeviceDTO(DeviceDto currentDeviceDTO) {
this.currentDeviceDTO = currentDeviceDTO;
}
#Override
protected void onBind() {
super.onBind();
driver = getView().createEditorDriver();
}
//UiHandler Method: Person person = driver.flush();
}
Is this the right approach? What is missing? Currently nothing happens when i try to use it like this:
#Override
public void showDeviceDialog() {
deviceEditorDialog.setCurrentDeviceDTO(new DeviceDto());
addToPopupSlot(deviceEditorDialog);
}
showDeviceDialog is in the parent presenter and called when clicking a button in that parent Presenter, that instantiates the dialog with private final DeviceEditorDialogPresenterWidget deviceEditorDialog;
Thanks!
Here are a few key points that are missing from your code above:
Your DeviceEditorDialogView should implement Editor<DeviceDto>. This is required in order for the fields of DeviceEditorDialogView to be populated with data from you POJO.
Your DeviceEditorDialogView should have child editors that are mapped to fields in your POJO. For example, given the field deviceDto.modelName (type String), you could have a GWT Label named modelName in your DeviceEditorDialogView. This Label implements Editor<String> and will be populated with the modelName from your DeviceDto when you call driver.edit(deviceDto)
You should call driver.initialize(this) only once, in DeviceEditorDialogView's constructor
You should override onReveal() like this:
#Override
public void onReveal() {
super.onReveal();
driver.edit(currentDeviceDTO); // this will populate your view with the data from your POJO
}
This method will be called when the popup is displayed, just after your DeviceEditorDialogPresenterWidget has been addToPopupSlot

Custom Renderer in GWT

I'm trying to create a widget that will render its associated value in a format that is not the same as the native value. For example, if the value (in the database) is "abcde" I want to show "ab.cd.e" on the screen, and if the user types "abcde" I would also want to show "ab.cd.e". If the user types "ab.cd.e" then I would want to store just "abcde" in the database. I am doing this within the GWT editor framework. I have attempted to use the advice from this answer: Converting String to BigDecimal in GWT, but I can't get it to work. Here's what I have in the UiBinder file:
<g:TextBox ui:field='myTextBox' width='300px'/>
And in the associated Java unit:
#UiField
TextBox myTextBox;
...
initWidget(binder.createAndBindUi(this));
new MyValueBox(myTextBox);
And here's the definition of the MyValueBox widget:
public class MyValueBox extends ValueBox<String> {
//=========================================================================
public static class MyRenderer extends AbstractRenderer<String> {
private static MyRenderer _instance;
private static MyRenderer instance() {
if (_instance == null) {
_instance = new MyRenderer();
}
return _instance;
}
#Override
public String render(final String text) {
// validation is required before doing this!
return text.substring(0, 2) + "." + text.substring(2, 4) + "."
+ text.substring(4);
}
}
//=========================================================================
public static class MyParser implements Parser<String> {
private static MyParser _instance;
private static MyParser instance() {
if (_instance == null) {
_instance = new MyParser();
}
return _instance;
}
#Override
public String parse(final CharSequence text) throws ParseException {
return "parsed string";
}
}
//=========================================================================
public MyValueBox(final TextBox valueBox) {
super(valueBox.getElement(), MyRenderer.instance(), MyParser.instance());
}
}
As you can see, I'm trying to wrap the TextBox that was created using UiBinder, but I don't see any effect from this. I know that I'm missing something very simple, and that there is a much easier way to accomplish this, but I'm stumped. Thank you for any suggestions!
--Edit--
I eventually decided to use a CellWidget, which had the added advantage that I can use this code in a cell widget (e.g., a DataGrid), in addition to using it on a panel. I have documented my solution here: GWT: A Custom Cell Example
You are missing to declare your custom Widget in the UIBinder. You need to tie the package to the xml declaration, adding yours to the standard one (called 'g'):
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder' xmlns:g='urn:import:com.google.gwt.user.client.ui' xmlns:myurn='urn:import:mypackage'>
Then you should use your declared urn, and the name of your class when declaring your TextBox in the UIBinder:
<myurn:MyValueBox ui:field='myTextBox' width='300px'/>
======EDIT=====
You should extend ValueBoxBase instead of wrapping TextBox, that way you will get control over the Renderer and the Parser as you intend, now you will be able to use your custom box as a widget from within the UIBinder:
public class CustomText extends ValueBoxBase<String>
{
public CustomText() {
super(Document.get().createTextInputElement(),CustomRenderer.instance(),
CustomParser.instance());
}
private static class CustomRenderer extends AbstractRenderer<String>
{
private static CustomRenderer INSTANCE;
public static CustomRenderer instance() {
if (INSTANCE == null) {
INSTANCE = new CustomRenderer();
}
return INSTANCE;
}
#Override
public String render(String text)
{
return "rendered string";
}
}
private static class CustomParser implements Parser<String>
{
private static CustomParser INSTANCE;
public static CustomParser instance() {
if (INSTANCE == null) {
INSTANCE = new CustomParser();
}
return INSTANCE;
}
#Override
public String parse(CharSequence text) throws ParseException
{
return "parsed string";
}
}
}

Editor not getting ListBox changes

Issue: On load of a form, ParentEditor, a sub-editor, ThisEditor, properly
popluates all its fields including a listbox(dropdown) widget, MyWidget. However,if I select a new option in the listbox and save, it doesn't save the newly selected option; though edits to other widgets are saving fine. It appears that on a driver flush, the editor does not get the value in my listBox. In debug mode, on driver.edit, I can see the TakesValueEditor call setValue(value) on all form widgets including the listbox. But on flush, I can see the TakesValueEditor call its getValue() on other form widgets but
not on my listbox.
The editor hierarchy: ParentEditor > ThisEditor > MyWidget. ParentEditor is the entire form. ThisEditor is a sub-section of the form. MyWidget is a custom listbox in ThisEditor section.
I'm using MVP pattern. Below are sample code snippets of the View and Presenter:
VIEW:
/** ThisEditor is a sub-section of ParentEditor (the Form) and contains a
MyWidget (custom listbox). */
public class ThisEditor extends Composite implements Editor<ThisProxy>, ThisView {
... //rfeDriver interface defined and created here
#UiField
MyWidget my; //getMy and setMy methods in ThisProxy
... //other field declarations
public ThisEditor() {
initWidget(binder.createAndBindUi(this));
}
#Override
public MyView getMy() {
return my;
}
... //other methods
}
/** This is the View interface that MyWidget implements */
public interface MyView extends HasOptions, HasValue<MyProxy>, Focusable {
interface Presenter {
...
}
...
}
public class MyWidget extends Composite implements MyView,
IsEditor<LeafValueEditor<MyProxy>> {
...
#UiField
ListBox listBox; //single-select dropdown
...
public MyWidget() {
initWidget(binder.createAndBindUi(this));
addChangeHandler(); //listen to changes to listBox and setSelectedIndex (?)
}
...
#Override
public int getSelectedIndex() {
return listBox.getSelectedIndex();
}
#Override
public void setSelectedIndex(int index) {
listBox.setSelectedIndex(index);
}
...
/**
* Called by the TakesValueEditor on rfeDriver.edit.
*/
#Override
public MyProxy getValue() {
//ask presenter for the MyProxy object -- presenter calls
//getSelectedIndex() on this widget and returns the object associated
//with the index
return presenter.getValue();
}
/**
* Called by the TakesValueEditor on rfeDriver.flush.
*/
#Override
public void setValue(MyProxy value) {
//pass the value to the presenter to parse and set the index that corresponds
//to this object
presenter.setValue(value);
}
PRESENTER
public class MyPresenter implements MyView.Presenter,
ValueLookupCompleteEventHandler {
...
protected HasOptions view;
private List<MyProxy> myList;
public MyPresenter(ParentPresenter parent) {
//setParent for this child presenter
}
... //methods to set view and create association between view and presenter
#Override
public MyProxy getValue() {
//identify the current selection
String selectedId = view.getValue(view.getSelectedIndex());
if (selectedId != null) {
//iterate myList to find the MyProxy object whose id.equals(selectedId)
for (Iterator<MyProxy> i = myList.iterator(); i.hasNext();) {
MyProxy value = i.next();
if (selectedId.equals(value.getCode().toString())) {
return value;
}
}
}
return null;
}
#Override
public void setValue(MyProxy value) {
//handle null value
String selectedId = value.getCode().toString();
... //verify the value is in myList
//traverse dropdown list and set selected index corresponding to value object
for (int i = 0; i < view.getItemCount(); ++i) {
if (selectedId.equals(view.getValue(i))) {
view.setSelectedIndex(i);
}
}
}
}
I just ran into this same issue. If you look at the source code for the GWT ListBox, you'll se e that it does not implement isEditor. I actually don't think it is a GWT editor component. Hard to understand. I had to code around it.

GWT 2.1 Places example without Activities

does anyone have any examples of how to using Places without using activities for history management. I knocked something up quickly and can see the url changing with browser-back and browser-forward clicks but the display doesn't go anywhere.
I'm using a DecoratedTabPanel and have a SelectionHandler that fires off getPlaceController().goTo(place).
Any ideas would be useful.
Here is a simple piece of code that I've made to demonstrate what you expected. It's based on the GWT and MVP Development document (GWT and MVP)
In this example you navigate between two tabs. On selection, a new history item is created (without any activity). As long as you use browser buttons to go back/forward the page will be updated correctly.
I have defined one place, one activity and its view. I've adjusted AppActivityMapper, AppActivityManager and ClientFactory to my needs. The code is lightweight and doesn't need comments to be understood. I've only put some explanations when it was needed, but if it's not clear do not hesitate to ask.
ExampleView.java
public interface ExampleView extends IsWidget {
void selectTab(int index);
}
ExampleViewImpl.java
public class ExampleViewImpl extends Composite implements ExampleView, SelectionHandler<Integer> {
private DecoratedTabPanel panel;
public ExampleViewImpl() {
panel = new DecoratedTabPanel();
initComposite();
initWidget(panel);
}
private void initComposite() {
panel.add(new HTML("Content 1"), "Tab 1");
panel.add(new HTML("Content 2"), "Tab 2");
panel.selectTab(0);
panel.addSelectionHandler(this);
}
#Override
public void selectTab(int index) {
if (index >=0 && index < panel.getWidgetCount()) {
if (index != panel.getTabBar().getSelectedTab()) {
panel.selectTab(index);
}
}
}
#Override
public void onSelection(SelectionEvent<Integer> event) {
// Fire an history event corresponding to the tab selected
switch (event.getSelectedItem()) {
case 0:
History.newItem("thetabplace:1");
break;
case 1:
History.newItem("thetabplace:2");
break;
}
}
}
ClientFactory.java
public class ClientFactory {
private final EventBus eventBus = new SimpleEventBus();
private final PlaceController placeController = new PlaceController(eventBus);
private final ExampleViewImpl example = new ExampleViewImpl();
public EventBus getEventBus() {
return this.eventBus;
}
public PlaceController getPlaceController() {
return this.placeController;
}
public ExampleViewImpl getExampleView() {
return example;
}
}
ExampleActivity.java
public class ExampleActivity extends AbstractActivity {
private ExampleView view;
private ClientFactory factory;
public ExampleActivity(ExamplePlace place, ClientFactory factory) {
// Get the factory reference
this.factory = factory;
// Get the reference to the view
view = this.factory.getExampleView();
// Select the tab corresponding to the token value
if (place.getToken() != null) {
// By default the first tab is selected
if (place.getToken().equals("") || place.getToken().equals("1")) {
view.selectTab(0);
} else if (place.getToken().equals("2")) {
view.selectTab(1);
}
}
}
#Override
public void start(AcceptsOneWidget panel, EventBus eventBus) {
// Attach this view to the application container
panel.setWidget(view);
}
}
ExamplePlace.java
/**
* Just an very basic place
*/
public class ExamplePlace extends Place {
// The token corresponding to an action
private String token;
// This place should use a token to identify a view behavior
public ExamplePlace(String token) {
this.token = token;
}
// Return the current token
public String getToken() {
return token;
}
// Custom prefix to break the default name : ExamplePlace
// So that the history token will be thetabplace:token
// and not any more : ExamplePlace:token
#Prefix(value="thetabplace")
public static class Tokenizer implements PlaceTokenizer<ExamplePlace> {
#Override
public String getToken(ExamplePlace place) {
return place.getToken();
}
#Override
public ExamplePlace getPlace(String token) {
return new ExamplePlace(token);
}
}
}
AppActivityMapper.java
public class AppActivityMapper implements ActivityMapper {
private ClientFactory clientFactory;
public AppActivityMapper(ClientFactory clientFactory) {
super();
this.clientFactory = clientFactory;
}
#Override
public Activity getActivity(Place place) {
if (place instanceof ExamplePlace) {
return new ExampleActivity((ExamplePlace) place, clientFactory);
}
return null;
}
}
AppPlaceHistoryMapper.java
#WithTokenizers({ExamplePlace.Tokenizer.class})
public interface AppPlaceHistoryMapper extends PlaceHistoryMapper
{
}
All together
private Place defaultPlace = new ExamplePlace("1");
private SimplePanel appWidget = new SimplePanel();
public void onModuleLoad() {
ClientFactory clientFactory = new ClientFactory();
EventBus eventBus = clientFactory.getEventBus();
PlaceController placeController = clientFactory.getPlaceController();
// Start ActivityManager for the main widget with our ActivityMapper
ActivityMapper activityMapper = new AppActivityMapper(clientFactory);
ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
activityManager.setDisplay(appWidget);
// Start PlaceHistoryHandler with our PlaceHistoryMapper
AppPlaceHistoryMapper historyMapper= GWT.create(AppPlaceHistoryMapper.class);
PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
historyHandler.register(placeController, eventBus, defaultPlace);
RootPanel.get().add(appWidget);
// Goes to the place represented on URL else default place
historyHandler.handleCurrentHistory();
}