Project

General

Profile

Download (20 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2007 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.model.common;
10

    
11
import java.beans.PropertyChangeEvent;
12
import java.beans.PropertyChangeListener;
13
import java.beans.PropertyChangeSupport;
14
import java.io.Serializable;
15
import java.lang.reflect.Method;
16
import java.util.HashSet;
17
import java.util.List;
18
import java.util.Set;
19
import java.util.UUID;
20

    
21
import javax.persistence.Basic;
22
import javax.persistence.Column;
23
import javax.persistence.FetchType;
24
import javax.persistence.GeneratedValue;
25
import javax.persistence.Id;
26
import javax.persistence.ManyToOne;
27
import javax.persistence.MappedSuperclass;
28
import javax.persistence.Transient;
29
import javax.validation.constraints.Min;
30
import javax.validation.constraints.NotNull;
31
import javax.xml.bind.annotation.XmlAccessType;
32
import javax.xml.bind.annotation.XmlAccessorType;
33
import javax.xml.bind.annotation.XmlAttribute;
34
import javax.xml.bind.annotation.XmlElement;
35
import javax.xml.bind.annotation.XmlID;
36
import javax.xml.bind.annotation.XmlIDREF;
37
import javax.xml.bind.annotation.XmlSchemaType;
38
import javax.xml.bind.annotation.XmlTransient;
39
import javax.xml.bind.annotation.XmlType;
40
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
41

    
42
import org.apache.commons.lang3.StringUtils;
43
import org.apache.log4j.Logger;
44
import org.hibernate.annotations.NaturalId;
45
import org.hibernate.annotations.Type;
46
import org.hibernate.envers.Audited;
47
import org.hibernate.search.annotations.Analyze;
48
import org.hibernate.search.annotations.DocumentId;
49
import org.hibernate.search.annotations.Field;
50
import org.hibernate.search.annotations.FieldBridge;
51
import org.hibernate.search.annotations.Index;
52
import org.hibernate.search.annotations.Store;
53
import org.joda.time.DateTime;
54

    
55
import eu.etaxonomy.cdm.hibernate.HibernateProxyHelper;
56
import eu.etaxonomy.cdm.hibernate.search.DateTimeBridge;
57
import eu.etaxonomy.cdm.hibernate.search.NotNullAwareIdBridge;
58
import eu.etaxonomy.cdm.hibernate.search.UuidBridge;
59
import eu.etaxonomy.cdm.jaxb.DateTimeAdapter;
60
import eu.etaxonomy.cdm.jaxb.UUIDAdapter;
61
import eu.etaxonomy.cdm.model.NewEntityListener;
62
import eu.etaxonomy.cdm.model.permission.User;
63
import eu.etaxonomy.cdm.strategy.match.IMatchStrategyEqual;
64
import eu.etaxonomy.cdm.strategy.match.IMatchable;
65
import eu.etaxonomy.cdm.strategy.match.Match;
66
import eu.etaxonomy.cdm.strategy.match.MatchMode;
67

    
68

    
69

    
70

    
71
/**
72
 * The base class for all CDM domain classes implementing UUIDs and bean property change event firing.
73
 * It provides a globally unique UUID and keeps track of creation date and person.
74
 * The UUID is the same for different versions (see {@link VersionableEntity}) of a CDM object, so a locally unique id exists in addition
75
 * that allows to safely access and store several objects (=version) with the same UUID.
76
 *
77
 * This class together with the {@link eu.etaxonomy.cdm.aspectj.PropertyChangeAspect}
78
 * will fire bean change events to all registered listeners. Listener registration and event firing
79
 * is done with the help of the {@link PropertyChangeSupport} class.
80
 *
81
 * @author m.doering
82
 *
83
 */
84
@XmlAccessorType(XmlAccessType.FIELD)
85
@XmlType(name = "CdmBase", propOrder = {
86
    "created",
87
    "createdBy"
88
})
89
@MappedSuperclass
90
public abstract class CdmBase implements Serializable, ICdmBase, ISelfDescriptive, Cloneable{
91

    
92
    private static final long serialVersionUID = -3053225700018294809L;
93
    @SuppressWarnings("unused")
94
    private static final Logger logger = Logger.getLogger(CdmBase.class);
95

    
96
    protected static final int CLOB_LENGTH = 65536;
97

    
98
    @Transient
99
    @XmlTransient
100
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
101

    
102
    @Transient
103
    @XmlTransient
104
    private static NewEntityListener newEntityListener;
105

    
106
    //@XmlAttribute(name = "id", required = true)
107
    @XmlTransient
108
    @Id
109
//	@GeneratedValue(generator = "system-increment")  //see also AuditEvent.revisionNumber
110
//	@GeneratedValue(generator = "enhanced-table")
111
    @GeneratedValue(generator = "custom-enhanced-table")
112
    @DocumentId
113
    @FieldBridge(impl=NotNullAwareIdBridge.class)
114
    @Match(MatchMode.IGNORE)
115
    @NotNull
116
    @Min(0)
117
    @Audited
118
    private int id;
119

    
120
    @XmlAttribute(required = true)
121
    @XmlJavaTypeAdapter(UUIDAdapter.class)
122
    @XmlID
123
    @Type(type="uuidUserType")
124
    @NaturalId // This has the effect of placing a "unique" constraint on the database column
125
    @Column(length=36)  //TODO needed? Type UUID will always assure that is exactly 36
126
    @Match(MatchMode.IGNORE)
127
    @NotNull
128
    @Field(store = Store.YES, index = Index.YES, analyze = Analyze.NO)
129
    @FieldBridge(impl = UuidBridge.class)
130
    @Audited
131
    protected UUID uuid;
132

    
133
    @XmlElement (name = "Created", type= String.class)
134
    @XmlJavaTypeAdapter(DateTimeAdapter.class)
135
    @Type(type="dateTimeUserType")
136
    @Basic(fetch = FetchType.LAZY)
137
    @Match(MatchMode.IGNORE)
138
    @Field(analyze = Analyze.NO)
139
    @FieldBridge(impl = DateTimeBridge.class)
140
    @Audited
141
    private DateTime created;
142

    
143
    @XmlElement (name = "CreatedBy")
144
    @XmlIDREF
145
    @XmlSchemaType(name = "IDREF")
146
    @ManyToOne(fetch=FetchType.LAZY)
147
    @Match(MatchMode.IGNORE)
148
    @Audited
149
    private User createdBy;
150

    
151
    /**
152
     * Class constructor assigning a unique UUID and creation date.
153
     * UUID can be changed later via setUuid method.
154
     */
155
    public CdmBase() {
156
        this.uuid = UUID.randomUUID();
157
        this.created = new DateTime().withMillisOfSecond(0);
158
    }
159

    
160
    public static void setNewEntityListener(NewEntityListener nel) {
161
        newEntityListener = nel;
162
    }
163

    
164
    public static void fireOnCreateEvent(CdmBase cdmBase) {
165
        if(newEntityListener != null) {
166
            newEntityListener.onCreate(cdmBase);
167
        }
168
    }
169

    
170
    /**
171
     * see {@link PropertyChangeSupport#addPropertyChangeListener(PropertyChangeListener)}
172
     * @param listener
173
     */
174
    public void addPropertyChangeListener(PropertyChangeListener listener) {
175
        propertyChangeSupport.addPropertyChangeListener(listener);
176
    }
177

    
178
    /**
179
     * see {@link PropertyChangeSupport#addPropertyChangeListener(String, PropertyChangeListener)}
180
     */
181
    public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
182
        propertyChangeSupport.addPropertyChangeListener(propertyName, listener);
183
    }
184

    
185
    /**
186
     * see {@link PropertyChangeSupport#addPropertyChangeListener(PropertyChangeListener)}
187
     */
188
    public void removePropertyChangeListener(PropertyChangeListener listener) {
189
        propertyChangeSupport.removePropertyChangeListener(listener);
190
    }
191

    
192
    /**
193
     * @see PropertyChangeSupport#addPropertyChangeListener(String, PropertyChangeListener)
194
     */
195
    public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
196
        propertyChangeSupport.removePropertyChangeListener(propertyName, listener);
197
    }
