Display only 1 field in Nested Object Metawidget - java

Using the metawidget to build some flexible UI in Java: https://sourceforge.net/projects/metawidget/
public class Cohort {
private int id;
private Project project;
private Member teamLead;
public Cohort() { }
#UiHidden
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public Project getProject() { return project; }
public void setProject(Project project) { this.project = project; }
public Member getTeamLead() { return teamLead; }
public void setTeamLead(Member teamLead) { this.teamLead = teamLead; }
}
Cohort is the class inspected. However as is desirable it recursively inspects both the Project and Member classes.
When displayed on the UI, it will display all the fields for each of the classes. However I would only like to display the "Name" field of the Project and firstName + last Name of the Member.

There are a number of ways to achieve this. I'll start with one and let me know if it's sufficient for your needs:
a) mark the fields of Project/Member that you don't want to see as UiHidden (you don't say what those fields are, but you seem to have gotten the idea because you are already hiding 'Cohort.getId'). Note you can also reuse existing annotations (like JPA annotations) for this purpose.
b) mark 'Cohort.getProject' and 'Cohort.getTeamLead' as UiLabel( "" ). This will suppress the sub-label for the sub-object, and make its fields appear as if part of the original object.

Related

Android Room library error: Cannot find getter for field

I get this error but I couldn't find any solution. I tried many things but still I'm getting this code.
My code is:
https://justpaste.it/4di3y
The error:
error: Cannot find getter for field.
( private Long fie_id )
How I can fix it?
Instead of
public Long getId() {
return fie_id;
}
public void setId(Long id) {
this.fie_id = id;
}
Do
public Long getFie_id() {
return fie_id;
}
public void setFie_id(Long fie_id) {
this.fie_id = fie_id;
}
Maybe you don't believe me but i have to say. I am using Mac and that problem was about the Computer Language. I was using Turkish Language and i have changed to English and that problem was gone after Invalidate Cache and Restart.
As summary:
Set MacOSX language as English (SystemPreferences -> Language & Region)
Open Android Studio and Perform Invalidate Caches And Restart (File -> Invalidate Caches/Restart -> Invalidate and Restart)
Change all the access modifier to "public". This will solve the issue.
Instead of:
#PrimaryKey
private Long fie_id;
#ColumnInfo(name = "name")
private String name;
Use:
#PrimaryKey
public Long fie_id;
#ColumnInfo(name = "name")
public String name;
Kotlin room does not allow defining variables in entity class start of 'i' character. I had the same error. I solved it, albeit difficult.
Replace id with pId and it will be fine.
For example;
val isrc: String? = "",
instead of
val albumIsrc: String? = "",
If you change the variable in this way, the error will be resolved.
Happy codding.
Note : if system language of your computers is Turkish, this case does.
It has to do with the naming of your PrimaryKey. The signature of your getter and setter should correspond to the name of the variable. Otherwise, Room can't find it.
Which means that the variable id should have getId(), and variable fie_id should have getFie_id() as a getter, the same goes for the setters. So, either rename your PrimaryKey or name your getters and setters accordingly.
For me it was because of an uncapitalized "m". The below works:
#ColumnInfo(name = "foo")
private String mFoo;
public String getMFoo() {
return mFoo;
}
public void setMFoo(String foo) {
this.mFoo = foo;
}
This doesn't:
#ColumnInfo(name = "foo")
private String mFoo;
public String getmFoo() {
return mFoo;
}
public void setmFoo(String foo) {
this.mFoo = foo;
}
Also don't forget to specify the new column in your migration. Something like:
val MIGRATION_2_3: Migration = object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE myDataObj "
+ " ADD COLUMN foo TEXT")
}
}
Try to match the name of the setter function as the variable name declared.
Forex.
There is a boolean variable declared like
private boolean attachment_status;
It's getter should be like this
public boolean getattachment_status(){
return attachment_status
}
or u can do like this
public boolean getAttachment_status(){
return attachment_status
}
I declared my getter like this and I was getting the same error
public boolean getAttachment(){
return attachment_status
}
but I refactor it and the problem was solved.
During your programs lifecycle if the encapsulation is incorrect then confusion happens. After viewing your code it seems might be attempting to access something from an eternal class. PrimaryKey id is being called instead of the passed value setId( id ).
Make the variable public:
Private --> Public
It is better to stick with documantation. The structures are sensitive. link of documantation
Sample :
#Entity(tableName = "notes")
public class Note {
#PrimaryKey(autoGenerate = true)
public int id;
#NotNull
#ColumnInfo(name = "note")
public String mNote;
public Note(#NotNull String mNote) {
this.mNote = mNote;
}
public int getId() {
return id;
}
#NotNull
public String getNote() {
return this.mNote;
}}
Had same problem Clear and Rebuild the project options are the answer somehow after the change.
for getter in setter, just follow the Pattern get/set[A-Z]last lenght-1 of the field just like in the example ( field: mWord)
#Entity(tableName = "words")
public class Word {
#PrimaryKey
#NonNull
#ColumnInfo(name = "word")
private String mWord;
public Word(#NonNull String mWord) {
this.mWord = mWord;
}
public String getMWord() {
return mWord;
}
}
Only need to change is fied scope update as "public" instead of "private".
https://github.com/rzwitserloot/lombok/issues/1403
Changing the variable from private to protected worked for me.
If everything is correct, then I have observe this issue mostly in a case of variable kind of pId, uId etc.
change variable name from
private Long pId;
to
private Long pid;
And generate getter and setter using IDE.

