Joaquín Reñé
2025-10-07 146a0fb8b0e90f9196e569152f649baf60d6cc8f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
/*
* Copyright @ 2013 CurisTEC, S.A.S. All Rights Reserved.
*/
package net.curisit.securis.db;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.EntityManager;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.NoResultException;
import jakarta.persistence.OneToMany;
import jakarta.persistence.Table;
import jakarta.persistence.TypedQuery;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.annotations.Type;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.curisit.integrity.commons.Utils;
import net.curisit.securis.db.common.CreationTimestampEntity;
import net.curisit.securis.db.common.ModificationTimestampEntity;
import net.curisit.securis.db.listeners.CreationTimestampListener;
import net.curisit.securis.db.listeners.ModificationTimestampListener;
import net.curisit.securis.services.exception.SeCurisServiceException;
/**
* License
* <p>
* Main license entity. Contains identity, ownership, timestamps and payload fields.
* Includes convenience JSON properties for related IDs/names.
*
* Mapping details:
* - Table: license
* - Listeners: CreationTimestampListener, ModificationTimestampListener
* - Named queries: license-by-code, license-by-activation-code, last-code-suffix-used-in-pack, ...
* - Status column uses custom Hibernate type: net.curisit.securis.db.common.LicenseStatusType
* @author JRA
* Last reviewed by JRA on Oct 5, 2025.
*/
@JsonAutoDetect
@JsonInclude(Include.NON_NULL)
@Entity
@EntityListeners({ CreationTimestampListener.class, ModificationTimestampListener.class })
@Table(name = "license")
@JsonIgnoreProperties(ignoreUnknown = true)
@NamedQueries({
    @NamedQuery(name = "license-by-code", query = "SELECT l FROM License l where l.code = :code"),
    @NamedQuery(name = "license-by-activation-code", query = "SELECT l FROM License l where l.activationCode = :activationCode"),
    @NamedQuery(name = "last-code-suffix-used-in-pack", query = "SELECT max(l.codeSuffix) FROM License l where l.pack.id = :packId"),
    @NamedQuery(name = "list-licenses-by-pack", query = "SELECT l FROM License l where l.pack.id = :packId"),
    @NamedQuery(name = "list-licenses-by-req-data", query = "SELECT l FROM License l where l.reqDataHash = :hash"),
    @NamedQuery(name = "list-active-licenses-by-req-data", query = "SELECT l FROM License l where l.reqDataHash = :hash and l.status in ('AC', 'PA')"),
    @NamedQuery(name = "list-valid-licenses-by-req-data", query = "SELECT l FROM License l where l.reqDataHash = :hash and l.status in ('RE', 'AC', 'PA')")
})
public class License implements CreationTimestampEntity, ModificationTimestampEntity, Serializable {
    private static final long serialVersionUID = 2700310404904877227L;
    private static final Logger LOG = LogManager.getLogger(License.class);
    // ------------------------------------------------------------------
    // Columns & relations
    // ------------------------------------------------------------------
    @Id
    @GeneratedValue
    private Integer id;
    private String code;
    @Column(name = "metadata_obsolete")
    @JsonProperty("metadata_obsolete")
    private Boolean metadataObsolete;
    @Column(name = "activation_code")
    @JsonProperty("activation_code")
    private String activationCode;
    @Column(name = "code_suffix")
    @JsonProperty("code_suffix")
    private Integer codeSuffix;
    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "pack_id")
    private Pack pack;
    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "created_by")
    private User createdBy;
    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "cancelled_by")
    private User cancelledBy;
    @Type(type = "net.curisit.securis.db.common.LicenseStatusType")
    private LicenseStatus status;
    @Column(name = "full_name")
    @JsonProperty("full_name")
    private String fullName;
    private String email;
    @Column(name = "request_data")
    @JsonProperty("request_data")
    private String requestData;
    /**
    * Request data hash (not serialized). Automatically updated by setRequestData().
    */
    @Column(name = "request_data_hash")
    @JsonIgnore
    private String reqDataHash;
    @Column(name = "license_data")
    @JsonProperty("license_data")
    @JsonIgnore
    // License data is delivered separately (e.g., file download). Not sent in list views.
    private String licenseData;
    @Column(name = "creation_timestamp")
    @JsonProperty("creation_timestamp")
    private Date creationTimestamp;
    @Column(name = "modification_timestamp")
    @JsonProperty("modification_timestamp")
    private Date modificationTimestamp;
    @Column(name = "last_access_timestamp")
    @JsonProperty("last_access_timestamp")
    private Date lastAccessTimestamp;
    @Column(name = "expiration_date")
    @JsonProperty("expiration_date")
    private Date expirationDate;
    private String comments;
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "license")
    @JsonIgnore
    private List<LicenseHistory> history;
    // ------------------------------------------------------------------
    // Basic accessors
    // ------------------------------------------------------------------
    /** 
     * getId<p>
     * Return primary key. 
     * 
     * @return id
     */
    public Integer getId() { return id; }
    /** 
     * getCode<p>
     * Return human-readable license code. 
     * 
     * @return code
     */
    public String getCode() { return code; }
    /** 
     * setCode<p>
     * Set human-readable license code. 
     * 
     * @param code
     */
    public void setCode(String code) { this.code = code; }
    /** 
     * getCreationTimestamp<p>
     * Required by CreationTimestampEntity. 
     * 
     * @return creationTimestamp
     */
    @Override
    public Date getCreationTimestamp() { return creationTimestamp; }
    /** 
     * setCreationTimestamp<p>
     * Set creation timestamp. 
     * 
     * @param creationTimestamp
     */
    @Override
    public void setCreationTimestamp(Date creationTimestamp) { this.creationTimestamp = creationTimestamp; }
    /** 
     * getCreatedBy<p>
     * Return creator user (entity). 
     * 
     * @return user
     */
    public User getCreatedBy() { return createdBy; }
    /** 
     * setCreatedBy<p>
     * Set creator user (entity). 
     * 
     * @param user
     */
    public void setCreatedBy(User createdBy) { this.createdBy = createdBy; }
    /** 
     * getPack<p>
     * Return owning pack. 
     * 
     * @return pack
     */
    public Pack getPack() { return pack; }
    /** 
     * setPack<p>
     * Set owning pack.
     * 
     * @param pack
     */
    public void setPack(Pack pack) { this.pack = pack; }
    /** 
     * getCreatedById<p>
     * Expose creator username as JSON. 
     * 
     * @return username
     */
    @JsonProperty("created_by_id")
    public String getCreatedById() { return createdBy == null ? null : createdBy.getUsername(); }
    /** 
     * setCreatedById<p>
     * Setter by username for JSON binding. 
     * 
     * @param username
     */
    @JsonProperty("created_by_id")
    public void setCreatedById(String username) {
        if (username == null) {
            createdBy = null;
        } else {
            createdBy = new User();
            createdBy.setUsername(username);
        }
    }
    /** 
     * getCancelledById<p>
     * Expose cancelling user username as JSON. 
     * 
     * @return username
     */
    @JsonProperty("cancelled_by_id")
    public String getCancelledById() { return cancelledBy == null ? null : cancelledBy.getUsername(); }
    /** 
     * setCancelledById<p>
     * Setter by username for JSON binding. 
     * 
     * @param username
     */
    @JsonProperty("cancelled_by_id")
    public void setCancelledById(String username) {
        if (username == null) {
            cancelledBy = null;
        } else {
            cancelledBy = new User();
            cancelledBy.setUsername(username);
        }
    }
    /** 
     * getPackCode<p>
     * Expose pack code for convenience. 
     * 
     * @return packCode
     */
    @JsonProperty("pack_code")
    public String getPackCode() { return pack == null ? null : pack.getCode(); }
    /** 
     * getPackId<p>
     * Expose pack id for convenience. 
     * 
     * @return packId
     */
    @JsonProperty("pack_id")
    public Integer getPackId() { return pack == null ? null : pack.getId(); }
    /** 
     * setPackId<p>
     * Setter by id for JSON binding (creates a shallow Pack).
     * 
     * @param packId
     */
    @JsonProperty("pack_id")
    public void setPackId(Integer idPack) {
        if (idPack == null) {
            pack = null;
        } else {
            pack = new Pack();
            pack.setId(idPack);
        }
    }
    /** 
     * getStatus<p>
     * Return license status. 
     * 
     * @return licenseStatus
     */
    public LicenseStatus getStatus() { return status; }
    /** 
     * setStatus<p>
     * Set license status. 
     * 
     * @param status
     */
    public void setStatus(LicenseStatus status) { this.status = status; }
    /** 
     * getModificationTimestamp<p>
     * Required by ModificationTimestampEntity. 
     * 
     * @return modificationTimestamp
     */
    @Override
    public Date getModificationTimestamp() { return modificationTimestamp; }
    /** 
     * setModificationTimestamp<p>
     * Set modification timestamp. 
     * 
     * @param modificationTimestamp
     */
    @Override
    public void setModificationTimestamp(Date modificationTimestamp) { this.modificationTimestamp = modificationTimestamp; }
    /** 
     * getFullName<p>
     * Return license holder full name. 
     * 
     * @return name
     */
    public String getFullName() { return fullName; }
    /** 
     * setFullName<p>
     * Set license holder full name. 
     * 
     * @param name
     */
    public void setFullName(String fullName) { this.fullName = fullName; }
    /** 
     * getEmail<p>
     * Return email address. 
     * 
     * @return email
     */
    public String getEmail() { return email; }
    /** 
     * setEmail<p>
     * Set email address. 
     * 
     * @param email
     */
    public void setEmail(String email) { this.email = email; }
    /** 
     * setId<p>
     * Set primary key (rarely used). 
     * 
     * @param id
     */
    public void setId(Integer id) { this.id = id; }
    /** 
     * getCancelledBy<p>
     * Return cancelling user (entity). 
     * 
     * @param user
     */
    public User getCancelledBy() { return cancelledBy; }
    /** 
     * setCancelledBy<p>
     * Set cancelling user (entity). 
     * 
     * @param cancelledBy
     */
    public void setCancelledBy(User cancelledBy) { this.cancelledBy = cancelledBy; }
    /** 
     * getLastAccessTimestamp<p>
     * Return last access timestamp. 
     * 
     * @return lastAccessTimestamp
     */
    public Date getLastAccessTimestamp() { return lastAccessTimestamp; }
    /** 
     * setLastAccessTimestamp<p>
     * Set last access timestamp. 
     * 
     * @param lastAccessTimestamp
     */
    public void setLastAccessTimestamp(Date lastAccessTimestamp) { this.lastAccessTimestamp = lastAccessTimestamp; }
    /** 
     * getRequestData<p>
     * Return raw request data. 
     * 
     * @return requestData
     */
    public String getRequestData() { return requestData; }
    /**
    * setRequestData<p>
    * Set raw request data and recompute {@link #reqDataHash} immediately using
    * the same hashing strategy as BlockedRequest (SHA-256).
    *
    * @param requestData
    */
    public void setRequestData(String requestData) {
        this.requestData = requestData;
        this.reqDataHash = BlockedRequest.generateHash(this.requestData);
    }
    /** 
     * getLicenseData<p>
     * Return opaque license data (not serialized in lists). 
     * 
     * @return licenseData
     */
    public String getLicenseData() { return licenseData; }
    /** 
     * setLicenseData<p>
     * Set opaque license data (large content kept server-side). 
     * 
     * @param licenseDate
     */
    public void setLicenseData(String licenseData) { this.licenseData = licenseData; }
    /** 
     * getComments<p>
     * Return optional comments. 
     * 
     * @return comments
     */
    public String getComments() { return comments; }
    /** 
     * setComments<p>
     * Set optional comments. 
     * 
     * @param comments
     */
    public void setComments(String comments) { this.comments = comments; }
    /** 
     * getHistory<p>
     * Return change history entries (lazy). 
     * 
     * @return history
     */
    public List<LicenseHistory> getHistory() { return history; }
    /** 
     * setHistory<p>
     * Set change history entries. 
     * 
     * @param history
     */
    public void setHistory(List<LicenseHistory> history) { this.history = history; }
    /** 
     * getExpirationDate<p>
     * Return expiration date (nullable). 
     * 
     * @return expirationDate
     */
    public Date getExpirationDate() { return expirationDate; }
    /** 
     * setExpirationDate<p>
     * Set expiration date (nullable). 
     * 
     * @param expirationDate
     */
    public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; }
    /** 
     * getReqDataHash<p>
     * Return cached hash of request data (not exposed in JSON). 
     * 
     * @return reqDataHash
     */
    public String getReqDataHash() { return reqDataHash; }
    /** 
     * getCodeSuffix<p>
     * Return numeric suffix of the code. 
     * 
     * @return codeSuffix
     */
    public Integer getCodeSuffix() { return codeSuffix; }
    /** 
     * setCodeSuffix<p>
     * Set numeric suffix of the code. 
     * 
     * @param codeSuffix
     */
    public void setCodeSuffix(Integer codeSuffix) { this.codeSuffix = codeSuffix; }
    /** 
     * getActivationCode<p>
     * Return activation code. 
     * 
     * @return activationCode
     */
    public String getActivationCode() { return activationCode; }
    /** 
     * setActivationCode<p>
     * Set activation code. 
     * 
     * @param activationCode
     */
    public void setActivationCode(String activationCode) { this.activationCode = activationCode; }
    /** 
     * isMetadataObsolete<p>
     * Convenience Boolean → primitive with null-safe false. 
     * 
     * @return isMetadataObsolete
     */
    public boolean isMetadataObsolete() { return metadataObsolete != null && metadataObsolete; }
    /** 
     * setMetadataObsolete<p>
     * Set metadata obsolete flag (nullable wrapper). 
     * 
     * @param obsolete
     */
    public void setMetadataObsolete(Boolean obsolete) { this.metadataObsolete = obsolete; }
    // ------------------------------------------------------------------
    // Status transitions helpers
    // ------------------------------------------------------------------
    /**
     * Action<p>
     * Actions to take with the license
     */
    public static class Action {
        public static final int CREATE = 1;
        public static final int REQUEST = 2;
        public static final int ACTIVATION = 3;
        public static final int SEND = 4;
        public static final int DOWNLOAD = 5;
        public static final int CANCEL = 6;
        public static final int DELETE = 7;
        public static final int BLOCK = 8;
        public static final int UNBLOCK = 9;
    }
    /**
     * Status<p>
     * Status of the requested license
     */
    public static class Status {
        private static final Map<Integer, List<LicenseStatus>> transitions = Utils.createMap(
            Action.REQUEST,   Arrays.asList(LicenseStatus.CREATED, LicenseStatus.REQUESTED),
            Action.ACTIVATION,Arrays.asList(LicenseStatus.CREATED, LicenseStatus.REQUESTED, LicenseStatus.PRE_ACTIVE, LicenseStatus.EXPIRED),
            Action.SEND,      Arrays.asList(LicenseStatus.ACTIVE, LicenseStatus.PRE_ACTIVE),
            Action.DOWNLOAD,  Arrays.asList(LicenseStatus.ACTIVE, LicenseStatus.PRE_ACTIVE),
            Action.CANCEL,    Arrays.asList(LicenseStatus.ACTIVE, LicenseStatus.PRE_ACTIVE, LicenseStatus.REQUESTED, LicenseStatus.EXPIRED),
            Action.DELETE,    Arrays.asList(LicenseStatus.CANCELLED, LicenseStatus.CREATED, LicenseStatus.BLOCKED),
            Action.UNBLOCK,   Arrays.asList(LicenseStatus.BLOCKED),
            Action.BLOCK,     Arrays.asList(LicenseStatus.CANCELLED)
        );
        /**
        * isActionValid<p>
        * Check whether an action is valid given the current license status.
        *
        * @param action action constant from {@link Action}
        * @param currentStatus current license status
        * @return true if allowed
        */
        public static boolean isActionValid(Integer action, LicenseStatus currentStatus) {
            List<LicenseStatus> validStatuses = transitions.get(action);
            LOG.info("Action {} is valid ? => {} current: {} OK? {}", action, validStatuses, currentStatus,
                     validStatuses != null && validStatuses.contains(currentStatus));
            return validStatuses != null && validStatuses.contains(currentStatus);
        }
    }
    // ------------------------------------------------------------------
    // Repository helpers (static queries)
    // ------------------------------------------------------------------
    /**
    * findValidLicenseByRequestData<p>
    * Return the first license in statuses RE/AC/PA for the given request data hash.
    *
    * @param requestData raw request data
    * @param em entity manager
    * @return matching license or null
    * @throws SeCurisServiceException
    */
    public static License findValidLicenseByRequestData(String requestData, EntityManager em) throws SeCurisServiceException {
        TypedQuery<License> query = em.createNamedQuery("list-valid-licenses-by-req-data", License.class);
        query.setParameter("hash", BlockedRequest.generateHash(requestData));
        try {
            List<License> list = query.getResultList();
            if (list.size() == 0) return null;
            if (list.size() > 1) {
                LOG.error("There are more than 1 active or requested license for request data: {}\nHash: {}",
                          requestData, BlockedRequest.generateHash(requestData));
            }
            return list.get(0);
        } catch (NoResultException e) {
            return null;
        }
    }
    /**
    * findLicenseByActivationCode<p>
    * Retrieve a license by its activation code.
    * 
    * @param activationCode
    * @param entityManager
    * @return license
    * @throws SeCurisServiceException
    */
    public static License findLicenseByActivationCode(String activationCode, EntityManager em) throws SeCurisServiceException {
        TypedQuery<License> query = em.createNamedQuery("license-by-activation-code", License.class);
        query.setParameter("activationCode", activationCode);
        try {
            return query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }
    /**
    * findActiveLicenseByRequestData<p>
    * Return the first AC/PA license for a given requestData.
    * 
    * @param requestData
    * @param entityManager
    * @return license
    * @throws SeCurisServiceException
    */
    public static License findActiveLicenseByRequestData(String requestData, EntityManager em) throws SeCurisServiceException {
        TypedQuery<License> query = em.createNamedQuery("list-active-licenses-by-req-data", License.class);
        query.setParameter("hash", BlockedRequest.generateHash(requestData));
        try {
            List<License> list = query.getResultList();
            if (list.size() == 0) return null;
            if (list.size() > 1) {
                LOG.error("There are more than 1 active license for request data: {}\nHash: {}",
                          requestData, BlockedRequest.generateHash(requestData));
            }
            return list.get(0);
        } catch (NoResultException e) {
            return null;
        }
    }
    /**
    * findLicenseByCode<p>
    * Retrieve a license by human-readable code.
    * 
    * @param code
    * @param entityManager
    * @return license
    * @throws SeCurisServiceException
    */
    public static License findLicenseByCode(String code, EntityManager em) throws SeCurisServiceException {
        TypedQuery<License> query = em.createNamedQuery("license-by-code", License.class);
        query.setParameter("code", code);
        try {
            return query.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }
}