198

    
199
    public boolean hasListeners(String propertyName) {
200
        return propertyChangeSupport.hasListeners(propertyName);
201
    }
202

    
203
    public void firePropertyChange(String property, String oldval, String newval) {
204
        propertyChangeSupport.firePropertyChange(property, oldval, newval);
205
    }
206
    public void firePropertyChange(String property, int oldval, int newval) {
207
        propertyChangeSupport.firePropertyChange(property, oldval, newval);
208
    }
209
    public void firePropertyChange(String property, float oldval, float newval) {
210
        propertyChangeSupport.firePropertyChange(property, oldval, newval);
211
    }
212
    public void firePropertyChange(String property, boolean oldval, boolean newval) {
213
        propertyChangeSupport.firePropertyChange(property, oldval, newval);
214
    }
215
    public void firePropertyChange(String property, Object oldval, Object newval) {
216
        propertyChangeSupport.firePropertyChange(property, oldval, newval);
217
    }
218
    public void firePropertyChange(PropertyChangeEvent evt) {
219
        propertyChangeSupport.firePropertyChange(evt);
220
    }
221

    
222
    /**
223
     * This method was initially added to {@link CdmBase} to fix #5161.
224
     * It can be overridden by subclasses such as {@link IdentifiableEntity}
225
     * to explicitly initialize listeners. This is needed e.g. after de-serialization
226
     * as listeners are not serialized due to the @Transient annotation.
227
     * However, it can be generally used for other use-cases as well
228
     */