Finding non-referenced class attributes in Eclipse

I wonder if there are another ways to find attributes in specific class are non-referenced by other classes (I mean, non used attributes).
My way is like that, for example I have a class like:
public class EABHeaderInformation implements Serializable{
/**
*
*/
private static final long serialVersionUID = -4986763088497593972L;
//BargainFinder - AlternateBooking
private int multiTicketSequencdNmbr;
private String resBookDesigCode;
private LocalDateTime departureDate;
private LocalDateTime lastTicketingDate;
private List<String> text;
private String validatingCarrierCode;
public String getValidatingCarrierCode() {
return validatingCarrierCode;
}
public void setValidatingCarrierCode(String validatingCarrierCode) {
this.validatingCarrierCode = validatingCarrierCode;
}
public int getMultiTicketSequencdNmbr() {
return multiTicketSequencdNmbr;
}
public void setMultiTicketSequencdNmbr(int multiTicketSequencdNmbr) {
this.multiTicketSequencdNmbr = multiTicketSequencdNmbr;
}
public String getResBookDesigCode() {
return resBookDesigCode;
}
public void setResBookDesigCode(String resBookDesigCode) {
this.resBookDesigCode = resBookDesigCode;
}
public LocalDateTime getDepartureDate() {
return departureDate;
}
public void setDepartureDate(LocalDateTime departureDate) {
this.departureDate = departureDate;
}
public LocalDateTime getLastTicketingDate() {
return lastTicketingDate;
}
public void setLastTicketingDate(LocalDateTime lastTicketingDate) {
this.lastTicketingDate = lastTicketingDate;
}
public List<String> getText() {
return text;
}
public void setText(List<String> text) {
this.text = text;
}}
It's a simple POJO with getter and setters. I check every getter and setter with 'Open Call Hierarchy' in Eclipse, to find out if the attribute is used by others or not. But it takes a lot of time when I work on bigger classes than this.
So, is there a faster way to do this? Thanks for replies.
Eclipse can already create a warning or error for unused private members, but for public ones the Eclipse stance has always been that it's not a valuable feature. I tend to disagree, because many users have a limited scope that would be useful (specifically, all, or a subset of, the projects in the workspace). See this feature request, this one, and this one.
There are some third party options, such as UCDetector and this simple plug-in example.
See also this SO question and the answers.

JavaFX: Property based entity vs property based wrapper

