I'm using GWT 2.4 by using the MVP pattern
I have this situation:
In one presenter (let's call it a TreePresenter since it shows a tree) i have the following code:
display.getSelectedItem().addSelectionHandler(new SelectionHandler<TreeItem>() {
#Override
public void onSelection(SelectionEvent<TreeItem> event) {
....
evtBus.fireEvent(new SelectCategoryEvent(item.getText()));
.....
}
});
And in my AppController class I have this situation:
eventBus.addHandler(SelectCategoryEvent.TYPE, new SelectCategoryEventHandler() {
#Override
public void onSelectCategory(SelectCategoryEvent event) {
saveHistoryEvent(event);
}
});
When i select one itm in the three the event is correctly fired by the instruction
evtBus.fireEvent(new SelectCategoryEvent(item.getText()));
But in my AppController the event is not propagated and I can't handle it in the code
eventBus.addHandler(SelectCategoryEvent.TYPE, new SelectCategoryEventHandler() {
#Override
public void onSelectCategory(SelectCategoryEvent event) {
saveHistoryEvent(event);
}
});
Can anybody tell me the reason?
Thank
Angelo
I'll give you some detail; I built a class for my own history management; I built this class:
public class GwtHistoryEventsMgr {
private Map<String, List<GwtEvent>> tknEvts;
private HandlerManager eventBus;
public GwtHistoryEventsMgr(HandlerManager evtBus){
tknEvts = new HashMap<String, List<GwtEvent>>();
this.eventBus = evtBus;
}
private void saveHistoryEvent( GwtEvent event ){
List<GwtEvent> eventi = null;
if( tknEvts.containsKey(History.getToken()) ){
eventi = tknEvts.get(History.getToken());
}else{
eventi = new ArrayList<GwtEvent>();
}
eventi.add(event);
tknEvts.put(History.getToken(), eventi);
}
public void addEvtHandlers(){
//Aggiungo gli handler
eventBus.addHandler(CustomEvent.TYPE, new CustomEventHandler() {
#Override
public void onEvent(CustomEvent event) {
saveHistoryEvent(event);
}
});
}
public List<GwtEvent> getTokenTransWidgetEvents(String token){
if( tknEvts.containsKey(token) ){
return tknEvts.remove(token);
}else{
return null;
}
}
}
Then in my AppController constructor I wrote this code:
public AppController(HandlerManager eventBus, StandardDispatchAsync dispatcher){
super(null);
this.eventBus = eventBus;
this.dispatcher = dispatcher;
//Gestione history
histMgr = new GwtHistoryEventsMgr(eventBus);
histMgr.addEvtHandlers();
}
This means that I should be pretty sure that the AppController registers itself to the events I want (note: I strongly reduced the code...but all the code is in the way I wrote)
Then, since I use client-side reflection, I did, where I use the client side reflection, this code (after that all widgets have been initialized):
#SuppressWarnings("rawtypes")
private void generateHistoricalEvents(){
List<GwtEvent> eventi = hisMgr.getTokenTransWidgetEvents(History.getToken());
//Ci sono eventi....vuol dire back del browser cliccato
if( eventi != null ){
for (GwtEvent gwtEvent : eventi) {
this.eventBus.fireEvent(gwtEvent);
}
}
}
According to me it's all OK; may you tell me where the problem is?
Thank you
Angelo
Related
I try to make sample login page with two fields (username, password) and save button with android architecture component, using android data binding, validating the data in viewmodel and from view model I make call to repository for remote server call as mentioned in official doc, remote server return me userid with success so how can I start new fragment from view model using this success? I learn something about singleLiveEvent and EventObserver, but I'm not able to find there clear usage example:
LoginViewModel
private MutableLiveData<String> snackbarStringSingleLiveEvent= new MutableLiveData<>();
#Inject
public LoginViewModel(#NonNull AppDatabase appDatabase,
#NonNull JobPortalApplication application,
#NonNull MyApiEndpointInterface myApiEndpointInterface) {
super(application);
loginRepository = new LoginRepository(application, appDatabase, myApiEndpointInterface);
snackbarStringSingleLiveEvent = loginRepository.getLogin(username.get(), password.get(), type.get());
}
public MutableLiveData<String> getSnackbarStringSingleLiveEvent() {
return snackbarStringSingleLiveEvent;
}
Repository
public SingleLiveEvent<String> getLogin(String name, String password, String type) {
SingleLiveEvent<String> mutableLiveData = new SingleLiveEvent<>();
apiEndpointInterface.getlogin(name, password, type).enqueue(new Callback<GenericResponse>() {
#Override
public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
mutableLiveData.setValue(response.body().getMessage());
}
#Override
public void onFailure(Call<GenericResponse> responseCall, Throwable t) {
mutableLiveData.setValue(Constant.FAILED);
}
});
return mutableLiveData;
}
Login Fragment
private void observeViewModel(final LoginViewModel viewModel) {
// Observe project data
viewModel.getSnackbarStringSingleLiveEvent().observe(this, new Observer<String>() {
#Override
public void onChanged(String s) {
}
});
}
How can I use EventObserver in above case? Any practical example?
Check out below example about how you can create single LiveEvent to observe only one time as LiveData :
Create a class called Event as below that will provide our data once and acts as child of LiveData wrapper :
public class Event<T> {
private boolean hasBeenHandled = false;
private T content;
public Event(T content) {
this.content = content;
}
public T getContentIfNotHandled() {
if (hasBeenHandled) {
return null;
} else {
hasBeenHandled = true;
return content;
}
}
public boolean isHandled() {
return hasBeenHandled;
}
}
Then declare this EventObserver class like below so that we don't end up placing condition for checking about Event handled every time, everywhere :
public class EventObserver<T> implements Observer<Event<T>> {
private OnEventChanged onEventChanged;
public EventObserver(OnEventChanged onEventChanged) {
this.onEventChanged = onEventChanged;
}
#Override
public void onChanged(#Nullable Event<T> tEvent) {
if (tEvent != null && tEvent.getContentIfNotHandled() != null && onEventChanged != null)
onEventChanged.onUnhandledContent(tEvent.getContentIfNotHandled());
}
interface OnEventChanged<T> {
void onUnhandledContent(T data);
}
}
And How you can implement it :
MutableLiveData<Event<String>> data = new MutableLiveData<>();
// And observe like below
data.observe(lifecycleOwner, new EventObserver<String>(data -> {
// your unhandled data would be here for one time.
}));
// And this is how you add data as event to LiveData
data.setValue(new Event(""));
Refer here for details.
Edit for O.P.:
Yes, data.setValue(new Event("")); is meant for repository when you've got response from API (Remember to return same LiveData type you've taken in VM instead of SingleLiveEvent class though).
So, let's say you've created LiveData in ViewModel like below :
private MutableLiveData<Event<String>> snackbarStringSingleLiveEvent= new MutableLiveData<>();
You provide value to this livedata as Single Event from repository like below :
#Override
public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
mutableLiveData.setValue(new Event(response.body().getMessage())); // we set it as Event wrapper class.
}
And observe it on UI (Fragment) like below :
viewModel.getSnackbarStringSingleLiveEvent().observe(this, new EventObserver<String>(data -> {
// your unhandled data would be here for one time.
}));
Event.java
public class Event<T> {
private T content;
private boolean hasBeenHandled = false;
public Event(T content) {
this.content = content;
}
/**
* Returns the content and prevents its use again.
*/
public T getContentIfNotHandled() {
if (hasBeenHandled) {
return null;
} else {
hasBeenHandled = true;
return content;
}
}
/**
* Returns the content, even if it's already been handled.
*/
public T peekContent() {
return content;
}
}
EventObserver.java
public class EventObserver<T> implements Observer<Event<? extends T>> {
public interface EventUnhandledContent<T> {
void onEventUnhandledContent(T t);
}
private EventUnhandledContent<T> content;
public EventObserver(EventUnhandledContent<T> content) {
this.content = content;
}
#Override
public void onChanged(Event<? extends T> event) {
if (event != null) {
T result = event.getContentIfNotHandled();
if (result != null && content != null) {
content.onEventUnhandledContent(result);
}
}
}
}
Example, In ViewModel Class
public class LoginViewModel extends BaseViewModel {
private MutableLiveData<Event<Boolean>> _isProgressEnabled = new MutableLiveData<>();
LiveData<Event<Boolean>> isProgressEnabled = _isProgressEnabled;
private AppService appService;
private SchedulerProvider schedulerProvider;
private SharedPreferences preferences;
#Inject
LoginViewModel(
AppService appService,
SchedulerProvider schedulerProvider,
SharedPreferences preferences
) {
this.appService = appService;
this.schedulerProvider = schedulerProvider;
this.preferences = preferences;
}
public void login(){
appService.login("username", "password")
.subscribeOn(schedulerProvider.executorIo())
.observeOn(schedulerProvider.ui())
.subscribe(_userLoginDetails::setValue,
_userLoginDetailsError::setValue,
() -> _isProgressEnabled.setValue(new Event<>(false)),
d -> _isProgressEnabled.setValue(new Event<>(true))
)
}
}
In Login Fragment,
viewModel.isProgressEnabled.observe(this, new EventObserver<>(hasEnabled -> {
if (hasEnabled) {
// showProgress
} else {
// hideProgress
}
}));
Using Event and EventObserver class we can achieve the same like SingleLiveEvent class but if you are thinking a lot of boilerplate code just avoid this method. I hope it would help you and give some idea about why we are using SingleEvent in LiveData.
I understand that Google gives the guidelines to use LiveData between the ViewModel and UI but there are edge cases where using LiveData as a SingleLiveEvent is like reinventing the wheel. For single time messaging between the view model and user interface we can use the delegate design pattern. When initializing the view model in the activity we just have to set the activity as the implementer of the interface. Then throughout our view model we can call the delegate method.
Interface
public interface Snackable:
void showSnackbarMessage(String message);
UI
public class MyActivity extends AppCompatActivity implements Snackable {
private MyViewModel myViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
this.myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
this.myViewModel.setListener(this);
}
#Override
public void showSnackbarMessage(String message) {
Toast.makeText(this, "message", Toast.LENGTH_LONG).show();
}
}
View Model
public class MyViewModel extends AndroidViewModel {
private Snackable listener;
public MyViewModel(#NonNull Application application) {
super(application);
}
public void setListener(MyActivity activity){
this.listener = activity;
}
private void sendSnackbarMessage(String message){
if(listener != null){
listener.showSnackbarMessage(message);
}
}
private void anyFunctionInTheViewModel(){
sendSnackbarMessage("Hey I've got a message for the UI!");
}
}
Wicket use of models can be cumbersome. For a stateful page to properly render an object, you need to use lots of boiler-plate code, overriding classes to properly get the visibility status, etc... A simple example:
private IModel<FooBar> fooBarModel;
public MyPage() {
Label lbl1 = new Label("field1",
new PropertyModel<>(fooBarModel, "field1")) {
#Override public boolean isVisible() {
return fooBarModel.getObject().someCondition();
} }
add(lbl1);
/// Etc... same for dozen of other fields
}
I'm often using a trick using a ListView to help. Same example:
public MyPage() {
add(new ListView<FooBar>("content",
new SingleListModel<FooBar>(fooBarModel)) {
#Override protected void populateItem(...) {
FooBar fooBar = item.getModelObject();
// Code here gets simpler:
Label lbl1 = new Label("field1", fooBar.getField1());
lbl1.setVisible(fooBar.someCondition());
item.add(lbl1);
// Etc...
}
});
}
With a simple utility class SingleListModel, that transform a IModel<T> to a ListModel<T>, having 1 or 0 elements, depending whether T is null or not:
public class SingleListModel<T>
extends LoadableDetachableModel<List<T>> {
private IModel<T> tModel;
public SingleListModel(IModel<T> tModel) {
this.tModel = tModel;
}
#Override
protected List<T> load() {
List<T> ret = new ArrayList<>(1);
T t = tModel.getObject();
if (t != null)
ret.add(tModel.getObject());
return ret;
}
}
The nice side-effect of this is that the whole "content" element in the markup is hidden if fooBarModel returns null; no special treatment needed.
But all this smells like a hack to me, as I use ListView in a somehow "unnatural" fashion.
Is there a cleaner way to get the same result? A standard wicket framework?
You should use Behavior instead to avoid such duplications.
public class MyBehavior extends Behavior {
private final MyModel model;
public MyBehavior(MyModel model) {this.model = model;}
#Override public void onConfigure(Component c) {
if (model.someCondition()) {
component.setVisible(false);
}
}
}
Usage:
MyBehavior b = new MyBehavior(modelInstance);
component1.add(b);
component2.add(b);
// dozen more
Label lbl1 = new Label("field1",
new PropertyModel<>(fooBarModel, "field1")) {
#Override public boolean isVisible() {
return fooBarModel.getObject().someCondition();
} }
add(lbl1);
with little refactoring it can be converted into
add(new FLabel("id","text")
.setVisibilityFunction(()->model.getObject().isVisible()))
);
the FLabel class:
public class FLabel extends Label implements IComponentWithVisibilityFunction<FLabel> {
private SerializableBooleanSupplier visibilityFunction;
public FLabel(String id) {
super(id);
}
public FLabel(String id, Serializable label) {
super(id, label);
}
public FLabel(String id, IModel<?> model) {
super(id, model);
}
#Override
public FLabel setVisibilityFunction(SerializableBooleanSupplier visibilityFunction) {
this.visibilityFunction = visibilityFunction;
return this;
}
#Override
protected void onConfigure() {
if (visibilityFunction != null) {
setVisible(visibilityFunction.getAsBoolean());
}
}
}
public interface IComponentWithVisibilityFunction<T> {
T setVisibilityFunction(SerializableBooleanSupplier visibilityFunction);
}
Moreover you can put supplier into constructor:
add(new FLabel("id","text", ()->model.getObject().isVisible()));
I have java web application, that is being used by multiple users. By users I mean people that actually connect to application and do stuff with it.
Every user can edit a schema, that has it's ID. At the moment, multiple users can edit same schema at the same time. I want to fix that, without using a database/table.
What I tried so far:
There's an EDIT button, that users click to edit certain schema. When they click it, a method is triggered.
protected SessionLockModSchema sessionLockModSchema = new SessionLockModSchema();
protected Model model; //schema model object
public void buttonClick(ClickEvent event) {
//button logic goes here
}
I figured I might create a bean with schema ID, when this method is triggered.
protected SessionLockModSchema sessionLockModSchema = new SessionLockModSchema();
protected Model model;
public void buttonClick(ClickEvent event) {
//button logic goes here
this.sessionLockModSchema.lockSchema(model);
}
When I have this bean created, all that I need to do is check if it exists, for the next user.
protected Model model;
public void buttonClick(ClickEvent event) {
if(!this.sessionLockModSchema.isSchemaLocked(model){
//button logic goes here
this.sessionLockModSchema.lockSchema(model);
}
}
In theory this sounded good to me, edit button wouldn't trigger if there was a bean created with that schema. But bean is not created (or at least only one user can access it). Here's sessionLockModSchema class:
public class SessionLockModSchema{
ApplicationContext context;
GenericApplicationContext ctx;
public SessionLockModSchema(){
if(ctx == null){
this.ctx = new GenericApplicationContext();
}
}
public void lockSchema(Model model){
String beanName = "model-"+model.getId();
BeanDefinitionBuilder bDBuilder = BeanDefinitionBuilder .rootBeanDefinition(String.class);
bDBuilder.setScope("prototype");
this.ctx.registerBeanDefinition(beanName, bDBuilder.getBeanDefinition());
//appcontext.close();
}
public boolean isSchemaLocked(Model model){
String beanName = "model-"+model.getId();
Object objectRef = null;
try{
//ctx.refresh();
objectRef = this.ctx.getBean(beanName);
}catch(NoSuchBeanDefinitionException e){
// TODO:
}catch(IllegalStateException e){
// TODO:
}
boolean isLocked;
if(objectRef == null){
isLocked = false;
}else{
isLocked = true;
}
return isLocked;
}
}
To clarify my question, I get IllegalStateException saying that beanFactory must be refreshed, if I do however refresh (commented ctx.refresh), I get that no such bean exists. Any advices on this? What am I doing wrong?
What about something like that (I don't see why you would need spring managed beans here):
public enum SessionLockModSchema {
INSTANCE;
private final Set<String> lockedModels = new HashSet<>;
public void lockSchema(Model model){
synchronized(lockedModels) {
lockedModels.add("" + model.getId());
}
}
public void unlockSchema(Model model){
synchronized(lockedModels) {
lockedModels.remove("" + model.getId());
}
}
public void isSchemaLocked(Model model){
synchronized(lockedModels) {
return lockedModels.contains("" + model.getId());
}
}
}
usage (something like that):
public void buttonClick(ClickEvent event) {
if (SessionLockModSchema.INSTANCE.isLocked(model) {
try {
SessionLockModSchema.INSTANCE.lockSchema(model);
// do something with "model"
} finally {
SessionLockModSchema.INSTANCE.unlockSchema(model);
}
}
}
I'm trying to select first root node of the CellTree after asynchronous data fetching from server. Here is my code:
public class MyTreeModel implements TreeViewModel{
private MyServiceAsync myService = GWT.create(MyService.class);
public <T> NodeInfo<?> getNodeInfo(T value) {
Cell<MyTO> cell = new AbstractCell<MyTO>() {
#Override
public void render(Context context, MyTO value, SafeHtmlBuilder sb) {
//rendering node...
}
};
return new DefaultNodeInfo<MyTO>(value instanceof MyTO ?
createBranchDataProvider((MyTO)value) : //fetching child nodes
cerateRootDataProvider(), cell); //fetching root nodes
}
#Override
public boolean isLeaf(Object value) {
if (value instanceof MyTO) {
MyTO to = (MyTO)value;
return to.isLeafNode();
}
return false;
}
private AbstractDataProvider<MyTO> cerateRootDataProvider() {
AsyncDataProvider<MyTO> dataProvider = new AsyncDataProvider<MyTO>() {
#Override
protected void onRangeChanged(HasData<MyTO> display) {
AsyncCallback<List<MyTO>> callback = new AsyncCallback<List<MyTO>>() {
#Override
public void onSuccess(List<MyTO> result) {
updateRowCount(result.size(), true);
updateRowData(0, result);
}
#Override
public void onFailure(Throwable caught) {
Window.alert(caught.toString());
}
};
myService.getRootNodes(callback);
}
};
return dataProvider;
}
private AbstractDataProvider<MyTO> createBranchDataProvider(final MyTO value) {
AsyncDataProvider<MyTO> dataProvider = new AsyncDataProvider<MyTO>() {
#Override
protected void onRangeChanged(HasData<MyTO> display) {
AsyncCallback<List<MyTO>> callback = new AsyncCallback<List<MyTO>>() {
#Override
public void onSuccess(List<MyTO> result) {
updateRowCount(result.size(), true);
updateRowData(0, result);
}
#Override
public void onFailure(Throwable caught) {
Window.alert(caught.toString());
}
};
myService.getChildNodes(value.getId(), callback);
}
};
return dataProvider;
}
For data which stored on client side solution looks pretty simple: we could just call something like
tree.getRootTreeNode().setChildOpen(0, true, true);
but if we want to fetch data asynchronously we will catch IndexOutOfBoundsException in case we try the same immediately after creation tree, because data is not obtained yet. How can I know when onSuccess() event will be fired in cerateRootDataProvider()? Or I could use another solution? Please suggest something.
I see two options for calling
tree.getRootTreeNode().setChildOpen(0, true, true);
in a right moment:
Direct dependency on presenter: add a constructor for your MyTreeModel object. Send corresponding presenter as a parameter. Add and call something like presenter.onDataLoadingComplete() at the end of onSuccess method.
Custom event: create your custom event. Fire it at the end of onSuccess method. Subscribe to it in some place where you can call access `tree``object. Call necessary code.
I am using Windchill 10.0 M030. I have created a windchill service that captures some actions. I am done with capturing the delete, checkin, and state change events, but I don't know how to capture the revision event of an object. Can someone help me out?
Some example code snippets would be helpful. The events that are working fine are the following:
public void notifyEvent(KeyedEvent event) throws RemoteException,
WTException {
if (event instanceof PersistenceManagerEvent) {
notifyEvent((PersistenceManagerEvent) event);
}
if (event instanceof WorkInProgressServiceEvent) {
notifyEvent((WorkInProgressServiceEvent) event);
}
if (event instanceof EPMWorkspaceManagerEvent) {
notifyEvent((EPMWorkspaceManagerEvent) event);
}
if (event instanceof LifeCycleServiceEvent) {
notifyEvent((LifeCycleServiceEvent) event);
}
}
Is there any separate event like Revise event to be captured in this way? How can I do that?
Thank you.
Here is the code for your ListenerAdapter :
public class VersionEventListenerAdapter extends ServiceEventListenerAdapter {
public VersionEventListenerAdapter(String serviceId) {
super(serviceId);
}
public void notifyVetoableEvent(Object event) throws WTException, WTPropertyVetoException {
if (!(event instanceof KeyedEvent)) {
return;
}
Object target = ((KeyedEvent) event).getEventTarget();
Object eventType = ((KeyedEvent) event).getEventType();
if (eventType.equals(VersionControlServiceEvent.NEW_VERSION)
{
/** Call your business code here
example : yourMethod(target);
**/
}
}
And then the service to register the listener
public class MyStandardListenerService extends StandardManager implements MyListenerServiceInterface {
private static final long serialVersionUID = 1L;
protected synchronized void performStartupProcess() throws ManagerException {
VersionEventListenerAdapter versionEventListenerAdapter = new VersionEventListenerAdapter(getName());
getManagerService().addEventListener(versionEventListenerAdapter, VersionControlServiceEvent.generateEventKey(VersionControlServiceEvent.NEW_VERSION));
}
public static MyStandardListenerService newMyStandardListenerService() throws WTException {
MyStandardListenerService instance = new MyStandardListenerService();
instance.initialize();
return instance;
}
This new service need to be registered in the wt.properties. See the customizer's guide for more details about how to register it (with xconfmanager command line utility)