229
    public void initListener() {}
230

    
231
    /**
232
     * Adds an item to a set of <code>this</code> object and fires the according
233
     * {@link PropertyChangeEvent}. Workaround as long as add and remove is not yet
234
     * implemented in aspectJ.
235
     * @param set the set the new item is added to
236
     * @param newItem the new item to be added to the set
237
     * @param propertyName the name of the set as property in <code>this</code> object
238
     */
239
    protected <T extends CdmBase> void addToSetWithChangeEvent(Set<T> set, T newItem, String propertyName ){
240
        Set<T> oldValue = new HashSet<>(set);
241
        set.add(newItem);
242
        firePropertyChange(new PropertyChangeEvent(this, propertyName, oldValue, set));
243
    }
244

    
245
    /**
246
     * Removes an item from a set of <code>this</code> object and fires the according
247
     * {@link PropertyChangeEvent}. Workaround as long as add and remove is not yet
248
     * implemented in aspectJ.
249
     * @param set the set the item is to be removed from
250
     * @param itemToRemove the item to be removed from the set
251
     * @param propertyName the name of the set as property in <code>this</code> object
252
     */
253
    protected <T extends CdmBase> void removeFromSetWithChangeEvent(Set<T> set, T itemToRemove, String propertyName ){
254
        Set<T> oldValue = new HashSet<T>(set);
255
        set.remove(itemToRemove);
256
        firePropertyChange(new PropertyChangeEvent(this, propertyName, oldValue, set));
257
    }
258

    
259
    @Override
260
    public UUID getUuid() {
261
        return uuid;
262
    }
263
    @Override
264
    public void setUuid(UUID uuid) {
265
        this.uuid = uuid;
266
    }
267

    
268
    @Override
269
    public int getId() {
270
        return this.id;
271
    }
272
    @Override
273
    public void setId(int id) {  //see #265 (private ?)
274
        this.id = id;
275
    }
276

    
277
    @Override
278
    public DateTime getCreated() {
279
        return created;
280
    }
281
    @Override
282
    public void setCreated(DateTime created) {
283
        if (created != null){
284
            created = created.withMillisOfSecond(0);
285
            //created.set(Calendar.MILLISECOND, 0);  //old, can be deleted
286
        }
287
        this.created = created;
288
    }
289

    
290

    
291
    @Override
292
    public User getCreatedBy() {
293
        return this.createdBy;
294
    }
295
    @Override
296
    public void setCreatedBy(User createdBy) {
297
        this.createdBy = createdBy;
298
    }
299

    
300
// ************************** Hibernate proxies *******************/
301

    
302
    /**
303
     * If entity is a HibernateProxy it returns the initialized object.
304
     * Otherwise entity itself is returned.
305
     * @param entity
306
     * @return
307
     * @throws ClassCastException
308
     */
309
    public static <T> T deproxy(T entity) {
310
        return HibernateProxyHelper.deproxy(entity);
311
    }
312

    
313
    /**
314
     * These methods are present due to HHH-1517 - that in a one-to-many
315
     * relationship with a superclass at the "one" end, the proxy created
316
     * by hibernate is the superclass, and not the subclass, resulting in
317
     * a ClassCastException when you try to cast it.
318
     *
319
     * Hopefully this will be resolved through improvements with the creation of
320
     * proxy objects by hibernate and the following methods will become redundant,
321
     * but for the time being . . .
322
     * @param <T>
323
     * @param object
324
     * @param clazz
325
     * @return
326
     * @throws ClassCastException
327
     */
328
    //non-static does not work because javassist already unwrapps the proxy before calling the method
329
     public static <T extends CdmBase> T deproxy(Object object, Class<T> clazz) throws ClassCastException {
330
         return HibernateProxyHelper.deproxy(object, clazz);
331
     }
