ActivityMapper with Gin and AsyncProvider - gwt

I've just started a project built with the new GWT archetype.
ActivityMapper looks like:
public interface Factory {
HomeActivity homeActivity();
GreetingActivity greetingActivity(String user);
}
private final Factory factory;
#Inject
MainActivityMapper(Factory factory) {
this.factory = factory;
}
#Override
public Activity getActivity(Place place) {
if (place instanceof HomePlace) {
return factory.homeActivity();
}
if (place instanceof GreetingPlace) {
GreetingPlace greetingPlace = (GreetingPlace) place;
return factory.greetingActivity(greetingPlace.getUser());
}
logger.severe("Unhandled place type: " + place.getClass().getName());
return null;
}
I'm now trying to implement code split with AsyncProvider based on this example, but I can't get it working.
When using ActivityAsyncProxy, what should I do? return the ActivityAsyncProxy from getActivity(Place place)? but then, how can I create the ActivityAsyncProxy from the factory?
How would you suggest to make the activity mapper play nicely with code split?

AFAICT, you cannot use AsyncProvider with assisted inject (that would be a great addition to GIN). That means you cannot benefit from generated runAsync calls, you'd have to do them yourself.
Have a look at http://code.google.com/p/google-web-toolkit/issues/detail?id=5129 for discussion of this issue, with several proposals.
Also have a look at https://groups.google.com/d/msg/google-web-toolkit-contributors/bUFYWEFskBI/ja2aJ0tBgdwJ for my own take on it (also available at https://gist.github.com/3038878).

Related

Creating Custom Operators in RxJava2?

I'm having trouble finding an example of how to make a custom operator with RxJava 2. I've considered a few approaches:
Using Observable.create, and then flatMaping on it from the source observable. I can get this working, but it doesn't quite feel right. I end up creating a static function which I provide the source Observable, and then flatMap on the source. In the OnSubscribe, I then instantiate an object that I pass the emitter to, which handles and manages the Observable / Emitter (as it's not trivial, and I want everything as encapsulated as possible).
Creating an ObservableOperator and providing it to Observable.lift. I can't find any examples of this for RxJava 2. I had to debug into my own example to make sure my understanding of upstream and downstream were correct. Because I can't find any examples or documentation on this for RxJava 2 I'm a little worried I might accidentally do something I'm not supposed to.
Create my own Observable type. This seems to be how the underlying operators work, many of which extend AbstractObservableWithUpstream. There is a lot going on here though, and it seems easy to miss something or do something I shouldn't. I'm not sure if I'm supposed to take an approach like this or not. I stepped myself through the mental process, and it seems like it can get hairy pretty quickly.
I'm going to proceed forward with option #2, but thought it worthwhile to ask what the supported method for doing this was in RxJava2 and also find out if there was any documentation or examples for this.
Writing operators is not recommended for beginners and many desired flow patterns can be achieved via existing operators.
Have you looked at RxJava's wiki about writing operators for 2.x? I suggest reading it from top to bottom.
using create() is possible but most people use it to emit the elements of a List with a for-each loop, not recognizing that Flowable.fromIterable does that.
We kept this extension point although RxJava 2 operators don't use lift() themselves. If you want to avoid some boilerplate with option 3. then you may try this route.
This is how RxJava 2 operators are implemented. AbstractObservableWithUpstream is a small convenience and not necessary for external implementors.
This may help you. I implement operator RxJava2 to handle APiError. I used lift operator.
See the example.
public final class ApiClient implements ApiClientInterface {
...
#NonNull
#Override
public Observable<ActivateResponse> activate(String email, EmailData emailLinkData) {
return myApiService.activate(email, emailData)
.lift(getApiErrorTransformer())
.subscribeOn(Schedulers.io());
}
private <T>ApiErrorOperator<T> getApiErrorTransformer() {
return new ApiErrorOperator<>(gson, networkService);
}
}
And then you can find custom operator
public final class ApiErrorOperator<T> implements ObservableOperator<T, T> {
private static final String TAG = "ApiErrorOperator";
private final Gson gson;
private final NetworkService networkService;
public ApiErrorOperator(#NonNull Gson gson, #NonNull NetworkService networkService) {
this.gson = gson;
this.networkService = networkService;
}
#Override
public Observer<? super T> apply(Observer<? super T> observer) throws Exception {
return new Observer<T>() {
#Override
public void onSubscribe(Disposable d) {
observer.onSubscribe(d);
}
#Override
public void onNext(T value) {
observer.onNext(value);
}
#Override
public void onError(Throwable e) {
Log.e(TAG, "onError", e);
if (e instanceof HttpException) {
try {
HttpException error = (HttpException) e;
Response response = error.response();
String errorBody = response.errorBody().string();
ErrorResponse errorResponse = gson.fromJson(errorBody.trim(), ErrorResponse.class);
ApiException exception = new ApiException(errorResponse, response);
observer.onError(exception);
} catch (IOException exception) {
observer.onError(exception);
}
} else if (!networkService.isNetworkAvailable()) {
observer.onError(new NetworkException(ErrorResponse.builder()
.setErrorCode("")
.setDescription("No Network Connection Error")
.build()));
} else {
observer.onError(e);
}
}
#Override
public void onComplete() {
observer.onComplete();
}
};
}
}

