No generator named "system-uuid" is defined in the persistence unit - eclipse

In eclipse Im getting the error "No generator named "system-uuid" is defined in the persistence unit"
#Id
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
#GeneratedValue(generator = "system-uuid")
private String userId;
Previous posts have asked the same question and the answer has been to turn off this error in eclipse ? but this isnt possible in the version of eclipse I'm using (mars) and Id really like to know the cause of this.

Related

Eclipse RCP persistence framework integration

I am developing an Eclipse application, using the latest version of Eclipse RCP and RAP 2022-12.
I have a target platform, a product file, a complete Maven/Tycho build system working with unit and integration test.
My need now is to persist to a DB (my preference here is MongoDB) a simple POJO class, for example:
/**
* The logged user.
*/
public class User implements IMASUser {
/**
* Developer user name
*/
public static final String DEVELOPER_USER_NAME = "developer"; //$NON-NLS-1$
private static final SimpleDateFormat DB_DATE_FORMAT = new SimpleDateFormat(CommonConstants.DB_DATE_FORMAT_PATTERN);
private int m_id;
private String m_username;
private String m_password;
private String m_name;
private String m_surname;
private String m_domainID;
private String m_office;
private String m_blockCode;
private String m_eMail;
private AccessLevel m_accessLevel;
private boolean m_isBeta; // Access to beta program
private boolean m_isActive; // Currently working (hired and actively developing)
private Date m_loginDate;
private Date m_lastLoginDate;
......
What is the most "common" and easy way to integrate a persistence framework into an Eclipse RCP application?
In a standard Java app I would try Hibernate or Spring Boot but here the integration in the OSGi environment is somehow problematic.
I tried to integrate:
Spring Boot JPA
Hibernate
Eclipselink
adding the dependencies to the target platform.
All of those have problems runtime discovering the needed service and classes.
For sure I'm missing some experience in Eclipse/RCP/OSGi.
Can you share some of your experience (if any), I can't find any up to date documentation.
Thank you!

Approve modification on entity before publish

I am trying to create a system that requires an admin to approve a modification to an entity before being published. This system is a REST API with authentication/authorization already working, so that part is not important. Let's assume we have a model depicting an article, with a title and a body. A normal user is allowed to modify all the fields, but before the article is published, it must be approved by an admin. But while the article is in ``approval mode'', the old version of the article must be accessible by the REST API so to at least have a version that works (and the API does not return a 404).
The requirements are:
I am using Spring Data and PostgreSQL so the one that gives me less headaches while integrating it is the one I am going with
The less tinkering with weird checks, the better
If possible, it should be modifiable to be used with other entities
If possible, I would like to keep the old versions and who modified them. Non essential but would be nice
I have two different ideas, but I am not sure which one is the best one:
Create an abstract parent class, and then extend it with an approved and a non-approved version. Then, when the modification is approved the entity is transformed into an approved one and the API will return the new version:
public abstract class Article {}
public class ApprovedArticle extends Article {}
public class ModifiedArticle extends Article {}
Create a separate table where the modified entities are stored, and restrict the view to be admin only. In this case I would isolate the two types and make it easier when fetching info. But I am losing the ``history'' this way and I need to fetch from two different locations.
Simple boolean flag: this is my last resort, and I would love to avoid it!
Is there a better way or should I use one of the outlined examples?
Thanks!
Look into spring Auditing.
https://www.baeldung.com/database-auditing-jpa
So there is an idea:
for each table you have a history table, each history table has REVTYPE( “0” for adding, “1” for updating, “2” for removing an entity) and REV(change number) columns.
Besides these, you need an extra table named REVINFO will be generated by default, to have user details you need to extend default DefaultRevisionEntity class.
#Entity
#RevisionEntity(YOURRevisionListener.class)
#Table(name = "your_audit_info")
#AttributeOverrides(
{#AttributeOverride(name = "timestamp", column = #Column(name = "REVTSTMP")),
#AttributeOverride(name = "id", column = #Column(name = "REV"))})
public class AuditInfo extends DefaultRevisionEntity
{
private static final long serialVersionUID = 8458400378132903089L;
#Column(name = "UpdateUser", nullable = false)
private String userName;
public String getUserName()
{
return userName;
}
public void setUserName(
final String userName)
{
this.userName = userName;
}
}
with audit set up, you get user details if the change approved by admin then compare revisions number when the operation started and operation approved to avoid overwriting by others.
#PrePersist
public void onPrePersist() {
audit("INSERT");
}
#PreUpdate
public void onPreUpdate() {
audit("UPDATE");
}
#PreRemove
public void onPreRemove() {
audit("DELETE");
}
I know it is a very high-level approach, but it can work in your case

Invocate correctly with EJB using JPA and Postgresql

As a first step to start doing Spring work, Ive been tasked to do just the simplest of things. I've followed this small little tutorial I found and copied it to have a starting point. But when I run the program, I get this error
Advertencia: A system exception occurred during an invocation on EJB UsersFacade, method: public void Session.UsersFacade.Save(java.lang.String,java.lang.String,java.lang.String)
Advertencia: javax.ejb.EJBException
...
...
Caused by: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.NotNull: #javax.validation.constraints.NotNull(message={javax.validation.constraints.NotNull.message}, groups=[], payload=[])
Even though I followed the tutorial correctly. Do I have to do more steps because I use Postgresql, or is there something else that I have to do that wasn't in the video?
Well, in the given error, it says
Duplicate annotation for class: interface javax.validation.constraints.NotNull
So in the Users class I decided to comment the #NotNull and (after a second error) the #Size for all my strings. This lets me save things into my database without a problem.
To use the #NotNull and #Size correctly though, I had to modify the #Column to be like this:
#Column(name = "name", length = 20, nullable = false)
The only thing left is to limit the textboxes to the size of the columns.

GWT Bean validation does not return all constraint violations in compiled mode

I am experiencing different behavior for client side bean validation when running in gwt development mode than in compiled mode. I have been trying to debug and resolve this issue for hours (days actually) but, although further still did not find the root cause and am currently stuck. Hence my request for help.
In general I have been following the approach advocated here http://www.gwtproject.org/doc/latest/DevGuideValidation.html
and was further more inspired by various articles and questions on StackOverlow. So I have the user enter an object on the client. Than I validate it client side via a call to the validator that has been created by the validator factory.
The problem I am experiencing is that when more than one constraint is validated (i.e. the user enters 2 or more "mistakes") the validator does not (always) return all constraint violations when running in compiled mode, while it does return them all when running in gwt development mode.
The object I try to validate is of the class EnvyMonUser
#Entity
public class EnvyMonUser implements Serializable, Obj<EnvyMonUser> {
private static final long serialVersionUID = 3L;
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
#Id
private Long id;
#NotNull(message = "company must be selected")
#Index
private Key<Company> companyKey;
#Index
private String googleUserId;
#NotNull(message = "email address must be set")
#Pattern(regexp = EMAIL_PATTERN, message = "invalid email address")
#Index
private String email;
#NotNull(message = "name must be set")
#Size(min = 3, message = "must have a name of minimal 3 characters")
#Index
private String nickName;
#NotNull(message = "location must be selected")
#Index
private Key<SampleLocation> sampleLocationKey;
#NotNull(message = "result must be set")
#Index
private Long value;
...
Where Company and SampleLocation are two other classes. (The annotations #Entity, #Index, #Id and the class Key are of Objectify. I use the same entity class(es) client and server (gae) side. )
Once the user has entered an EnvyMonUser object I validate it via a validator, i.e.
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
...
EnvyMonUser obj = getView().getEditorDriver().flush();
Set<ConstraintViolation<O>> validate = validator.validate(obj);
where my validation factory is
public final class AppValidatorFactory extends AbstractGwtValidatorFactory {
#GwtValidation(value = { MonitorType.class, Measurement.class,
ProgramMeasurement.class, EnvyMonUser.class, Company.class,
SampleLocation.class })
public interface GwtValidator extends Validator {
}
#Override
public AbstractGwtValidator createValidator() {
return GWT.create(GwtValidator.class);
}
}
Am I doing something wrong?
Desperate as I was I tried removing and adding several fields but have not found any logical pattern. Depending on which fields I leave out and also on which of the fields are filled correctly by the user the (missing) constraint(s) in compiled mode change.
I have already tried multiple routes but no success so far. For example at some point I thought this was caused by using objectify. However when I remove sampleLocationKey member it works perfectly fine for companyKey member. I also tried removing the objectify attributes but this also doesn't seem to make a difference.
An interesting thing I did observe (by accident) is that when I remove (comment) some of the members from the hashCode and equals methods the behavior changes. Not sure why this is. Maybe it has something to do with how the validator generator is implemented.
Does anyone have any clue?
Also a pointer in the right direction is appreciated. Does someone for example know where I can find the validator that is generated. Or the sources of the validator generator?
Some versions of libraries I use:
gwt 2.6.0
hibernate-validator-4.1.0.Final.jar
hibernate-validator-4.1.0.Final-sources.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
log4j-1.2.16.jar
objectify 4.0.1
Turns out the problem was not in my code but a bug in gwt sources for com.google.gwt.validation.client.impl.ConstraintViolationImpl . See https://groups.google.com/forum/#!topic/Google-Web-Toolkit/xRVGnMWfttc for a full description of the problem and solution.
I had the same issue. The validations were working fine on dev mode and all the error messages were showing up on the UI but in the prod mode we could see only one error message at one time. Late on when debugged and found that my DTO has implemented equals and hashcode method and that what causing this issue. The moment is removed these two implementations from my DTO every things worked fine after that.
I am using GWT 2.6.1.

Spring Data JPA Auditing never getting called at runtime

I'm presently struggling with getting Spring Data JPA Auditing to work, it is presently not setting the fields and doesn't seem to be getting called in any way when working with Entities. In particular any insight into how it hooks into the standard flow of persisting Entities would be helpful.
I'm presently using Spring Data JPA 1.5.0.M1 with Spring 3.2.6 and the basic configuration for the auditing piece is:
#Configuration
#EnableJpaAuditing(auditorAwareRef = "auditorAware")
#EnableJpaRepositories(basePackages = "org.myproject.dao")
#EnableTransactionManagement
public class JpaConfig {
...}
the relevant entity at the moment is marked up with the annotations and the interface while trying to work this out (the annotations would be preferred). I realize this should not be done but I copied and pasted for the moment.
#Entity
public class AutoDraft implements Auditable<Long, Long> {
#SequenceGenerator(name="seq_auto_draft", sequenceName="SEQ_AUTO_DRAFT")
#GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq_auto_draft")
#Id
private Long id;
#CreatedDate
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime createdDate;
#LastModifiedDate
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime lastModifiedDate;
In the logs the relevant beans are being set up and I can catch the AuditingHandler being properly configured within the AuditingEntityListener on startup, but nothing seems to be getting triggered at runtime, nor are there any audit related logging messages associated with specific entities or repositories. My attention is presently drawn by the AuditingBeanFactoryPostProcessor, but I've already spent too long on this so could use any assistance.
I know this is an old question, but I hit the same problem and a comment helped me resolve it. So I thought I would make it clearer if anyone falls on this question again.
The documentation for Spring Data is a bit misleading in that it implies that you can enable auditing simply by annotating a #Configuration class with #EnableJpaAuditing.
However, the part I found unclear is that you still need to modify the orm.xml file (https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#auditing):
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="….data.jpa.domain.support.AuditingEntityListener" />
</entity-listeners>
</persistence-unit-defaults>
However, if you are using a pure annotation based solution, you may not have an orm.xml file. As indicated by Matt Whipple in a comment, you have to add the #EntityListeners annotation to you entity classes so that the JPA persistence library calks the Spring auditing class when persisting the objects (which in turn deals with the auditing).
So a complete example could be something like:
#Configuration
#EnableJpaAuditing
#PropertySource({ "application.properties" })
public class AppConfig {
/**
* Stubbed method for the auditor as the app does not concern itself with auditing any User fields
* Consequently, return null for the current auditor
* #return
*/
#Bean
public AuditorAware<User> auditorProvider(){
return new AuditorAware<User>() {
#Override
public User getCurrentAuditor() {
return <User object that is Logged In>;
}
};
}
}
Then on your entity:
#Entity
#EntityListeners(AuditingEntityListener.class)
public class Log {
#Id
#GeneratedValue
private long id;
#CreatedDate
#Column(nullable=false)
private Date createdOn;
// bunch of other audit fields (and other fields)
...
...
}
It seems like you forgot to configure AuditingEntityListener in the orm.xml (which is still neccessary). Add this lines to your orm.xml:
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="….data.jpa.domain.support.AuditingEntityListener" />
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
see: Spring data jpa documentation: Auditing.