332

    
333
     @Override
334
     public boolean isInstanceOf(Class<? extends CdmBase> clazz) throws ClassCastException {
335
         return HibernateProxyHelper.isInstanceOf(this, clazz);
336
     }
337

    
338
    @Override
339
    @XmlTransient
340
    @Transient
341
    public boolean isPersited() {
342
        return id != 0;
343
    }
344

    
345
// ************* Object overrides *************************/
346

    
347
    /**
348
     * Is <code>true</code> if UUID and created timestamp (is this really needed/make sense?)
349
     * is the same for the passed Object and this one.
350
     * This method is final as subclasses should not override it.<BR>
351
     *
352
     * The contract should be the same for all persistable entities.
353
     * 2 instances are equal if they represent the same entity in a given
354
     * database.<BR>
355
     * NOTE: currently the method is only final in {@link VersionableEntity#equals(Object)}.
356
     * For discussion see #7202.
357
     * <BR><BR>
358
     *
359
     * If one wants to compare 2 CdmBase entities content wise you may use e.g. a
360
     * {@link IMatchStrategyEqual match strategy} and make sure
361
     * {@link IMatchable matching} is implemented for the respective CdmBase subclass.
362
     * You may adapt your match strategy to your own needs.
363
     *
364
     * See {@link http://www.hibernate.org/109.html hibernate109}, {@link http://www.geocities.com/technofundo/tech/java/equalhash.html geocities},
365
     * or {@link http://www.ibm.com/developerworks/java/library/j-jtp05273.html ibm}
366
     * for more information about equals and hashcode.
367
     * <BR>
368
     * See also https://dev.e-taxonomy.eu/redmine/issues/7155 and related tickets for discussion.
369
     *
370
     * @see java.lang.Object#equals(java.lang.Object)
371
     *
372
     */
373
    @Override
374
    public boolean equals(Object obj) {
375
        if (obj == this){
376
            return true;
377
        }
378
        if (obj == null){
379
            return false;
380
        }
381
        if (!CdmBase.class.isAssignableFrom(obj.getClass())){
382
            return false;
383
        }
384
        ICdmBase cdmObj = (ICdmBase)obj;
385
        UUID objUuid = cdmObj.getUuid();
386
        if (objUuid == null){
387
            throw new NullPointerException("CdmBase is missing UUID");
388
        }
389
        boolean uuidEqual = objUuid.equals(this.getUuid());
390
        //TODO is this still needed?
391
//        boolean createdEqual = CdmUtils.nullSafeEqual(cdmObj.getCreated(), this.getCreated());
392
        boolean createdEqual = true; //preliminary, to test im createdEqual is still needed #7201
393
        if (! uuidEqual || !createdEqual){
394
                return false;
395
        }
396
        return true;
397
    }
398

    
399

    
400

    
401
    /** Overrides {@link java.lang.Object#hashCode()}
402
     *  See {@link http://www.hibernate.org/109.html hibernate109}, {@link http://www.geocities.com/technofundo/tech/java/equalhash.html geocities}
403
     * or {@link http://www.ibm.com/developerworks/java/library/j-jtp05273.html ibm}
404
     * for more information about equals and hashcode.
405
     */
406
    @Override
407
    public int hashCode() {
408
           int hashCode = 7;
409
           if(this.getUuid() != null) {
410
               //this unfortunately leads to errors when loading maps via hibernate
411
               //as hibernate computes hash values for CdmBase objects used as key at
412
               // a time when the uuid is not yet loaded from the database. Therefore
413
               //the hash values later change and give wrong results when retrieving
414
               //data from the map (map.get(key) returns null, though there is an entry
415
               //for key in the map.
416
               //see further comments in #2114
417
               int result = 29 * hashCode + this.getUuid().hashCode();
418
//		       int shresult = 29 * hashCode + Integer.valueOf(this.getId()).hashCode();
419
               return result;
420
           } else {
421
               return 29 * hashCode;
422
           }
423
    }
424

    
425
    /**
426
     * Overrides {@link java.lang.Object#toString()}.
427
     * This returns an String that identifies the object well without being necessarily unique. Internally the method is delegating the
428
     * call to {link {@link #instanceToString()}.<br>
429
     * <b>Specification:</b> This method should never call other object' methods so it can be well used for debugging
430
     * without problems like lazy loading, unreal states etc.
431
     * <p>
432
     * <b>Note</b>: If overriding this method's javadoc always copy or link the above requirement.
433
     * If not overwritten by a subclass method returns the class, id and uuid as a string for any CDM object.
434
     * <p>
435
     * <b>For example</b>: Taxon#13&lt;b5938a98-c1de-4dda-b040-d5cc5bfb3bc0&gt;
436
     * @see java.lang.Object#toString()
437
     */