Understanding OrientGraphFactory

I do not understand the OrientGraphFactory class fully. Several questions:
1) What is the role of leaveGraphsOpen ? I cannot see any usage and/or examples.
public class OrientGraphFactory extends ... {
public boolean isLeaveGraphsOpen() {
return leaveGraphsOpen;
}
public void setLeaveGraphsOpen(boolean leaveGraphsOpen) {
this.leaveGraphsOpen = leaveGraphsOpen;
}
}
2) Why two public getDatabase() methods? This is a factory for Graph databases
3) I only want to auto create the database in specific situations (in our app, only when in "setting up mode". The only way to achieve this is:
final boolean autoCreate = false;
this.factory = new OrientGraphFactory(url) {
#Override
public ODatabaseDocumentTx getDatabase(boolean iCreate, boolean iOpen) {
return super.getDatabase(autoCreate, iOpen);
}
}.setupPool(1, 5); // default: no pool (instances are created on demand)
Is this the correct way of doing this? Looks very ugly :(
This is not supported out of the box, so your solution should work and use the wonderful Object Orientation.

GWT JSNI call Java instance method from nested Javascript funcion

I have a simple wrapper around a WYSIWYG editor (TinyMCE). I'm using JSNI to call a Java instance method (onClick) from Javascript. However the Java onClick method always gets called on the same Java instance (the last one created), no matter the editor that originated it.
private SimplePanel panel;
private TextArea ta;
private String id;
public TinyMCE(AbstractTinyMCEConfiguration config) {
id = HTMLPanel.createUniqueId();
ta = new TextArea();
ta.getElement().setId(id);
panel = new SimplePanel();
panel.add(ta);
initWidget(panel);
init(config);
}
protected native void init(AbstractTinyMCEConfiguration conf) /*-{
var ins = this;
$wnd.tinyMCE.init({
// General options
mode : conf.#com.chip.tinymce.client.AbstractTinyMCEConfiguration::getMode()(),
setup : function(ed) {
ed.onClick.add(function(ed,e) {
alert(ed.id);
ins.#com.chip.tinymce.client.TinyMCE::onClick(Lcom/google/gwt/dom/client/NativeEvent;)(e);
});
}
});
}-*/;
private void onClick(NativeEvent e) {
GWT.log("onClick " + id);
ClickEvent.fireNativeEvent(e, this);
}
I'm not sure if I can call a Java method from a Javascript funcion that is inside another funcion. Maybe that explains my problem... or maybe I'm missing something. Thanks for your help.
I think TinyMCE has one shared configuration for all editors, and that is the problem here.
It probably does not make much sense to hand the configuration to the constructor if it is shared...
Why not add a static map that maps the id back to the Java instance, something like
// ....
private static Map<String, TinyMCE> idMap = new HashMap<String, TinyMCE>();
public TinyMCE() {
// ...
idMap.put(id, this);
}
// call this from Javascript with (ed.id, e)
private static void onClick(String id, NativeEvent e) {
idMap.get(id).onClick(e);
}

Eclipse Plugin, How can I know when IResourceDeltaVisitor ends processing tree nodes?

I wrote an Eclipse Plugin that basically allow a programmer to select a Java source from the Project Explorer and by selecting the corresponding DropDown menu option it will creates an interface .java file based on the one selected.
Everything works fine, but now I need to program the update part of the job.
The update requierement is simple, I need to listen for changes and identify that the sources that have the interface generated have been modified and recreate the interface file.
To do this I wrote a class that implements IResourceChangeListener interface.
That class looks like:
public class DTOChangeListener implements IResourceChangeListener {
private List<UpdatedUnit> updatedUnits;
public DTOChangeListener() {
super();
this.updatedUnits=new ArrayList<UpdatedUnit>();
}
#Override
public void resourceChanged(IResourceChangeEvent event) {
try{
if(event.getType() == IResourceChangeEvent.POST_CHANGE){
event.getDelta().accept(this.buildVisitor());
}
}catch(CoreException ex){
ex.printStackTrace();
}
}
protected IResourceDeltaVisitor buildVisitor(){
IResourceDeltaVisitor result=new IResourceDeltaVisitor() {
#Override
public boolean visit(IResourceDelta resDelta) throws CoreException {
String resName=resDelta.getResource().getName();
if(resName==null || resName.equals("")){
return true;
}
String[] splits=resName.split("\\.");
String name = splits[0];
if(name.contains("PropertyAccess")){
return false;
}
String interfaceName=name + "PropertyAccess";
String interfaceFile=interfaceName + ".java";
IResource res=resDelta.getResource();
if((res instanceof IFolder) || (res instanceof IProject)){
// Avoid Folder & Project Nodes
return true;
}
IProject project=res.getProject();
if(project!=null){
if(project.isNatureEnabled("org.eclipse.jdt.core.javanature")){
IJavaElement element=JavaCore.create(res);
if(element instanceof ICompilationUnit){
ICompilationUnit unit=(ICompilationUnit)element;
IPath path=res.getProjectRelativePath().removeLastSegments(1);
IResource propertyAccess=project.findMember(path.append(interfaceFile));
if(propertyAccess!=null){
UpdatedUnit updatedUnit=new UpdatedUnit(project, path, unit);
updatedUnits.add(updatedUnit);
return false;
}
}
}
}
return true;
}
};
return result;
}
public List<UpdatedUnit> getUpdatedUnits() {
return updatedUnits;
}
}
I add the Listener to the Workspace, now the question I have is:
How can I know when the updatedUnits List is completed in order to proccess the list with my own code?
One posible answer to this question would be, don't worry, the:
event.getData().accept(this.buildVisitor());
will block until proccessing of the visitor finish.
but at least is not documented like it would.
Any ideas would be appreciated.
Thanks in Advance.
Daniel
Unless it's documented to not block, it blocks.

GWT MVP architecture advantages

I am learning GWT and i have read at multiple places that using MVP architecture is best suitable to develop a GWT Application
I have also read that its easy to do testing using the MVP ARCH.Can somebody explain me why its easy to do testing using the MVP architecture.
Also i am working on a project using MVP and i find it very tedious to make the view connect to the data base.I mean i have to update my presenter,service,serviceAsync,servicImpl,Facades in order to make connection to database.
So can somebody provide me the essence of MVP for GWT?i would appreciate a couple of examples.
Separation between the presenter (which contains logic) and view (a dumb wrapper around UI controls) allows you to:
write unit tests for the presenters that can run without needing the corresponding environment (desktop, browser, GWT widgets)
reuse front-end logic without being tied to a particular set of widgets/UI framework
The latter use case is rare, so let's focus on the MVP model's suitability for automated, programmatic testing. With a team of developers this often takes the form of a continuous build/test cycle using Hudson (or similar) on a headless server, where it's not practical to open a web browser, create controls, etc. every time a test is run.
Typical usage of MVP+GWT is that views implement an interface provided by the presenter, and often this interface is defined in terms of other generic interfaces. Here's a very simple presenter that increments a numeric label when a button is clicked - note that instead of exposing the TextBox and Button directly, the view returns generic HasText and HasClickHandlers instances:
public class ButtonClickPresenter {
public interface View {
HasText currentValue();
HasClickHandlers incrementButton();
}
private final View myView;
private int currentValue = 0;
public ButtonClickPresenter(View myView) {
this.myView = myView;
this.myView.currentValue().setText("0");
this.bind(); // for the sake of demonstration
}
public void bind() {
this.myView.incrementButton.addClickHandler(
#Override
new ClickHandler() {
void onClick(ClickEvent event) {
currentValue ++;
myView.currentValue().setText(
Integer.toString(currentValue));
}
});
}
}
The "real" view returns UI widgets (created via UiBinder in this example):
public class ButtonClickView implements ButtonClickPresenter.View {
// ... skipped UiBinder initialisation ...
#UiField Label currentValueLabel;
#UiField Button incrementButton;
#Override
public HasText currentValue() {
return currentValueLabel;
}
#Override
public HasClickHandlers incrementButton() {
return incrementButton;
}
// ... etc ...
}
whereas unit tests create a dummy implementation (or use Mockito, EasyMock, etc.) and thus don't require any UI components:
public class ButtonClickPresenterTest {
ButtonClickPresenter presenter;
ClickHandler currentHandler;
String currentText;
#Before
public void setUp() {
presenter = new ButtonClickPresenter(
// dummy view - just stores label text in a String and
// keeps track of the Presenter's click handler
new ButtonClickPresenter.View() {
#Override
public HasText currentValue() {
return new HasText() {
#Override public String getText() { return currentText; }
#Override public void setText(String text) { currentText = text; }
};
}
#Override
public HasClickHandlers incrementButton() {
return new HasClickHandlers() {
#Override
public HandlerRegistration addClickHandler(ClickHandler handler) {
currentHandler = handler;
}
};
}
});
}
#Test
public void testIncrement() {
// initial value
assertEquals("0", currentText);
// clicking the button should increment the number
currentHandler.onClick(null);
assertEquals("1", currentText);
}
}
As for your next paragraph: your views shouldn't be connecting to the database at all! The presenter should request data via Service/ServiceAsync (or an abstraction such as gwt-dispatch or gwt-platform), then call methods on the view to populate the UI.
By the way, those last two links (along with gwt-presenter) are a good start if you're looking for GWT MVP code samples - combined with Google GIN they provide frameworks for tying all this stuff together.
Having said all that, I agree - the combination of GWT+MVP+Java can be hard work and extremely verbose (I'm glad I don't have to work with it much these days). The alternative, though, is even less attractive: an untestable, unmaintainable ball of spaghetti...
You might like to have a look at the sample gwt-platform application blogged about here-> http://uptick.com.au/content/serendipity-working-gwt-platform-and-smartgwt.
Cheers
Mark