How to get access to underlying POJO from GWT Editor class - gwt

I have a HashMap inside my POJO that I am using the Editor framework in GWT to edit. While I have access to the standard member variables bound through thier getters/setters, I don't know how to access the values inside the HashMap. How do I get access to the underlying POJO that is being edited through my editor that is using the SimpleBeanEditorDriver?
My POJO:
#Entity(noClassnameStored=true)
public class ProfileConfig extends BaseEntity {
#Indexed(unique=true)
private String name;
private boolean isDefault;
private HashMap<ProfileID, ProfileInfo> profiles= new HashMap<ProfileID, ProfileInfo>();
public ProfileInfo getProfile(ProfileID id) {
return profiles.get(id);
}
public void setProfile(ProfileID id, ProfileInfo p) {
profiles.put(id, p);
}
My Editor:
public class ProfileConfigEditor extends Composite implements ManagedObjectEditor<ProfileConfig> {
private static ProfileConfigEditorUiBinder uiBinder = GWT.create(ProfileConfigEditorUiBinder.class);
interface ProfileConfigEditorUiBinder extends UiBinder<Widget, ProfileConfigEditor> {
}
private UserManager userManager;
#UiField
CellList Profiles;
#UiField
TextBox name;
#UiField
CheckBox isDefault;
So given that I have a list of valid Profile ids from the userManager, how do I go about calling the getProfile method from my POJO from within my Editor?

What you need is a ValueAwareEditor.
public class ProfileConfigEditor extends Composite implements ManagedObjectEditor<ProfileConfig>, ValueAwareEditor<ProfileConfig> {
void setValue(ProfileConfig value){
// TODO: Call ProfileConfig.getProfile()
}
void flush(){
// TODO: Call ProfileConfig.setProfile()
}
// ... Other methods here
Alternatively, if you want more of a challenge, you can look at rolling your own CompositeEditor, for example see the source code for ListEditor. In your case, you would implement a CompositeEditor<ProfileConfig, ProfileInfo, MyNewProfileInfoEditor>. You can this of this as "This editor will take a ProfileConfig object, extract one or more ProfileInfo objects and edit it with one or more MyNewProfileInfoEditor editors"

Related

Dynamic injection using #SpringBean in wicket

I have a form that based on collected information generates a report. I have multiple sources from which to generate reports, but the form for them is the same. I tried to implement strategy pattern using an interface implementing report generator services, but that led to wicket complaining about serialization issues of various parts of the report generator. I would like to solve this without duplicating the code contained in the form, but I have not been able to find information on dynamic injection with #SpringBean.
Here is a rough mock up of what I have
public class ReportForm extends Panel {
private IReportGenerator reportGenerator;
public ReportForm(String id, IReportGenerator reportGenerator) {
super(id);
this.reportGenerator = reportGenerator;
final Form<Void> form = new Form<Void>("form");
this.add(form);
...
form.add(new AjaxButton("button1") {
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit(AjaxRequestTarget target)
{
byte[] report = reportGenerator.getReport(...);
...
}
});
}
}
If I do it this way, wicket tries to serialize the concrete instance of reportGenerator. If I annotate the reportGenerator property with #SpringBean I receive Concrete bean could not be received from the application context for class: IReportGenerator
Edit: I have reworked implementations of IRerportGenerator to be able to annotate them with #Component and now I when I use #SpringBean annotation I get More than one bean of type [IReportGenerator] found, you have to specify the name of the bean (#SpringBean(name="foo")) or (#Named("foo") if using #javax.inject classes) in order to resolve this conflict. Which is exactly what I don't want to do.
I think the behavior you're trying to achieve can be done with a slight workaround, by introducing a Spring bean that holds all IReportGenerator instances:
#Component
public class ReportGeneratorHolder {
private final List<IReportGenerator> reportGenerators;
#Autowired
public ReportGeneratorHolder(List<IReportGenerator> reportGenerators) {
this.reportGenerators = reportGenerators;
}
public Optional<IReportGenerator> getReportGenerator(Class<? extends IReportGenerator> reportGeneratorClass) {
return reportGenerators.stream()
.filter(reportGeneratorClass::isAssignableFrom)
.findAny();
}
}
You can then inject this class into your Wicket page, and pass the desired class as a constructor-parameter. Depending on your Spring configuration you might need to introduce an interface for this as well.
public class ReportForm extends Panel {
#SpringBean
private ReportGeneratorHolder reportGeneratorHolder;
public ReportForm(String id, Class<? extends IReportGenerator> reportGeneratorClass) {
super(id);
IReportGenerator reportGenerator = reportGeneratorHolder
.getReportGenerator(reportGeneratorClass)
.orElseThrow(IllegalStateException::new);
// Form logic omitted for brevity
}
}
As far as I am able to find, looking through documentation and even the source for wicket #SpringBean annotation, this isn't possible. The closest I got is with explicitly creating a proxy for a Spring bean based on class passed. As described in 13.2.4 Using proxies from the wicket-spring project chapter in Wicket in Action.
public class ReportForm extends Panel {
private IReportGenerator reportGenerator;
private Class<? extends IReportGenerator> classType;
private static ISpringContextLocator CTX_LOCATOR = new ISpringContextLocator() {
public ApplicationContext getSpringContext() {
return ((MyApplication)MyApplication.get()).getApplicationContext();
}
};
public ReportForm(String id, Class<? extends IReportGenerator> classType) {
super(id);
this.classType = classType;
final Form<Void> form = new Form<Void>("form");
this.add(form);
...
form.add(new AjaxButton("button1") {
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit(AjaxRequestTarget target)
{
byte[] report = getReportGenerator().getReport(...);
...
}
});
}
private <T> T createProxy(Class<T> classType) {
return (T) LazyInitProxyFactory.createProxy(classType, new
SpringBeanLocator(classType, CTX_LOCATOR));
}
private IReportGenerator getReportGenerator() {
if (reportGenerator = null) {
reportGenerator = createProxy(classType);
}
return reportGenerator;
}
}

how to inject a uiBinder with #Inject (instead of GWT.create())?

Firstly, is doing such thing a good practice ?
I tried what seems to be the right way for me but wasn't successful :
public class FormViewImpl extends CompositeView implements HasUiHandlers<C>, FormView {
public interface SettlementInstructionsSearchFormViewUiBinder extends UiBinder<Widget, SettlementInstructionsSearchFormViewImpl> {}
#Inject
static FormViewImpl uiBinder;
#Inject
static Provider<DateEditorWidget> dateEditorProvider;
#UiField(provided = true)
MyComponent<String> myComp;
#UiField
DateEditorWidget effectiveDateFrom;
// .. other fields
#Inject
public FormViewImpl () {
myComp = new MyComponent<String>("lol");
if (uiBinder == null)
uiBinder = GWT.create(SettlementInstructionsSearchFormViewUiBinder.class);
initWidget(uiBinder.createAndBindUi(this));
}
#UiFactory
DateEditorWidget createDateEditor() {
return dateEditorProvider.get();
}
}
What other things than a class with no arguments is required ? In my company's project the same kind of code works at some other place. Sorry from the high level of noob here...
If you guys had any pointers it would be nice.
Thanks
Two issues:
First, two of your #Inject fields are static - have you done anything to make static fields be injected? Static fields don't get set when Gin (or Guice) creates new instances, those have to be set once and done. As they are static, they will never be garbage collected - this may be okay with you, or it might be a problem, and you should change them to instance fields. If you want to keep them static, then you must invoke requestStaticInjection in your module to ask Gin to initialize them when the ginjector is created.
Next, if you do choose to remove static, the uiBinder field must still be null in that constructor, because the fields can't have been injected yet! How do you set a field on an object that you haven't yet created? That's what you are expecting Gin to be able to do. Instead, consider passing that as an argument into the #Inject decorated constructor. You don't even need to save it as a field, since the widget will only use it the one time.
To have a class generated by GIN (doesn't matter if it is a uiBinder or not) it is not necessary for it to have a default constructor (i.e. the one without parameters). The class you want to inject must have the constructor annotated with #Inject:
#Inject
public InjectMeClass(Object a, Object b)
The other class which is injected, suppose it is a UiBinder, must have the injected fields annotated with #UiField(provided=true):
public class Injected extends Composite {
private static InjectedUiBinder uiBinder = GWT
.create(InjectedUiBinder.class);
interface InjectedUiBinder extends UiBinder<Widget, Injected> {
}
#UiField(provided=true)
InjectMeClass imc;
public Injected(final InjectMeClass imc) {
this.imc=imc;
initWidget(uiBinder.createAndBindUi(this));
}
So, back to your case:
#UiField(provided = true)
MyComponent<String> myComp;
#Inject
public FormViewImpl (MyComponent<String> myComp) {
this.myComp = myComp;
and for example:
public class MyComponent<T> extends Composite {
private T value;
#Inject
public MyComponent(T t) {
this.value = t;
...
}
...
}
In the GIN module you can have a provider:
#Provides
#Singleton
public MyComponent<String> createMyComponent() {
return new MyComponent<String>("lol");
}

How to bind a list of objects to ListBox in GWT?

I want to bind my services to ListBox but I can't bind it.
//Service class
public class Service {
private String serviceName;
public Service(String serviceName) {
this.serviceName = serviceName;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
}
// SignUpBean class
public class SignUpBean {
private List<Service> services;
public List<Service> getServices() {
return services;
}
public void setServices(List<Service> services) {
this.services = services;
}
}
The following is my Main Editor
public class SignUpEditor extends SimplePanelimplements Editor<SignUpBean> {
public ListBox services;
public void SignUpEditor (){
services.addItem("Service1");
services.addItem("Service2");
setWidget(services);
}
}
I am not getting any error but I think I have to use ListEditor or CompositeEditor. But i don't know about it. Can anyone suggest how to bind Service to ListBox
ListBox suppose to be a LeafValueEditor. Conceptually we don't edit the list in the ListBox. Rather We select a value from the list which will be displayed in the selection. So, ListBox holds only one value and thus ListBox must be leaf value Editor.
Currently there is no GWT support to directly bind the list to ListBox. We have to write an adapter which extends ListEditor ( Refer HasDataEditor class for more detail ). This approach is strange.
Simple approach is to write an adapter which implements LeafValueEditor< List < String > >. In adapter's setValue method we should iterate over the list and call listBox.addItem for each value in the list.
I don't recommend either approaches simply because ListBox's LIST is NON EDITABLE and only VALUE is EDITABLE. I recommend doing addItems manually without using Editors.
UPDATED : HasDataAdapter is an example ListEditor. Refer that implementation. You may get some idea.

How to handle java.util.Properties when using eclipse data binding

I have a model class, it contains a java.util.Properties.
public class Model{
private Properties properties;
}
This properties can contains arbitrary key-value pairs. Now I want to bind "properties" to a JFace TableViewer. How to do this?
Some example code will be good, I have googled for this, but found nothing useful.
To access your model from a TableViewer you have to provide a LabelProvider and a ContentProvider as a translation to the TableViewer and of course provide the model itself.
In short the ContentProvider wraps your models content to the structure of the TableViewer (basically a breakdown of your model to the line by line approach of the TableViewer).
The LabelProvider lets you control the actual rendering in the TableCells.
To provide your model the TableViewer supplies a setInput method.
This works best however when your model is modeled as a JavaBean.
If you look at the snippets you will find something like this in your implementation of the ContentProvider like here:
public Object[] getElements(Object inputElement) {
return (MyModel[]) inputElement;
}
So, if your model as I understand right now, is just a wrapper around your properties, one way to achieve your goal would be to introduce the notion of a PropertyLine that gets populated either by startup, or dynamically via JFace Databinding (that might be a different topic).
public class Model{
...
private PropertyLine[] propertyLineArray;
private PropertyLine[] initializeProperties(){
//initialize your PropertyLines
}
public Model(){
...
propertyLineArray=initializeProperties();
...
}
public PropertyLine[] getPropertyLines(){
return propertyLineArray;
}
}
public class ProperyLine{
...
private String propertyKey;
private String propertyText;
//getter, setter
...
}
Your ContentProvider would look something like this:
private class PropertyContentProvider implements IStructuredContentProvider {
...
public Object[] getElements(Object inputElement) {
return (PropertyLine[]) inputElement;
}
...
}
Your LabelProvider seems quite straightforward then:
public class PropertyLabelProvider extends LabelProvider implements
ITableLabelProvider {
...
public String getColumnText(Object element, int columnIndex) {
PropertyLine pl=(PropertyLine) element
return pl.getPropertyText();
}
...
}
You wire everything up somewhere by:
final TableViewer v = new TableViewer(shell, SWT.BORDER
| SWT.FULL_SELECTION);
v.setLabelProvider(new PropertyLabelProvider());
v.setContentProvider(new PropertyContentProvider ());
v.setInput(myModel.getPropertyLines());

How to edit a Set<? extends EntityProxy> with GWT Editor framework?

for sake of simplicity:
public class Person
{
String name;
Set<Address> addresses;
}
public class Address
{
String city;
String street;
}
with and matching
public interface PersonProxy extends EntityProxy
{
public String getName();
public Set<AdressProxy> getAddresses();
}
and
public interface AdressProxy extends EntityProxy
{
public String getCity();
public String getStreet();
}
I got UiBuinder classes to edit AddressProxy
and it clear to me how to use ListEditor in case if I got List but data is Set in the Person class
how do I use Editor Framework to edit them?
Or may be how do I convert Set to List when it becomes PersonProxy?
I did an attempt to put a kind of adapter Editor class that would implement
LeafValueEditor<Set<AddressProxy>>
and then inside of the LeafValueEditor.setValue() move to a List and start a new driver.edit() on a separate Editor hierarchy that takes care of List editing but with now luck.
You should create a CompositeEditor<Set<AddressProxy>, AddressProxy, AddressEditor>, similar to a ListEditor but handling a Set instead of a List.
I suppose you could somehow delegate to a ListEditor though I'm really not sure.
I've done it with Points and Routes (one Route contains N Points):
Route (Composite):
#UiField
TextBox name;
#Ignore
#UiField
FlexTable listPoints;
PointsEditor pointsEditor = new PointsEditor();
....
pointsEditor.add(String id);
PointsEditor:
public class PointsEditor implements HasRequestContext<List<PointProxy>>, ValueAwareEditor<List<PointProxy>> {
List<PointProxy> points = new ArrayList<PointProxy>();
public void add(String id) {
PointProxy point = ctx.create(PointProxy.class);
point.setId(id);
points.add(point);
}
Route (server side):
#Embedded
private List<Point> points = new ArrayList<Point>();
RouteProxy
public interface RouteProxy extends EntityProxy {
abstract List<PointProxy> getPoints();
abstract void setPoints(List<PointProxy> points);
PointProxy
public interface PointProxy extends ValueProxy {
...
}