I am using model entities consiting of JavaFX Properties witch allows me to change the values on the single place, bind them to UI and add changed listeners with extra conditions across the array of model entities (unique values etc.).
I have to store the model in a database so the question is following:
Should I transform my model entity into JPA entity (with AccessType.PROPERTY to set the values) when I do not necessary need to all values (or all the times) to be the properties or create classic value based entity class with property based wrapper (faced) to access it.
Note: Some of the bindable properties does not have to be persisted at all.
Whether or not you should use a particular technique is very opinion-based, so I won't answer your exact question here. I will just offer some options with pros and cons.
The advantage of using JavaFX properties directly in your JPA-annotated entity class is that you keep the design simple, with just one class representing each entity, instead of wrapper classes around the entity-annotated classes.
The disadvantages to using JavaFX properties directly in the JPA entity classes are:
Potential performance cost. JavaFX properties are "heavier" than the plain data type they represent, and there is some cost in creating them and presumably in creating containers for their listeners, etc. This can be minimized (or perhaps eliminated) at the cost of some verbosity, see below.
Adding a dependency on the JavaFX API. While JavaFX ships with the standard JDK from Oracle, it is not a required part of the JSE spec, and some implementations (e.g. OpenJDK) do not include it. This is probably not much of a problem in practice, but you should be aware of it.
You can minimize the cost of using JavFX properties by using the "super lazy" pattern. Here the property objects are only created if they are actually used (e.g. if you register a listener with them); otherwise a surrogate field with the same datatype is used:
#Entity
#Access(AccessType.PROPERTY)
public class Person {
private IntegerProperty age ;
private int _age ;
private StringProperty name ;
private String _name ;
private int id ;
#Id
public int getId() {
return id ;
}
public void setId(int id) {
this.id = id ;
}
public IntegerProperty ageProperty() {
if (age == null) {
age = new SimpleIntegerProperty(_age);
}
return age ;
}
public int getAge() {
if (age == null) {
return _age ;
} else {
return age.get();
}
}
public void setAge(int age) {
if (this.age == null) {
_age = age ;
} else {
this.age.set(age);
}
}
public StringProperty nameProperty() {
if (name == null) {
name = new SimpleStringProperty(_name);
}
return name ;
}
public String getName() {
if (name == null) {
return _name ;
} else {
return name.get();
}
}
public void setName(String name) {
if (this.name == null) {
_name = name ;
} else {
this.name.set(name);
}
}
}
This basically avoids (almost) any performance overhead due to using this class in a non-JavaFX environment, because the properties are not instantiated unless explicitly requested via the xxxProperty() methods. Note that calling these methods is the only way to register listeners, so if listeners are registered, the code guarantees to notify those listeners if setXxx(...) is subsequently invoked. The cost here is some code verbosity and the very minor cost of some redundant null checking (which the JVM will probably optimize for anyway).
This technique obviously doesn't get around the issue of dependency on the JavaFX API.
Another possible option is to use a plain JavaBean with a property change listener:
#Entity
public class Person {
#Id
private int id ;
private int age ;
private String name ;
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public int getAge() {
return age ;
}
public void setAge(int age) {
int oldAge = age ;
this.age = age ;
pcs.firePropertyChange("age", oldAge, age);
}
public String getName() {
return name ;
}
public void setName(String name) {
String oldName = name ;
this.name = name ;
pcs.firePropertyChange("name", oldName, name);
}
// ...
}
Now in your JavaFX Client you can do things like:
TableView<Person> contactTable = new TableView<>();
TableColumn<Person, String> nameCol = new TableView<>("Name");
nameCol.setCellValueFactory(cellData -> {
try {
return JavaBeanStringPropertyBuilder.create()
.bean(cellData.getValue())
.name("name")
.build();
} catch (Exception exc) {
return new RuntimeException(exc);
}
});
The benefits here are that your entity is completely devoid of any dependency on JavaFX. The cost is that your client code is both more verbose and lacks compile-time checking for the existence of the correct method. There is a fair amount of reflection under the hood here, so you will take some (probably minor) performance hit in the evaluation of the properties in the client code. See JavaBean wrapping with JavaFX Properties for more details on this.
I guess one other comment may be pertinent. The most common use case in which you might want to use an entity both in and out of a JavaFX context is where you have a both a web application and a stand-alone (JavaFX) client application which both access data via a web service (e.g. providing and consuming JSON). In this case you might consider keeping two sets of classes in parallel, one using JavaFX properties and one implemented as a Java bean. Since the collection of get/set methods is identical, the JSON serializer should be able to convert the same JSON representation to either form. You can keep both forms synchronized using an interface:
public interface Person {
public int getAge() ;
public void setAge(int age) ;
public String getName() ;
public void setName(String name) ;
}
With the obvious implementations
#Entity
public class PersonEntity implements Person {
private int age ;
private String name ;
#Id
private int id ;
// get/set methods omitted...
}
and
public class PersonFX implements Person {
private final StringProperty name = new SimpleStringProperty() ;
private final IntegerProperty age = new SimpleIntegerProperty() ;
public StringProperty nameProperty() {
return name ;
}
#Override
public final String getName() {
return nameProperty().get();
}
#Override
public final void setName(String name) {
nameProperty().set(name);
}
// similarly for age...
}
Now in the JavaFX client you can have a JSON engine that [de]serializes JSON to and from PersonFX instances, and on the server you have a JSON engine that [de]serializes the same JSON data to and from PersonEntity instances. Since the JSON engine will just work via calls to get/set methods, the objects essentially have the same form from its perspective. I haven't worked with serializing to/from XML data since I started working with JavaFX, so I don't know for certain the same approach would work with XML data, but I assume you could make that work too. You could even do this with Java serialized streams, by defining readObject and writeObject methods in your implementation classes, that expected the same form of data (or by using a Serialization proxy).