438
    @Override
439
    public String toString() {
440
        return instanceToString();
441
    }
442

    
443
    /**
444
     * This returns an String that identifies the cdm instance well without being necessarily unique.
445
     * The string representation combines the class name the {@link #id} and {@link #uuid}.
446
     * <p>
447
     * <b>For example</b>: Taxon#13&lt;b5938a98-c1de-4dda-b040-d5cc5bfb3bc0&gt;
448
     * @return
449
     */
450
    public String instanceToString() {
451
        return this.getClass().getSimpleName()+"#"+this.getId()+"<"+this.getUuid()+">";
452
    }
453

    
454
// **************** invoke methods **************************/
455

    
456
    protected void invokeSetMethod(Method method, Object object){
457
        try {
458
            method.invoke(object, this);
459
        } catch (Exception e) {
460
            e.printStackTrace();
461
            //TODO handle exceptioin;
462
        }
463
    }
464

    
465
    protected void invokeSetMethodWithNull(Method method, Object object){
466
        try {
467
            Object[] nul = new Object[]{null};
468
            method.invoke(object, nul);
469
        } catch (Exception e) {
470
            e.printStackTrace();
471
            //TODO handle exceptioin;
472
        }
473
    }
474

    
475
    @Transient
476
	@Override
477
	public String getUserFriendlyTypeName(){
478
		return getClass().getSimpleName();
479
	}
480

    
481
	@Transient
482
	@Override
483
	public String getUserFriendlyDescription(){
484
		return toString();
485
	}
486

    
487
	@Override
488
	public String getUserFriendlyFieldName(String field){
489
		return field;
490
	}
491

    
492
// ********************* HELPER ****************************************/
493

    
494
    protected <T extends CdmBase> boolean replaceInList(List<T> list,
495
            T newObject, T oldObject){
496
        boolean result = false;
497
        for (int i = 0; i < list.size(); i++){
498
            if (list.get(i).equals(oldObject)){
499
                list.set(i, newObject);
500
                result = true;
501
            }
502
        }
503
        return result;
504
    }
505

    
506
    /**
507
     * Returns <code>true</code> if the given String is blank.
508
     * @param str the String to check
509
     * @see StringUtils#isBlank(String)
510
     * @return <code>true</code> if str is blank, <code>false</code> otherwise
511
     */
512
    protected static boolean isBlank(String str) {
513
        return StringUtils.isBlank(str);
514
    }
515

    
516
    /**
517
     * Returns <code>true</code> if the given String is not blank.
518
     * @param str the String to check
519
     * @see StringUtils#isNotBlank(String)
520
     * @return <code>true</code> if str is not blank, <code>false</code> otherwise
521
     */
522
    protected static boolean isNotBlank(String str) {
523
        return StringUtils.isNotBlank(str);
524
    }
525

    
526
// **************** EMPTY ************************/
527

    
528
    /**
529
     * Checks if the entity is completely empty
530
     * and therefore can be removed.<BR>
531
     *
532
     * To be implemented by subclasses if used
533
     *
534
     * @return <code>true</code> if empty
535
     */
536
    protected boolean checkEmpty(){
537
        //nothing to check; id, uuid, created and createdBy are not relevant
538
        return true;
539
    }
540

    
541
//********************** CLONE *****************************************/
542

    
543
//    protected void clone(CdmBase clone){
544
//        clone.setCreatedBy(createdBy);
545
//        clone.setId(id);
546
//        clone.propertyChangeSupport=new PropertyChangeSupport(clone);
547
//        //Constructor Attributes
548
//        //clone.setCreated(created);
549
//        //clone.setUuid(getUuid());
550
//
551
//    }
552

    
553
    @Override
554
    public CdmBase clone() throws CloneNotSupportedException{
555
        CdmBase result = (CdmBase)super.clone();
556
        result.propertyChangeSupport=new PropertyChangeSupport(result);
557

    
558
        //TODO ?
559
        result.setId(0);
560
        result.setUuid(UUID.randomUUID());
561
        result.setCreated(new DateTime());
562
        result.setCreatedBy(null);
563

    
564
        //no changes to: -
565
        return result;
566
    }
567

    
568
}
(5-5/56)