Custom code generation for JPA entities from database

I'm here asking for a simple way to add some custom code in the JPA Entity generated by Eclipse from database.
Basically what I want to achieve is to add public String properties containing the names of the entity properties, and use them when I need to provide "property name" as String and be sure that there won't be runtime access errors.
Something like this
#Entity
#Table(name="clients")
#NamedQuery(name="ClientModel.findAll", query="SELECT c FROM ClientModel c")
public class ClientModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="id_client")
private long idClient;
public String name;
public ClienteModel() {
}
public long getIdClient() {
return this.idClient;
}
public void setIdClient(long idClient) {
this.idClient = idClient;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
//CUSTOM CODE
public static final String idClientProperty = "idClient";
public static final String nameProperty = "name";
}
So i could use property name like
ClientModel.nameProperty
and be compile-time safe of his existence and in case of names refactoring after a further entity generation.
I'm aware of the existence of Telosys Tools & co., but I hoped there could be something simplier/faster (like a custom class provided as plugin in WSDL_to_entity generation with JAXB)
Thank you.
In the end I've used Telosys Tools, even if I didn't want to add another tool to my project,
Is kinda easy to set up, just read here
https://sites.google.com/site/telosystools/getting-started/21-configure-a-project
In my specific case i've added to the template "JPA_bean_with_links" this code during getters creation
#if ( $field.getter ) public static String ${field.getter}Property() {
return "$field.name";
}
#end

What does Eclipse consider as a "simple getter" or a "simple setter"?

I use the Eclipse debugger on a regular basis and this has always bugged me about the IDE. Step filtering is such an invaluable tool, that way I'm not stepping into classes that does not have source code or I'm simply not interested in. However Eclipse isn't getting it right for most cases. In particular, there are options to "Filter simple getters" and "Filter simple setters".
I might use a getter that just simply returns the value of a member variable.
private String value;
public String getValue()
{
return value;
}
Or perhaps a getter that lazily instantiates an expensive object.
private IObjectFactory instance;
public IObjectFactory getInstance()
{
if (instance == null)
instance = ObjectFactory.createFactory();
return instance;
}
I might use a setter that just sets the value of a member variable.
private String value;
public void setValue(String value)
{
this.value = value;
}
I might want to support fluent syntax.
private String value;
public ObjectFactory setValue(String value)
{
this.value = value;
return this;
}
Or perhaps do some validation or event triggering.
private String user;
public void setUser(String user)
{
if (StringUtils.isBlank(user))
throw ExceptionHelper.argumentNull("user");
this.user = user;
}
private String title;
public void setTitle(String title)
{
if (!StringUtils.equals(this.title, title))
{
this.title= title;
onPropertyChanged("title", title);
}
}
And for every single one of these uses, stepping into code using eclipse steps into these methods...
What does Eclipse consider as a "simple getter" or a "simple setter"?
The filters are definitely enabled:
In case it matters, I'm using Eclipse Kepler build 20130614-0229. I'm using JRE6 to run Eclipse and a Tomcat 7 server hosting a Java 1.4 web app. Although we ultimately target 1.4, it is compiled locally using JDK6 so I don't see that as being a problem. I do have JRebel installed and in use, perhaps the classloader is interfering with the algorithms which determine what is considered "simple"? Combined with the "Step through filters" option enabled, it's stepping through my code perhaps. I'll experiment further after thinking about this.
Ok I think I tracked it down.
Under normal circumstances, a plain getter and plain setter (examples 1 and 3 in the question) will be stepped over if these filters are enabled. If a special class loader such as JRebel which modifies methods to hook into them is installed and in use, it seems to interfere with Eclipse's algorithms which determine if a method is a "simple getter" or "simple setter".
So a getter that might look like this in code:
public String getValue()
{
return this.value;
}
Might be altered to look something like this from the JVM's perspective:
public String getValue()
{
Proxy proxy = getProxy(this);
return (String)proxy.invoke("getValue", new Object[] { });
// this is all just an example,
// it's defintely way more complicated than this
}
This altered code confuses Eclipse into thinking "that's not a simple getter so step into it". It does but the actual source code is my actual simple getter which then confuses me thinking "Why did Eclipse step into this simple getter?"
I ran a very contrived test to try to get the step filtering to work.
import org.apache.commons.lang.StringUtils;
public class Program
{
public static void main(String[] args)
{
User bob = new User("0001", "Bob");
String id = bob.getId(); //stepped over
String name = bob.getName(); //stepped over
IHome home = bob.getHome(); //stepped into
bob.setId("foo"); //stepped into
bob.setName("Bobby"); //stepped over
String asString = bob.setNameFluent("Bobbo").toString(); //stepped into
IHome newHome = Neighborhood.getHome("moo");
bob.setHome(newHome); //stepped into
return;
}
static class User
{
private String id;
private String name;
private IHome home;
public User() { this("0001", null); }
public User(String id, String name) { this.id = id; this.name = name; }
public String getId() // simple
{
return id;
}
public String getName() // simple
{
return name;
}
public IHome getHome() // not simple
{
if (home == null)
home = Neighborhood.getHome(id);
return home;
}
public void setId(String id) // not simple
{
if (StringUtils.isBlank(id))
throw ExceptionHelper.argumentBlank("id");
this.id = id;
}
public void setName(String name) // simple
{
this.name = name;
}
public User setNameFluent(String name) // not simple
{
this.name = name;
return this;
}
public void setHome(IHome home) // not simple
{
if (home != null)
{
this.home = home;
onHomeChanged();
}
}
protected void onHomeChanged()
{
this.id = home.getId();
}
public String toString()
{
return "User { name=" + getName() + ", home=" + getHome() + " }";
}
}
static interface IHome
{
String getId();
String getLocation();
}
static class Neighborhood
{
public static IHome getHome(String id)
{
return new Home(id);
}
static class Home implements IHome
{
private String id;
public Home(String id) { this.id = id; }
public String getId() { return id; }
public String getLocation() { return "Home" + id; }
public String toString() { return "Home: " + getLocation(); }
}
}
static class ExceptionHelper
{
public static IllegalArgumentException argumentBlank(String name)
{
return new IllegalArgumentException("Argument " + name + " must not be blank");
}
}
}
With the default configuration (JDK6 without JRebel), the step filtering appeared to work. Trying to step into the simple methods actually stepped over them. After enabling JRebel and stepping through the code again, it stepped into all the methods. And it doesn't matter if "Step through filters" is enabled or not.
tldr;
By using JRebel, the magic that it does confused Eclipse making simple getters and simple setters look more complicated than they originally are. Disabling JRebel will cause the filters to work as intended.
Here is a page on Eclipse's website, which describes the two options in a little more detail
Filter simple getters:
This option controls if simple Java bean-style getters should always be filtered or not while stepping
Filter simple setters:
This option controls if simple Java bean-style setters should always be filtered or not while stepping
From the sounds of it, examples 1 and 3 that you give do appear to be what they mean here. Not sure why you're seeing the behavior that you are though.
EDIT: Looks like the original poster found the issue; something about JRebel overcomplicating the methods.

Categories

Resources