rsanchez
2017-03-24 4f5711b8ec555ab8307516ce178b454445d3833f
#3535 - Apply metadata changes in cascade
2 files added
11 files modified
changed files
securis/src/main/java/net/curisit/securis/db/Application.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/ApplicationMetadata.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/LicenseType.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/LicenseTypeMetadata.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/Pack.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/PackMetadata.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/common/Metadata.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/ApplicationResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/BasicServices.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/LicenseTypeResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/PackResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/UserResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/helpers/MetadataHelper.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/Application.java
....@@ -64,7 +64,7 @@
6464 @OneToMany(fetch = FetchType.LAZY, mappedBy = "application")
6565 private Set<LicenseType> licenseTypes;
6666
67
- @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "application")
67
+ @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.REFRESH }, mappedBy = "application")
6868 @JsonManagedReference
6969 private Set<ApplicationMetadata> metadata;
7070
....@@ -110,20 +110,6 @@
110110 this.metadata = metadata;
111111 }
112112
113
- @Override
114
- public boolean equals(Object obj) {
115
- if (!(obj instanceof Application))
116
- return false;
117
- Application other = (Application) obj;
118
- return id.equals(other.id);
119
- }
120
-
121
- @Override
122
- public int hashCode() {
123
-
124
- return (id == null ? 0 : id.hashCode());
125
- }
126
-
127113 public String getLicenseFilename() {
128114 return licenseFilename;
129115 }
....@@ -148,4 +134,19 @@
148134 public void setCode(String code) {
149135 this.code = code;
150136 }
137
+
138
+ @Override
139
+ public boolean equals(Object obj) {
140
+ if (!(obj instanceof Application))
141
+ return false;
142
+ Application other = (Application) obj;
143
+ return id.equals(other.id);
144
+ }
145
+
146
+ @Override
147
+ public int hashCode() {
148
+
149
+ return (id == null ? 0 : id.hashCode());
150
+ }
151
+
151152 }
securis/src/main/java/net/curisit/securis/db/ApplicationMetadata.java
....@@ -2,6 +2,7 @@
22
33 import java.io.Serializable;
44 import java.util.Date;
5
+import java.util.Objects;
56
67 import javax.persistence.Column;
78 import javax.persistence.Entity;
....@@ -22,6 +23,8 @@
2223 import com.fasterxml.jackson.annotation.JsonInclude.Include;
2324 import com.fasterxml.jackson.annotation.JsonProperty;
2425
26
+import net.curisit.securis.db.common.Metadata;
27
+
2528 /**
2629 * Entity implementation class for Entity: application_metadata
2730 *
....@@ -32,7 +35,7 @@
3235 @Table(name = "application_metadata")
3336 @JsonIgnoreProperties(ignoreUnknown = true)
3437 @NamedQueries({ @NamedQuery(name = "list-application-metadata", query = "SELECT a FROM ApplicationMetadata a where a.application.id = :applicationId") })
35
-public class ApplicationMetadata implements Serializable {
38
+public class ApplicationMetadata implements Serializable, Metadata {
3639
3740 private static final Logger LOG = LogManager.getLogger(ApplicationMetadata.class);
3841
....@@ -100,7 +103,20 @@
100103 @Override
101104 public String toString() {
102105
103
- return String.format("ApplicationMetadata (%s)", this.key);
106
+ return String.format("AppMd (%s: %s)", this.key, value);
107
+ }
108
+
109
+ @Override
110
+ public boolean equals(Object obj) {
111
+ if (!(obj instanceof ApplicationMetadata))
112
+ return false;
113
+ ApplicationMetadata other = (ApplicationMetadata) obj;
114
+ return Objects.equals(key, other.key) && Objects.equals(application, other.application);
115
+ }
116
+
117
+ @Override
118
+ public int hashCode() {
119
+ return Objects.hash(key, application);
104120 }
105121
106122 }
securis/src/main/java/net/curisit/securis/db/LicenseType.java
....@@ -62,7 +62,7 @@
6262 @JoinColumn(name = "application_id")
6363 private Application application;
6464
65
- @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "licenseType")
65
+ @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.REFRESH }, mappedBy = "licenseType")
6666 @JsonManagedReference
6767 private Set<LicenseTypeMetadata> metadata;
6868
....@@ -152,7 +152,11 @@
152152
153153 @Override
154154 public int hashCode() {
155
-
156155 return (id == null ? 0 : id.hashCode());
157156 }
157
+
158
+ @Override
159
+ public String toString() {
160
+ return String.format("LT: ID: %d, code: %s", id, code);
161
+ }
158162 }
securis/src/main/java/net/curisit/securis/db/LicenseTypeMetadata.java
....@@ -1,6 +1,7 @@
11 package net.curisit.securis.db;
22
33 import java.io.Serializable;
4
+import java.util.Objects;
45
56 import javax.persistence.Column;
67 import javax.persistence.Entity;
....@@ -17,6 +18,8 @@
1718 import com.fasterxml.jackson.annotation.JsonInclude;
1819 import com.fasterxml.jackson.annotation.JsonInclude.Include;
1920
21
+import net.curisit.securis.db.common.Metadata;
22
+
2023 /**
2124 * Entity implementation class for Entity: licensetype_metadata
2225 *
....@@ -27,7 +30,7 @@
2730 @Table(name = "licensetype_metadata")
2831 @JsonIgnoreProperties(ignoreUnknown = true)
2932 @NamedQueries({ @NamedQuery(name = "list-licensetype-metadata", query = "SELECT a FROM LicenseTypeMetadata a where a.licenseType.id = :licenseTypeId") })
30
-public class LicenseTypeMetadata implements Serializable {
33
+public class LicenseTypeMetadata implements Serializable, Metadata {
3134
3235 private static final long serialVersionUID = 1L;
3336
....@@ -76,4 +79,22 @@
7679 public void setMandatory(boolean mandatory) {
7780 this.mandatory = mandatory;
7881 }
82
+
83
+ @Override
84
+ public boolean equals(Object obj) {
85
+ if (!(obj instanceof LicenseTypeMetadata))
86
+ return false;
87
+ LicenseTypeMetadata other = (LicenseTypeMetadata) obj;
88
+ return Objects.equals(key, other.key) && Objects.equals(licenseType, other.licenseType);
89
+ }
90
+
91
+ @Override
92
+ public int hashCode() {
93
+ return Objects.hash(key, licenseType);
94
+ }
95
+
96
+ @Override
97
+ public String toString() {
98
+ return String.format("LTMD (%s: %s)", key, value);
99
+ }
79100 }
securis/src/main/java/net/curisit/securis/db/Pack.java
....@@ -20,8 +20,6 @@
2020 import javax.persistence.OneToMany;
2121 import javax.persistence.Table;
2222
23
-import net.curisit.integrity.commons.Utils;
24
-
2523 import org.hibernate.annotations.Type;
2624
2725 import com.fasterxml.jackson.annotation.JsonAutoDetect;
....@@ -30,6 +28,8 @@
3028 import com.fasterxml.jackson.annotation.JsonInclude;
3129 import com.fasterxml.jackson.annotation.JsonInclude.Include;
3230 import com.fasterxml.jackson.annotation.JsonProperty;
31
+
32
+import net.curisit.integrity.commons.Utils;
3333
3434 /**
3535 * Entity implementation class for Entity: pack
....@@ -40,358 +40,360 @@
4040 @Entity
4141 @Table(name = "pack")
4242 @JsonIgnoreProperties(ignoreUnknown = true)
43
-@NamedQueries({
44
- @NamedQuery(name = "list-packs", query = "SELECT pa FROM Pack pa"),//
45
- @NamedQuery(name = "pack-by-code", query = "SELECT pa FROM Pack pa where pa.code = :code"),//
46
- @NamedQuery(name = "list-packs-by-orgs", query = "SELECT pa FROM Pack pa where pa.organization.id in :list_ids")
47
-})
43
+@NamedQueries({ @NamedQuery(name = "list-packs", query = "SELECT pa FROM Pack pa"), //
44
+ @NamedQuery(name = "pack-by-code", query = "SELECT pa FROM Pack pa where pa.code = :code"), //
45
+ @NamedQuery(name = "list-packs-by-lic-type", query = "SELECT pa FROM Pack pa where pa.licenseType.id = :lt_id"), //
46
+ @NamedQuery(name = "list-packs-by-orgs", query = "SELECT pa FROM Pack pa where pa.organization.id in :list_ids") })
4847 public class Pack implements Serializable {
4948
50
- private static final long serialVersionUID = 1L;
49
+ private static final long serialVersionUID = 1L;
5150
52
- @Id
53
- @GeneratedValue
54
- private Integer id;
51
+ @Id
52
+ @GeneratedValue
53
+ private Integer id;
5554
56
- private String code;
55
+ private String code;
5756
58
- private String comments;
57
+ private String comments;
5958
60
- @Column(name = "creation_timestamp")
61
- @JsonProperty("creation_timestamp")
62
- private Date creationTimestamp;
59
+ @Column(name = "creation_timestamp")
60
+ @JsonProperty("creation_timestamp")
61
+ private Date creationTimestamp;
6362
64
- @JsonIgnore
65
- @ManyToOne
66
- @JoinColumn(name = "organization_id")
67
- private Organization organization;
63
+ @JsonIgnore
64
+ @ManyToOne
65
+ @JoinColumn(name = "organization_id")
66
+ private Organization organization;
6867
69
- @JsonIgnore
70
- @ManyToOne
71
- @JoinColumn(name = "license_type_id")
72
- private LicenseType licenseType;
68
+ @JsonIgnore
69
+ @ManyToOne
70
+ @JoinColumn(name = "license_type_id")
71
+ private LicenseType licenseType;
7372
74
- @JsonIgnore
75
- @ManyToOne
76
- @JoinColumn(name = "created_by")
77
- private User createdBy;
73
+ @JsonIgnore
74
+ @ManyToOne
75
+ @JoinColumn(name = "created_by")
76
+ private User createdBy;
7877
79
- @JsonIgnore
80
- @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "pack")
81
- private Set<License> licenses;
78
+ @JsonIgnore
79
+ @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.REFRESH }, mappedBy = "pack")
80
+ private Set<License> licenses;
8281
83
- @Column(name = "num_licenses")
84
- @JsonProperty("num_licenses")
85
- private int numLicenses;
82
+ @Column(name = "num_licenses")
83
+ @JsonProperty("num_licenses")
84
+ private int numLicenses;
8685
87
- @Column(name = "init_valid_date")
88
- @JsonProperty("init_valid_date")
89
- private Date initValidDate;
86
+ @Column(name = "init_valid_date")
87
+ @JsonProperty("init_valid_date")
88
+ private Date initValidDate;
9089
91
- @Column(name = "end_valid_date")
92
- @JsonProperty("end_valid_date")
93
- private Date endValidDate;
90
+ @Column(name = "end_valid_date")
91
+ @JsonProperty("end_valid_date")
92
+ private Date endValidDate;
9493
95
- @Type(type = "net.curisit.securis.db.common.PackStatusType")
96
- private PackStatus status;
94
+ @Type(type = "net.curisit.securis.db.common.PackStatusType")
95
+ private PackStatus status;
9796
98
- @Column(name = "license_preactivation")
99
- @JsonProperty("license_preactivation")
100
- private boolean licensePreactivation;
97
+ @Column(name = "license_preactivation")
98
+ @JsonProperty("license_preactivation")
99
+ private boolean licensePreactivation;
101100
102
- @Column(name = "preactivation_valid_period")
103
- @JsonProperty("preactivation_valid_period")
104
- private Integer preactivationValidPeriod;
101
+ @Column(name = "preactivation_valid_period")
102
+ @JsonProperty("preactivation_valid_period")
103
+ private Integer preactivationValidPeriod;
105104
106
- @Column(name = "renew_valid_period")
107
- @JsonProperty("renew_valid_period")
108
- private Integer renewValidPeriod;
105
+ @Column(name = "renew_valid_period")
106
+ @JsonProperty("renew_valid_period")
107
+ private Integer renewValidPeriod;
109108
110
- @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "pack")
111
- private Set<PackMetadata> metadata;
109
+ @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.REFRESH }, mappedBy = "pack")
110
+ private Set<PackMetadata> metadata;
112111
113
- public Integer getId() {
114
- return id;
115
- }
112
+ public Integer getId() {
113
+ return id;
114
+ }
116115
117
- public void setId(Integer id) {
118
- this.id = id;
119
- }
116
+ public void setId(Integer id) {
117
+ this.id = id;
118
+ }
120119
121
- public String getCode() {
122
- return code;
123
- }
120
+ public String getCode() {
121
+ return code;
122
+ }
124123
125
- public void setCode(String code) {
126
- this.code = code;
127
- }
124
+ public void setCode(String code) {
125
+ this.code = code;
126
+ }
128127
129
- public Date getCreationTimestamp() {
130
- return creationTimestamp;
131
- }
128
+ public Date getCreationTimestamp() {
129
+ return creationTimestamp;
130
+ }
132131
133
- public void setCreationTimestamp(Date creationTimestamp) {
134
- this.creationTimestamp = creationTimestamp;
135
- }
132
+ public void setCreationTimestamp(Date creationTimestamp) {
133
+ this.creationTimestamp = creationTimestamp;
134
+ }
136135
137
- public Organization getOrganization() {
138
- return organization;
139
- }
136
+ public Organization getOrganization() {
137
+ return organization;
138
+ }
140139
141
- public void setOrganization(Organization organization) {
142
- this.organization = organization;
143
- }
140
+ public void setOrganization(Organization organization) {
141
+ this.organization = organization;
142
+ }
144143
145
- public LicenseType getLicenseType() {
146
- return licenseType;
147
- }
144
+ public LicenseType getLicenseType() {
145
+ return licenseType;
146
+ }
148147
149
- public void setLicenseType(LicenseType licenseType) {
150
- this.licenseType = licenseType;
151
- }
148
+ public void setLicenseType(LicenseType licenseType) {
149
+ this.licenseType = licenseType;
150
+ }
152151
153
- public User getCreatedBy() {
154
- return createdBy;
155
- }
152
+ public User getCreatedBy() {
153
+ return createdBy;
154
+ }
156155
157
- public void setCreatedBy(User createdBy) {
158
- this.createdBy = createdBy;
159
- }
156
+ public void setCreatedBy(User createdBy) {
157
+ this.createdBy = createdBy;
158
+ }
160159
161
- public int getNumLicenses() {
162
- return numLicenses;
163
- }
160
+ public int getNumLicenses() {
161
+ return numLicenses;
162
+ }
164163
165
- public void setNumLicenses(int numLicenses) {
166
- this.numLicenses = numLicenses;
167
- }
164
+ public void setNumLicenses(int numLicenses) {
165
+ this.numLicenses = numLicenses;
166
+ }
168167
169
- @JsonProperty("num_activations")
170
- public int getNumActivations() {
171
- if (licenses == null) {
172
- return 0;
173
- }
174
- int num = 0;
175
- for (License lic : licenses) {
176
- if (lic.getStatus() == LicenseStatus.ACTIVE || lic.getStatus() == LicenseStatus.PRE_ACTIVE) {
177
- num++;
178
- }
179
- }
180
- return num;
181
- }
168
+ @JsonProperty("num_activations")
169
+ public int getNumActivations() {
170
+ if (licenses == null) {
171
+ return 0;
172
+ }
173
+ int num = 0;
174
+ for (License lic : licenses) {
175
+ if (lic.getStatus() == LicenseStatus.ACTIVE || lic.getStatus() == LicenseStatus.PRE_ACTIVE) {
176
+ num++;
177
+ }
178
+ }
179
+ return num;
180
+ }
182181
183
- /**
184
- * Counts all created licenses, It counts active licenses and licenses
185
- * waiting for activation This number will be used to control the max number
186
- * of licenses created. Ignore canceled licenses.
187
- *
188
- * @return
189
- */
190
- @JsonProperty("num_creations")
191
- public int getNumCreations() {
192
- if (licenses == null) {
193
- return 0;
194
- }
195
- int num = 0;
196
- for (License lic : licenses) {
197
- if (lic.getStatus() != LicenseStatus.CANCELLED) {
198
- num++;
199
- }
200
- }
201
- return num;
202
- }
182
+ /**
183
+ * Counts all created licenses, It counts active licenses and licenses
184
+ * waiting for activation This number will be used to control the max number
185
+ * of licenses created. Ignore canceled licenses.
186
+ *
187
+ * @return
188
+ */
189
+ @JsonProperty("num_creations")
190
+ public int getNumCreations() {
191
+ if (licenses == null) {
192
+ return 0;
193
+ }
194
+ int num = 0;
195
+ for (License lic : licenses) {
196
+ if (lic.getStatus() != LicenseStatus.CANCELLED) {
197
+ num++;
198
+ }
199
+ }
200
+ return num;
201
+ }
203202
204
- /**
205
- * Number of available licenses in this pack
206
- *
207
- * @return
208
- */
209
- @JsonProperty("num_available")
210
- public int getNumAvailables() {
211
- return numLicenses - getNumActivations();
212
- }
203
+ /**
204
+ * Number of available licenses in this pack
205
+ *
206
+ * @return
207
+ */
208
+ @JsonProperty("num_available")
209
+ public int getNumAvailables() {
210
+ return numLicenses - getNumActivations();
211
+ }
213212
214
- @JsonProperty("organization_name")
215
- public String getOrgName() {
216
- return organization == null ? null : organization.getName();
217
- }
213
+ @JsonProperty("organization_name")
214
+ public String getOrgName() {
215
+ return organization == null ? null : organization.getName();
216
+ }
218217
219
- @JsonProperty("application_name")
220
- public String getAppName() {
221
- if (licenseType == null) {
222
- return null;
223
- }
224
- Application app = licenseType.getApplication();
225
- return app == null ? null : app.getName();
226
- }
218
+ @JsonProperty("application_name")
219
+ public String getAppName() {
220
+ if (licenseType == null) {
221
+ return null;
222
+ }
223
+ Application app = licenseType.getApplication();
224
+ return app == null ? null : app.getName();
225
+ }
227226
228
- @JsonProperty("organization_id")
229
- public Integer getOrgId() {
230
- return organization == null ? null : organization.getId();
231
- }
227
+ @JsonProperty("organization_id")
228
+ public Integer getOrgId() {
229
+ return organization == null ? null : organization.getId();
230
+ }
232231
233
- @JsonProperty("organization_id")
234
- public void setOrgId(Integer idOrg) {
235
- if (idOrg == null) {
236
- organization = null;
237
- } else {
238
- organization = new Organization();
239
- organization.setId(idOrg);
240
- }
241
- }
232
+ @JsonProperty("organization_id")
233
+ public void setOrgId(Integer idOrg) {
234
+ if (idOrg == null) {
235
+ organization = null;
236
+ } else {
237
+ organization = new Organization();
238
+ organization.setId(idOrg);
239
+ }
240
+ }
242241
243
- @JsonProperty("license_type_id")
244
- public void setLicTypeId(Integer idLT) {
245
- if (idLT == null) {
246
- licenseType = null;
247
- } else {
248
- licenseType = new LicenseType();
249
- licenseType.setId(idLT);
250
- }
251
- }
242
+ @JsonProperty("license_type_id")
243
+ public void setLicTypeId(Integer idLT) {
244
+ if (idLT == null) {
245
+ licenseType = null;
246
+ } else {
247
+ licenseType = new LicenseType();
248
+ licenseType.setId(idLT);
249
+ }
250
+ }
252251
253
- @JsonProperty("license_type_id")
254
- public Integer getLicTypeId() {
255
- return licenseType == null ? null : licenseType.getId();
256
- }
252
+ @JsonProperty("license_type_id")
253
+ public Integer getLicTypeId() {
254
+ return licenseType == null ? null : licenseType.getId();
255
+ }
257256
258
- @JsonProperty("created_by_id")
259
- public String getCreatedById() {
260
- return createdBy == null ? null : createdBy.getUsername();
261
- }
257
+ @JsonProperty("created_by_id")
258
+ public String getCreatedById() {
259
+ return createdBy == null ? null : createdBy.getUsername();
260
+ }
262261
263
- @JsonProperty("created_by_id")
264
- public void setCreatedById(String username) {
265
- createdBy = new User();
266
- createdBy.setUsername(username);
267
- }
262
+ @JsonProperty("created_by_id")
263
+ public void setCreatedById(String username) {
264
+ createdBy = new User();
265
+ createdBy.setUsername(username);
266
+ }
268267
269
- @JsonProperty("created_by_name")
270
- public String getCreatedByname() {
271
- return createdBy == null ? null : String.format("%s %s (%s)", createdBy.getFirstName(),
272
- createdBy.getLastName() != null ? createdBy.getLastName() : "", createdBy.getUsername());
273
- }
268
+ @JsonProperty("created_by_name")
269
+ public String getCreatedByname() {
270
+ return createdBy == null ? null
271
+ : String.format("%s %s (%s)", createdBy.getFirstName(), createdBy.getLastName() != null ? createdBy.getLastName() : "", createdBy.getUsername());
272
+ }
274273
275
- @JsonProperty("licensetype_code")
276
- public String getLicenseTypeCode() {
277
- return licenseType == null ? null : licenseType.getCode();
278
- }
274
+ @JsonProperty("licensetype_code")
275
+ public String getLicenseTypeCode() {
276
+ return licenseType == null ? null : licenseType.getCode();
277
+ }
279278
280
- public String getComments() {
281
- return comments;
282
- }
279
+ public String getComments() {
280
+ return comments;
281
+ }
283282
284
- public void setComments(String comments) {
285
- this.comments = comments;
286
- }
283
+ public void setComments(String comments) {
284
+ this.comments = comments;
285
+ }
287286
288
- public boolean isLicensePreactivation() {
289
- return licensePreactivation;
290
- }
287
+ public boolean isLicensePreactivation() {
288
+ return licensePreactivation;
289
+ }
291290
292
- public void setLicensePreactivation(boolean licensePreactivation) {
293
- this.licensePreactivation = licensePreactivation;
294
- }
291
+ public void setLicensePreactivation(boolean licensePreactivation) {
292
+ this.licensePreactivation = licensePreactivation;
293
+ }
295294
296
- public Set<PackMetadata> getMetadata() {
297
- return metadata;
298
- }
295
+ public Set<PackMetadata> getMetadata() {
296
+ return metadata;
297
+ }
299298
300
- public void setMetadata(Set<PackMetadata> metadata) {
301
- this.metadata = metadata;
302
- }
299
+ public void setMetadata(Set<PackMetadata> metadata) {
300
+ this.metadata = metadata;
301
+ }
303302
304
- public PackStatus getStatus() {
305
- return status;
306
- }
303
+ public PackStatus getStatus() {
304
+ return status;
305
+ }
307306
308
- public void setStatus(PackStatus status) {
309
- this.status = status;
310
- }
307
+ public void setStatus(PackStatus status) {
308
+ this.status = status;
309
+ }
311310
312
- public Date getInitValidDate() {
313
- return initValidDate;
314
- }
311
+ public Date getInitValidDate() {
312
+ return initValidDate;
313
+ }
315314
316
- public void setInitValidDate(Date initValidDate) {
317
- this.initValidDate = initValidDate;
318
- }
315
+ public void setInitValidDate(Date initValidDate) {
316
+ this.initValidDate = initValidDate;
317
+ }
319318
320
- public Date getEndValidDate() {
321
- return endValidDate;
322
- }
319
+ public Date getEndValidDate() {
320
+ return endValidDate;
321
+ }
323322
324
- public void setEndValidDate(Date endValidDate) {
325
- this.endValidDate = endValidDate;
326
- }
323
+ public void setEndValidDate(Date endValidDate) {
324
+ this.endValidDate = endValidDate;
325
+ }
327326
328
- public Set<License> getLicenses() {
329
- return licenses;
330
- }
327
+ public Set<License> getLicenses() {
328
+ return licenses;
329
+ }
331330
332
- public void setLicenses(Set<License> licenses) {
333
- this.licenses = licenses;
334
- }
331
+ public void setLicenses(Set<License> licenses) {
332
+ this.licenses = licenses;
333
+ }
335334
336
- @Override
337
- public boolean equals(Object obj) {
338
- if (!(obj instanceof Pack))
339
- return false;
340
- Pack other = (Pack) obj;
341
- return id.equals(other.id);
342
- }
335
+ public Integer getPreactivationValidPeriod() {
336
+ return preactivationValidPeriod;
337
+ }
343338
344
- @Override
345
- public int hashCode() {
339
+ public void setPreactivationValidPeriod(Integer preactivationValidPeriod) {
340
+ this.preactivationValidPeriod = preactivationValidPeriod;
341
+ }
346342
347
- return (id == null ? 0 : id.hashCode());
348
- }
343
+ public Integer getRenewValidPeriod() {
344
+ return renewValidPeriod;
345
+ }
349346
350
- public Integer getPreactivationValidPeriod() {
351
- return preactivationValidPeriod;
352
- }
347
+ public void setRenewValidPeriod(Integer renewValidPeriod) {
348
+ this.renewValidPeriod = renewValidPeriod;
349
+ }
353350
354
- public void setPreactivationValidPeriod(Integer preactivationValidPeriod) {
355
- this.preactivationValidPeriod = preactivationValidPeriod;
356
- }
351
+ @Override
352
+ public boolean equals(Object obj) {
353
+ if (!(obj instanceof Application))
354
+ return false;
355
+ return id.equals(Pack.class.cast(obj).id);
356
+ }
357357
358
- public Integer getRenewValidPeriod() {
359
- return renewValidPeriod;
360
- }
358
+ @Override
359
+ public int hashCode() {
360
+ return (id == null ? 0 : id.hashCode());
361
+ }
361362
362
- public void setRenewValidPeriod(Integer renewValidPeriod) {
363
- this.renewValidPeriod = renewValidPeriod;
364
- }
363
+ @Override
364
+ public String toString() {
365
+ return String.format("Pack: ID: %d, code: %s", id, code);
366
+ }
365367
366
- public static class Action {
367
- public static final int CREATE = 1;
368
- public static final int ACTIVATION = 2;
369
- public static final int PUT_ONHOLD = 3;
370
- public static final int CANCEL = 4;
371
- public static final int DELETE = 5;
372
- }
368
+ public static class Action {
369
+ public static final int CREATE = 1;
370
+ public static final int ACTIVATION = 2;
371
+ public static final int PUT_ONHOLD = 3;
372
+ public static final int CANCEL = 4;
373
+ public static final int DELETE = 5;
374
+ }
373375
374
- public static class Status {
376
+ public static class Status {
375377
376
- private static final Map<Integer, List<PackStatus>> transitions = Utils.createMap( //
377
- Action.ACTIVATION, Arrays.asList(PackStatus.CREATED, PackStatus.ON_HOLD, PackStatus.EXPIRED), //
378
- Action.PUT_ONHOLD, Arrays.asList(PackStatus.ACTIVE), //
379
- Action.CANCEL, Arrays.asList(PackStatus.ACTIVE, PackStatus.ON_HOLD, PackStatus.EXPIRED), //
380
- Action.DELETE, Arrays.asList(PackStatus.CANCELLED, PackStatus.CREATED) //
381
- );
378
+ private static final Map<Integer, List<PackStatus>> transitions = Utils.createMap( //
379
+ Action.ACTIVATION, Arrays.asList(PackStatus.CREATED, PackStatus.ON_HOLD, PackStatus.EXPIRED), //
380
+ Action.PUT_ONHOLD, Arrays.asList(PackStatus.ACTIVE), //
381
+ Action.CANCEL, Arrays.asList(PackStatus.ACTIVE, PackStatus.ON_HOLD, PackStatus.EXPIRED), //
382
+ Action.DELETE, Arrays.asList(PackStatus.CANCELLED, PackStatus.CREATED) //
383
+ );
382384
383
- /**
384
- * It checks if a given action is valid for the License, passing the
385
- * action and the current license status
386
- *
387
- * @param oldStatus
388
- * @param newStatus
389
- * @return
390
- */
391
- public static boolean isActionValid(Integer action, PackStatus currentStatus) {
392
- List<PackStatus> validStatuses = transitions.get(action);
385
+ /**
386
+ * It checks if a given action is valid for the License, passing the
387
+ * action and the current license status
388
+ *
389
+ * @param oldStatus
390
+ * @param newStatus
391
+ * @return
392
+ */
393
+ public static boolean isActionValid(Integer action, PackStatus currentStatus) {
394
+ List<PackStatus> validStatuses = transitions.get(action);
393395
394
- return validStatuses != null && validStatuses.contains(currentStatus);
395
- }
396
- }
396
+ return validStatuses != null && validStatuses.contains(currentStatus);
397
+ }
398
+ }
397399 }
securis/src/main/java/net/curisit/securis/db/PackMetadata.java
....@@ -1,6 +1,7 @@
11 package net.curisit.securis.db;
22
33 import java.io.Serializable;
4
+import java.util.Objects;
45
56 import javax.persistence.Column;
67 import javax.persistence.Entity;
....@@ -18,6 +19,8 @@
1819 import com.fasterxml.jackson.annotation.JsonInclude.Include;
1920 import com.fasterxml.jackson.annotation.JsonProperty;
2021
22
+import net.curisit.securis.db.common.Metadata;
23
+
2124 /**
2225 * Entity implementation class for Entity: pack_metadata
2326 *
....@@ -28,7 +31,7 @@
2831 @Table(name = "pack_metadata")
2932 @JsonIgnoreProperties(ignoreUnknown = true)
3033 @NamedQueries({ @NamedQuery(name = "list-pack-metadata", query = "SELECT a FROM PackMetadata a where a.pack.id = :packId") })
31
-public class PackMetadata implements Serializable {
34
+public class PackMetadata implements Serializable, Metadata {
3235
3336 private static final long serialVersionUID = 1L;
3437
....@@ -103,4 +106,22 @@
103106 this.mandatory = mandatory;
104107 }
105108
109
+ @Override
110
+ public String toString() {
111
+ return String.format("PackMD (%s: %s)", key, value);
112
+ }
113
+
114
+ @Override
115
+ public boolean equals(Object obj) {
116
+ if (!(obj instanceof PackMetadata))
117
+ return false;
118
+ PackMetadata other = (PackMetadata) obj;
119
+ return Objects.equals(key, other.key) && Objects.equals(pack, other.pack);
120
+ }
121
+
122
+ @Override
123
+ public int hashCode() {
124
+ return Objects.hash(key, pack);
125
+ }
126
+
106127 }
securis/src/main/java/net/curisit/securis/db/common/Metadata.java
....@@ -0,0 +1,16 @@
1
+package net.curisit.securis.db.common;
2
+
3
+public interface Metadata {
4
+ public String getKey();
5
+
6
+ public void setKey(String key);
7
+
8
+ public String getValue();
9
+
10
+ public void setValue(String value);
11
+
12
+ public boolean isMandatory();
13
+
14
+ public void setMandatory(boolean mandatory);
15
+
16
+}
securis/src/main/java/net/curisit/securis/services/ApplicationResource.java
....@@ -25,6 +25,9 @@
2525 import javax.ws.rs.core.Response;
2626 import javax.ws.rs.core.Response.Status;
2727
28
+import org.apache.logging.log4j.LogManager;
29
+import org.apache.logging.log4j.Logger;
30
+
2831 import net.curisit.integrity.commons.Utils;
2932 import net.curisit.securis.DefaultExceptionHandler;
3033 import net.curisit.securis.db.Application;
....@@ -34,10 +37,8 @@
3437 import net.curisit.securis.security.Securable;
3538 import net.curisit.securis.services.exception.SeCurisServiceException;
3639 import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
40
+import net.curisit.securis.services.helpers.MetadataHelper;
3741 import net.curisit.securis.utils.TokenHelper;
38
-
39
-import org.apache.logging.log4j.LogManager;
40
-import org.apache.logging.log4j.Logger;
4142
4243 /**
4344 * Application resource, this service will provide methods to create, modify and
....@@ -48,191 +49,185 @@
4849 @Path("/application")
4950 public class ApplicationResource {
5051
51
- @Inject
52
- TokenHelper tokenHelper;
52
+ @Inject
53
+ TokenHelper tokenHelper;
5354
54
- @Context
55
- EntityManager em;
55
+ @Inject
56
+ MetadataHelper metadataHelper;
5657
57
- private static final Logger LOG = LogManager.getLogger(ApplicationResource.class);
58
+ @Context
59
+ EntityManager em;
5860
59
- public ApplicationResource() {
60
- }
61
+ private static final Logger LOG = LogManager.getLogger(ApplicationResource.class);
6162
62
- /**
63
- *
64
- * @return the server version in format majorVersion.minorVersion
65
- */
66
- @GET
67
- @Path("/")
68
- @Produces({
69
- MediaType.APPLICATION_JSON
70
- })
71
- @Securable
72
- public Response index() {
73
- LOG.info("Getting applications list ");
63
+ public ApplicationResource() {
64
+ }
7465
75
- // EntityManager em = emProvider.get();
76
- em.clear();
77
- TypedQuery<Application> q = em.createNamedQuery("list-applications", Application.class);
78
- List<Application> list = q.getResultList();
66
+ /**
67
+ *
68
+ * @return the server version in format majorVersion.minorVersion
69
+ */
70
+ @GET
71
+ @Path("/")
72
+ @Produces({ MediaType.APPLICATION_JSON })
73
+ @Securable
74
+ public Response index() {
75
+ LOG.info("Getting applications list ");
7976
80
- return Response.ok(list).build();
81
- }
77
+ // EntityManager em = emProvider.get();
78
+ em.clear();
79
+ TypedQuery<Application> q = em.createNamedQuery("list-applications", Application.class);
80
+ List<Application> list = q.getResultList();
8281
83
- /**
84
- *
85
- * @return the server version in format majorVersion.minorVersion
86
- * @throws SeCurisServiceException
87
- */
88
- @GET
89
- @Path("/{appid}")
90
- @Produces({
91
- MediaType.APPLICATION_JSON
92
- })
93
- @Securable
94
- public Response get(@PathParam("appid") String appid) throws SeCurisServiceException {
95
- LOG.info("Getting application data for id: {}: ", appid);
96
- if (appid == null || "".equals(appid)) {
97
- LOG.error("Application ID is mandatory");
98
- return Response.status(Status.NOT_FOUND).build();
99
- }
82
+ return Response.ok(list).build();
83
+ }
10084
101
- em.clear();
85
+ /**
86
+ *
87
+ * @return the server version in format majorVersion.minorVersion
88
+ * @throws SeCurisServiceException
89
+ */
90
+ @GET
91
+ @Path("/{appid}")
92
+ @Produces({ MediaType.APPLICATION_JSON })
93
+ @Securable
94
+ public Response get(@PathParam("appid") String appid) throws SeCurisServiceException {
95
+ LOG.info("Getting application data for id: {}: ", appid);
96
+ if (appid == null || "".equals(appid)) {
97
+ LOG.error("Application ID is mandatory");
98
+ return Response.status(Status.NOT_FOUND).build();
99
+ }
102100
103
- Application app = null;
104
- try {
105
- LOG.info("READY to GET app: {}", appid);
106
- app = em.find(Application.class, Integer.parseInt(appid));
107
- } catch (Exception e) {
108
- LOG.info("ERROR GETTING app: {}", e);
109
- }
110
- if (app == null) {
111
- LOG.error("Application with id {} not found in DB", appid);
112
- throw new SeCurisServiceException(ErrorCodes.NOT_FOUND, "Application not found with ID: " + appid);
113
- }
101
+ em.clear();
114102
115
- return Response.ok(app).build();
116
- }
103
+ Application app = null;
104
+ try {
105
+ LOG.info("READY to GET app: {}", appid);
106
+ app = em.find(Application.class, Integer.parseInt(appid));
107
+ } catch (Exception e) {
108
+ LOG.info("ERROR GETTING app: {}", e);
109
+ }
110
+ if (app == null) {
111
+ LOG.error("Application with id {} not found in DB", appid);
112
+ throw new SeCurisServiceException(ErrorCodes.NOT_FOUND, "Application not found with ID: " + appid);
113
+ }
117114
118
- @POST
119
- @Path("/")
120
- @Consumes(MediaType.APPLICATION_JSON)
121
- @Produces({
122
- MediaType.APPLICATION_JSON
123
- })
124
- @EnsureTransaction
125
- @Securable
126
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
127
- public Response create(Application app, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
128
- LOG.info("Creating new application");
129
- // EntityManager em = emProvider.get();
130
- app.setCreationTimestamp(new Date());
131
- em.persist(app);
115
+ return Response.ok(app).build();
116
+ }
132117
133
- if (app.getApplicationMetadata() != null) {
134
- for (ApplicationMetadata md : app.getApplicationMetadata()) {
135
- md.setApplication(app);
136
- md.setCreationTimestamp(new Date());
137
- em.persist(md);
138
- }
139
- }
140
- LOG.info("Creating application ({}) with date: {}", app.getId(), app.getCreationTimestamp());
118
+ @POST
119
+ @Path("/")
120
+ @Consumes(MediaType.APPLICATION_JSON)
121
+ @Produces({ MediaType.APPLICATION_JSON })
122
+ @EnsureTransaction
123
+ @Securable
124
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
125
+ public Response create(Application app, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
126
+ LOG.info("Creating new application");
127
+ // EntityManager em = emProvider.get();
128
+ app.setCreationTimestamp(new Date());
129
+ em.persist(app);
141130
142
- return Response.ok(app).build();
143
- }
131
+ if (app.getApplicationMetadata() != null) {
132
+ for (ApplicationMetadata md : app.getApplicationMetadata()) {
133
+ md.setApplication(app);
134
+ md.setCreationTimestamp(new Date());
135
+ em.persist(md);
136
+ }
137
+ }
138
+ LOG.info("Creating application ({}) with date: {}", app.getId(), app.getCreationTimestamp());
144139
145
- @PUT
146
- @POST
147
- @Path("/{appid}")
148
- @EnsureTransaction
149
- @Consumes(MediaType.APPLICATION_JSON)
150
- @Produces({
151
- MediaType.APPLICATION_JSON
152
- })
153
- @Securable
154
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
155
- public Response modify(Application app, @PathParam("appid") String appid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
156
- LOG.info("Modifying application with id: {}", appid);
157
- // EntityManager em = emProvider.get();
158
- Application currentapp = em.find(Application.class, Integer.parseInt(appid));
159
- if (currentapp == null) {
160
- LOG.error("Application with id {} not found in DB", appid);
161
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid)
162
- .build();
163
- }
164
- currentapp.setCode(app.getCode());
165
- currentapp.setName(app.getName());
166
- currentapp.setLicenseFilename(app.getLicenseFilename());
167
- currentapp.setDescription(app.getDescription());
140
+ return Response.ok(app).build();
141
+ }
168142
169
- Set<ApplicationMetadata> newMD = app.getApplicationMetadata();
170
- Set<ApplicationMetadata> oldMD = currentapp.getApplicationMetadata();
171
- Map<String, ApplicationMetadata> directOldMD = getMapMD(oldMD);
172
- Map<String, ApplicationMetadata> directNewMD = getMapMD(newMD);
173
- for (ApplicationMetadata currentMd : oldMD) {
174
- if (newMD == null || !directNewMD.containsKey(currentMd.getKey())) {
175
- em.remove(currentMd);
176
- }
177
- }
143
+ @PUT
144
+ @POST
145
+ @Path("/{appid}")
146
+ @EnsureTransaction
147
+ @Consumes(MediaType.APPLICATION_JSON)
148
+ @Produces({ MediaType.APPLICATION_JSON })
149
+ @Securable
150
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
151
+ public Response modify(Application app, @PathParam("appid") String appid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
152
+ LOG.info("Modifying application with id: {}", appid);
153
+ // EntityManager em = emProvider.get();
154
+ Application currentapp = em.find(Application.class, Integer.parseInt(appid));
155
+ if (currentapp == null) {
156
+ LOG.error("Application with id {} not found in DB", appid);
157
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid).build();
158
+ }
159
+ currentapp.setCode(app.getCode());
160
+ currentapp.setName(app.getName());
161
+ currentapp.setLicenseFilename(app.getLicenseFilename());
162
+ currentapp.setDescription(app.getDescription());
178163
179
- if (newMD != null) {
180
- for (ApplicationMetadata md : newMD) {
181
- if (directOldMD.containsKey(md.getKey())) {
182
- ApplicationMetadata amd = directOldMD.get(md.getKey());
183
- amd.setValue(md.getValue());
184
- amd.setMandatory(md.isMandatory());
185
- em.merge(amd);
186
- } else {
187
- md.setApplication(currentapp);
188
- if (md.getCreationTimestamp() == null) {
189
- md.setCreationTimestamp(app.getCreationTimestamp());
190
- }
191
- em.persist(md);
192
- }
193
- }
194
- }
195
- currentapp.setApplicationMetadata(app.getApplicationMetadata());
196
- em.merge(currentapp);
197
- return Response.ok(currentapp).build();
198
- }
164
+ Set<ApplicationMetadata> newMD = app.getApplicationMetadata();
165
+ Set<ApplicationMetadata> oldMD = currentapp.getApplicationMetadata();
166
+ boolean metadataChanges = !metadataHelper.match(newMD, oldMD);
167
+ if (metadataChanges) {
168
+ Map<String, ApplicationMetadata> directOldMD = getMapMD(oldMD);
169
+ Map<String, ApplicationMetadata> directNewMD = getMapMD(newMD);
170
+ for (ApplicationMetadata currentMd : oldMD) {
171
+ if (newMD == null || !directNewMD.containsKey(currentMd.getKey())) {
172
+ em.remove(currentMd);
173
+ }
174
+ }
199175
200
- private Map<String, ApplicationMetadata> getMapMD(Set<ApplicationMetadata> amd) {
201
- Map<String, ApplicationMetadata> map = new HashMap<String, ApplicationMetadata>();
202
- if (amd != null) {
203
- for (ApplicationMetadata applicationMetadata : amd) {
204
- map.put(applicationMetadata.getKey(), applicationMetadata);
205
- }
206
- }
207
- return map;
208
- }
176
+ if (newMD != null) {
177
+ for (ApplicationMetadata md : newMD) {
178
+ if (directOldMD.containsKey(md.getKey())) {
179
+ em.merge(md);
180
+ } else {
181
+ md.setApplication(currentapp);
182
+ if (md.getCreationTimestamp() == null) {
183
+ md.setCreationTimestamp(app.getCreationTimestamp());
184
+ }
185
+ em.persist(md);
186
+ }
187
+ }
188
+ }
189
+ currentapp.setApplicationMetadata(app.getApplicationMetadata());
190
+ }
191
+ em.merge(currentapp);
192
+ if (metadataChanges) {
193
+ metadataHelper.propagateMetadata(em, currentapp);
194
+ }
195
+ return Response.ok(currentapp).build();
196
+ }
209197
210
- @DELETE
211
- @Path("/{appid}")
212
- @EnsureTransaction
213
- @Produces({
214
- MediaType.APPLICATION_JSON
215
- })
216
- @Securable
217
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
218
- public Response delete(@PathParam("appid") String appid, @Context HttpServletRequest request) {
219
- LOG.info("Deleting app with id: {}", appid);
220
- // EntityManager em = emProvider.get();
221
- Application app = em.find(Application.class, Integer.parseInt(appid));
222
- if (app == null) {
223
- LOG.error("Application with id {} can not be deleted, It was not found in DB", appid);
224
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid)
225
- .build();
226
- }
227
- /*
228
- * if (app.getLicenseTypes() != null &&
229
- * !app.getLicenseTypes().isEmpty()) { throw new
230
- * SeCurisServiceException(ErrorCodes.NOT_FOUND,
231
- * "Application can not be deleted becasue has assigned one or more License types, ID: "
232
- * + appid); }
233
- */
234
- em.remove(app);
235
- return Response.ok(Utils.createMap("success", true, "id", appid)).build();
236
- }
198
+ private Map<String, ApplicationMetadata> getMapMD(Set<ApplicationMetadata> amd) {
199
+ Map<String, ApplicationMetadata> map = new HashMap<String, ApplicationMetadata>();
200
+ if (amd != null) {
201
+ for (ApplicationMetadata applicationMetadata : amd) {
202
+ map.put(applicationMetadata.getKey(), applicationMetadata);
203
+ }
204
+ }
205
+ return map;
206
+ }
207
+
208
+ @DELETE
209
+ @Path("/{appid}")
210
+ @EnsureTransaction
211
+ @Produces({ MediaType.APPLICATION_JSON })
212
+ @Securable
213
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
214
+ public Response delete(@PathParam("appid") String appid, @Context HttpServletRequest request) {
215
+ LOG.info("Deleting app with id: {}", appid);
216
+ // EntityManager em = emProvider.get();
217
+ Application app = em.find(Application.class, Integer.parseInt(appid));
218
+ if (app == null) {
219
+ LOG.error("Application with id {} can not be deleted, It was not found in DB", appid);
220
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid).build();
221
+ }
222
+ /*
223
+ * if (app.getLicenseTypes() != null &&
224
+ * !app.getLicenseTypes().isEmpty()) { throw new
225
+ * SeCurisServiceException(ErrorCodes.NOT_FOUND,
226
+ * "Application can not be deleted becasue has assigned one or more License types, ID: "
227
+ * + appid); }
228
+ */
229
+ em.remove(app);
230
+ return Response.ok(Utils.createMap("success", true, "id", appid)).build();
231
+ }
237232
238233 }
securis/src/main/java/net/curisit/securis/services/BasicServices.java
....@@ -7,8 +7,8 @@
77
88 import javax.enterprise.context.ApplicationScoped;
99 import javax.inject.Inject;
10
+import javax.persistence.EntityManager;
1011 import javax.servlet.http.HttpServletRequest;
11
-import javax.ws.rs.FormParam;
1212 import javax.ws.rs.GET;
1313 import javax.ws.rs.HeaderParam;
1414 import javax.ws.rs.POST;
....@@ -44,6 +44,9 @@
4444 @Inject
4545 TokenHelper tokenHelper;
4646
47
+ @Context
48
+ EntityManager em;
49
+
4750 @Inject
4851 public BasicServices() {
4952 }
....@@ -74,16 +77,6 @@
7477 String page = "/index.jsp";
7578 URI uri = UriBuilder.fromUri(page).build();
7679 return Response.seeOther(uri).build();
77
- }
78
-
79
- @POST
80
- @Path("/login")
81
- @Produces({ MediaType.APPLICATION_JSON })
82
- public Response login(@FormParam("username") String user, @FormParam("password") String password, @Context HttpServletRequest request) {
83
- LOG.info("is user in role: {} == {} ? ", "advance", request.isUserInRole("advance"));
84
-
85
- String tokenAuth = tokenHelper.generateToken(user);
86
- return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();
8780 }
8881
8982 /**
securis/src/main/java/net/curisit/securis/services/LicenseTypeResource.java
....@@ -4,6 +4,7 @@
44 import java.util.HashSet;
55 import java.util.List;
66 import java.util.Set;
7
+import java.util.stream.Collectors;
78
89 import javax.annotation.security.RolesAllowed;
910 import javax.inject.Inject;
....@@ -24,6 +25,9 @@
2425 import javax.ws.rs.core.Response;
2526 import javax.ws.rs.core.Response.Status;
2627
28
+import org.apache.logging.log4j.LogManager;
29
+import org.apache.logging.log4j.Logger;
30
+
2731 import net.curisit.integrity.commons.Utils;
2832 import net.curisit.securis.DefaultExceptionHandler;
2933 import net.curisit.securis.SeCurisException;
....@@ -35,10 +39,8 @@
3539 import net.curisit.securis.security.Securable;
3640 import net.curisit.securis.services.exception.SeCurisServiceException;
3741 import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
42
+import net.curisit.securis.services.helpers.MetadataHelper;
3843 import net.curisit.securis.utils.TokenHelper;
39
-
40
-import org.apache.logging.log4j.LogManager;
41
-import org.apache.logging.log4j.Logger;
4244
4345 /**
4446 * LicenseType resource, this service will provide methods to create, modify and
....@@ -49,206 +51,204 @@
4951 @Path("/licensetype")
5052 public class LicenseTypeResource {
5153
52
- private static final Logger LOG = LogManager.getLogger(LicenseTypeResource.class);
54
+ private static final Logger LOG = LogManager.getLogger(LicenseTypeResource.class);
5355
54
- @Inject
55
- TokenHelper tokenHelper;
56
+ @Inject
57
+ TokenHelper tokenHelper;
5658
57
- @Context
58
- EntityManager em;
59
+ @Inject
60
+ MetadataHelper metadataHelper;
5961
60
- public LicenseTypeResource() {
61
- }
62
+ @Context
63
+ EntityManager em;
6264
63
- /**
64
- *
65
- * @return the server version in format majorVersion.minorVersion
66
- */
67
- @GET
68
- @Path("/")
69
- @Produces({
70
- MediaType.APPLICATION_JSON
71
- })
72
- @Securable
73
- public Response index() {
74
- LOG.info("Getting license types list ");
65
+ public LicenseTypeResource() {
66
+ }
7567
76
- // EntityManager em = emProvider.get();
77
- em.clear();
78
- TypedQuery<LicenseType> q = em.createNamedQuery("list-license_types", LicenseType.class);
79
- List<LicenseType> list = q.getResultList();
68
+ /**
69
+ *
70
+ * @return the server version in format majorVersion.minorVersion
71
+ */
72
+ @GET
73
+ @Path("/")
74
+ @Produces({ MediaType.APPLICATION_JSON })
75
+ @Securable
76
+ public Response index() {
77
+ LOG.info("Getting license types list ");
8078
81
- return Response.ok(list).build();
82
- }
79
+ // EntityManager em = emProvider.get();
80
+ em.clear();
81
+ TypedQuery<LicenseType> q = em.createNamedQuery("list-license_types", LicenseType.class);
82
+ List<LicenseType> list = q.getResultList();
8383
84
- /**
85
- *
86
- * @return the server version in format majorVersion.minorVersion
87
- * @throws SeCurisServiceException
88
- */
89
- @GET
90
- @Path("/{ltid}")
91
- @Produces({
92
- MediaType.APPLICATION_JSON
93
- })
94
- @Securable
95
- public Response get(@PathParam("ltid") String ltid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) throws SeCurisServiceException {
96
- LOG.info("Getting license type data for id: {}: ", ltid);
97
- if (ltid == null || "".equals(ltid)) {
98
- LOG.error("LicenseType ID is mandatory");
99
- return Response.status(Status.NOT_FOUND).build();
100
- }
84
+ return Response.ok(list).build();
85
+ }
10186
102
- // EntityManager em = emProvider.get();
103
- em.clear();
104
- LicenseType lt = em.find(LicenseType.class, Integer.parseInt(ltid));
105
- if (lt == null) {
106
- LOG.error("LicenseType with id {} not found in DB", ltid);
107
- throw new SeCurisServiceException(ErrorCodes.NOT_FOUND, "LicenseType was not found in DB");
108
- }
109
- return Response.ok(lt).build();
110
- }
87
+ /**
88
+ *
89
+ * @return the server version in format majorVersion.minorVersion
90
+ * @throws SeCurisServiceException
91
+ */
92
+ @GET
93
+ @Path("/{ltid}")
94
+ @Produces({ MediaType.APPLICATION_JSON })
95
+ @Securable
96
+ public Response get(@PathParam("ltid") String ltid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) throws SeCurisServiceException {
97
+ LOG.info("Getting license type data for id: {}: ", ltid);
98
+ if (ltid == null || "".equals(ltid)) {
99
+ LOG.error("LicenseType ID is mandatory");
100
+ return Response.status(Status.NOT_FOUND).build();
101
+ }
111102
112
- @POST
113
- @Path("/")
114
- @Consumes(MediaType.APPLICATION_JSON)
115
- @Produces({
116
- MediaType.APPLICATION_JSON
117
- })
118
- @EnsureTransaction
119
- @Securable
120
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
121
- public Response create(LicenseType lt, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
122
- LOG.info("Creating new license type");
123
- // EntityManager em = emProvider.get();
103
+ // EntityManager em = emProvider.get();
104
+ em.clear();
105
+ LicenseType lt = em.find(LicenseType.class, Integer.parseInt(ltid));
106
+ if (lt == null) {
107
+ LOG.error("LicenseType with id {} not found in DB", ltid);
108
+ throw new SeCurisServiceException(ErrorCodes.NOT_FOUND, "LicenseType was not found in DB");
109
+ }
110
+ return Response.ok(lt).build();
111
+ }
124112
125
- try {
126
- setApplication(lt, lt.getApplicationId(), em);
127
- } catch (SeCurisException e) {
128
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
129
- }
113
+ @POST
114
+ @Path("/")
115
+ @Consumes(MediaType.APPLICATION_JSON)
116
+ @Produces({ MediaType.APPLICATION_JSON })
117
+ @EnsureTransaction
118
+ @Securable
119
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
120
+ public Response create(LicenseType lt, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
121
+ LOG.info("Creating new license type");
122
+ // EntityManager em = emProvider.get();
130123
131
- if (lt.getApplicationId() == null) {
132
- LOG.error("Application is missing for current license type data");
133
- return Response.status(Status.NOT_FOUND)
134
- .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application is missing for current license type data").build();
135
- }
124
+ try {
125
+ setApplication(lt, lt.getApplicationId(), em);
126
+ } catch (SeCurisException e) {
127
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
128
+ }
136129
137
- lt.setCreationTimestamp(new Date());
138
- em.persist(lt);
139
- Set<LicenseTypeMetadata> newMD = lt.getMetadata();
130
+ if (lt.getApplicationId() == null) {
131
+ LOG.error("Application is missing for current license type data");
132
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application is missing for current license type data").build();
133
+ }
140134
141
- if (newMD != null) {
142
- for (LicenseTypeMetadata md : newMD) {
143
- md.setLicenseType(lt);
144
- em.persist(md);
145
- }
146
- }
147
- lt.setMetadata(newMD);
135
+ lt.setCreationTimestamp(new Date());
136
+ em.persist(lt);
137
+ Set<LicenseTypeMetadata> newMD = lt.getMetadata();
148138
149
- return Response.ok(lt).build();
150
- }
139
+ if (newMD != null) {
140
+ for (LicenseTypeMetadata md : newMD) {
141
+ md.setLicenseType(lt);
142
+ em.persist(md);
143
+ }
144
+ }
145
+ lt.setMetadata(newMD);
151146
152
- private Set<String> getMdKeys(Set<LicenseTypeMetadata> mds) {
153
- Set<String> ids = new HashSet<String>();
154
- if (mds != null) {
155
- for (LicenseTypeMetadata md : mds) {
156
- ids.add(md.getKey());
157
- }
158
- }
159
- return ids;
160
- }
147
+ return Response.ok(lt).build();
148
+ }
161149
162
- @PUT
163
- @POST
164
- @Path("/{ltid}")
165
- @EnsureTransaction
166
- @Consumes(MediaType.APPLICATION_JSON)
167
- @Produces({
168
- MediaType.APPLICATION_JSON
169
- })
170
- @Securable
171
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
172
- public Response modify(LicenseType lt, @PathParam("ltid") String ltid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
173
- LOG.info("Modifying license type with id: {}", ltid);
174
- // EntityManager em = emProvider.get();
175
- LicenseType currentlt = em.find(LicenseType.class, Integer.parseInt(ltid));
176
- if (currentlt == null) {
177
- LOG.error("LicenseType with id {} not found in DB", ltid);
178
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License type not found with ID: " + ltid)
179
- .build();
180
- }
150
+ private Set<String> getMdKeys(Set<LicenseTypeMetadata> mds) {
151
+ Set<String> ids = new HashSet<String>();
152
+ if (mds != null) {
153
+ for (LicenseTypeMetadata md : mds) {
154
+ ids.add(md.getKey());
155
+ }
156
+ }
157
+ return ids;
158
+ }
181159
182
- try {
183
- setApplication(currentlt, lt.getApplicationId(), em);
184
- } catch (SeCurisException e) {
185
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
186
- }
160
+ @PUT
161
+ @POST
162
+ @Path("/{ltid}")
163
+ @EnsureTransaction
164
+ @Consumes(MediaType.APPLICATION_JSON)
165
+ @Produces({ MediaType.APPLICATION_JSON })
166
+ @Securable
167
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
168
+ public Response modify(LicenseType lt, @PathParam("ltid") String ltid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
169
+ LOG.info("Modifying license type with id: {}", ltid);
170
+ // EntityManager em = emProvider.get();
171
+ LicenseType currentlt = em.find(LicenseType.class, Integer.parseInt(ltid));
172
+ if (currentlt == null) {
173
+ LOG.error("LicenseType with id {} not found in DB", ltid);
174
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License type not found with ID: " + ltid).build();
175
+ }
187176
188
- currentlt.setCode(lt.getCode());
189
- currentlt.setName(lt.getName());
190
- currentlt.setDescription(lt.getDescription());
177
+ try {
178
+ setApplication(currentlt, lt.getApplicationId(), em);
179
+ } catch (SeCurisException e) {
180
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
181
+ }
191182
192
- Set<LicenseTypeMetadata> newMD = lt.getMetadata();
193
- Set<String> newMdKeys = getMdKeys(newMD);
194
- for (LicenseTypeMetadata currentMd : currentlt.getMetadata()) {
195
- if (!newMdKeys.contains(currentMd.getKey())) {
196
- em.remove(currentMd);
197
- LOG.info("Removing MD: {}", currentMd);
198
- }
199
- }
183
+ currentlt.setCode(lt.getCode());
184
+ currentlt.setName(lt.getName());
185
+ currentlt.setDescription(lt.getDescription());
200186
201
- if (newMD != null) {
202
- Set<LicenseTypeMetadata> oldMD = currentlt.getMetadata();
203
- Set<String> oldMdKeys = getMdKeys(oldMD);
187
+ Set<LicenseTypeMetadata> newMD = lt.getMetadata();
188
+ Set<LicenseTypeMetadata> oldMD = currentlt.getMetadata();
189
+ boolean metadataChanges = !metadataHelper.match(newMD, oldMD);
190
+ if (metadataChanges) {
191
+ Set<String> newMdKeys = getMdKeys(newMD);
192
+ for (LicenseTypeMetadata currentMd : oldMD) {
193
+ if (!newMdKeys.contains(currentMd.getKey())) {
194
+ em.remove(currentMd);
195
+ LOG.info("Removing MD: {}", currentMd);
196
+ }
197
+ }
204198
205
- for (LicenseTypeMetadata md : newMD) {
206
- if (oldMdKeys.contains(md.getKey())) {
207
- em.merge(md);
208
- } else {
209
- md.setLicenseType(currentlt);
210
- em.persist(md);
211
- }
212
- }
213
- }
214
- currentlt.setMetadata(newMD);
215
- em.merge(currentlt);
199
+ if (newMD != null) {
200
+ Set<String> oldMdKeys = getMdKeys(oldMD);
216201
217
- return Response.ok(currentlt).build();
218
- }
202
+ for (LicenseTypeMetadata md : newMD) {
203
+ if (oldMdKeys.contains(md.getKey())) {
204
+ em.merge(md);
205
+ } else {
206
+ md.setLicenseType(currentlt);
207
+ em.persist(md);
208
+ }
209
+ }
210
+ }
211
+ currentlt.setMetadata(newMD);
212
+ }
213
+ em.merge(currentlt);
214
+ if (metadataChanges) {
215
+ Set<String> keys = newMD.parallelStream().map(md -> md.getKey()).collect(Collectors.toSet());
216
+ metadataHelper.propagateMetadata(em, currentlt, keys);
217
+ }
219218
220
- private void setApplication(LicenseType licType, Integer applicationId, EntityManager em) throws SeCurisException {
221
- Application app = null;
222
- if (applicationId != null) {
223
- app = em.find(Application.class, applicationId);
224
- if (app == null) {
225
- LOG.error("LicenseType application with id {} not found in DB", applicationId);
219
+ return Response.ok(currentlt).build();
220
+ }
226221
227
- throw new SecurityException("License type's app not found with ID: " + applicationId);
228
- }
229
- }
230
- licType.setApplication(app);
231
- }
222
+ private void setApplication(LicenseType licType, Integer applicationId, EntityManager em) throws SeCurisException {
223
+ Application app = null;
224
+ if (applicationId != null) {
225
+ app = em.find(Application.class, applicationId);
226
+ if (app == null) {
227
+ LOG.error("LicenseType application with id {} not found in DB", applicationId);
232228
233
- @DELETE
234
- @Path("/{ltid}")
235
- @EnsureTransaction
236
- @Produces({
237
- MediaType.APPLICATION_JSON
238
- })
239
- @Securable
240
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
241
- public Response delete(@PathParam("ltid") String ltid, @Context HttpServletRequest request) {
242
- LOG.info("Deleting app with id: {}", ltid);
243
- // EntityManager em = emProvider.get();
244
- LicenseType app = em.find(LicenseType.class, Integer.parseInt(ltid));
245
- if (app == null) {
246
- LOG.error("LicenseType with id {} can not be deleted, It was not found in DB", ltid);
247
- return Response.status(Status.NOT_FOUND).build();
248
- }
229
+ throw new SecurityException("License type's app not found with ID: " + applicationId);
230
+ }
231
+ }
232
+ licType.setApplication(app);
233
+ }
249234
250
- em.remove(app);
251
- return Response.ok(Utils.createMap("success", true, "id", ltid)).build();
252
- }
235
+ @DELETE
236
+ @Path("/{ltid}")
237
+ @EnsureTransaction
238
+ @Produces({ MediaType.APPLICATION_JSON })
239
+ @Securable
240
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
241
+ public Response delete(@PathParam("ltid") String ltid, @Context HttpServletRequest request) {
242
+ LOG.info("Deleting app with id: {}", ltid);
243
+ // EntityManager em = emProvider.get();
244
+ LicenseType app = em.find(LicenseType.class, Integer.parseInt(ltid));
245
+ if (app == null) {
246
+ LOG.error("LicenseType with id {} can not be deleted, It was not found in DB", ltid);
247
+ return Response.status(Status.NOT_FOUND).build();
248
+ }
249
+
250
+ em.remove(app);
251
+ return Response.ok(Utils.createMap("success", true, "id", ltid)).build();
252
+ }
253253
254254 }
securis/src/main/java/net/curisit/securis/services/PackResource.java
....@@ -86,10 +86,10 @@
8686 LOG.info("Getting all packs for user: " + bsc.getUserPrincipal());
8787 q = em.createNamedQuery("list-packs", Pack.class);
8888 } else {
89
- q = em.createNamedQuery("list-packs-by-orgs", Pack.class);
9089 if (bsc.getOrganizationsIds() == null) {
91
- Response.ok().build();
90
+ return Response.ok().build();
9291 }
92
+ q = em.createNamedQuery("list-packs-by-orgs", Pack.class);
9393 q.setParameter("list_ids", bsc.getOrganizationsIds());
9494 }
9595
securis/src/main/java/net/curisit/securis/services/UserResource.java
....@@ -264,10 +264,9 @@
264264 em.getTransaction().rollback();
265265 }
266266 clearUserCache(username);
267
-
267
+ String userFullName = String.format("%s %s", user.getFirstName(), user.getLastName() == null ? "" : user.getLastName()).trim();
268268 String tokenAuth = tokenHelper.generateToken(username);
269
- return Response.ok(Utils.createMap("success", true, "token", tokenAuth, "username", username, "full_name", String.format("%s %s", user.getFirstName(), user.getLastName())))
270
- .build();
269
+ return Response.ok(Utils.createMap("success", true, "token", tokenAuth, "username", username, "full_name", userFullName)).build();
271270 }
272271
273272 /**
securis/src/main/java/net/curisit/securis/services/helpers/MetadataHelper.java
....@@ -0,0 +1,155 @@
1
+package net.curisit.securis.services.helpers;
2
+
3
+import java.util.Collection;
4
+import java.util.HashSet;
5
+import java.util.List;
6
+import java.util.Objects;
7
+import java.util.Set;
8
+import java.util.stream.Collectors;
9
+
10
+import javax.enterprise.context.ApplicationScoped;
11
+import javax.persistence.EntityManager;
12
+import javax.persistence.TypedQuery;
13
+
14
+import org.apache.logging.log4j.LogManager;
15
+import org.apache.logging.log4j.Logger;
16
+
17
+import net.curisit.securis.db.Application;
18
+import net.curisit.securis.db.ApplicationMetadata;
19
+import net.curisit.securis.db.LicenseType;
20
+import net.curisit.securis.db.LicenseTypeMetadata;
21
+import net.curisit.securis.db.Pack;
22
+import net.curisit.securis.db.PackMetadata;
23
+import net.curisit.securis.db.common.Metadata;
24
+
25
+@ApplicationScoped
26
+public class MetadataHelper {
27
+
28
+ private static final Logger log = LogManager.getLogger(MetadataHelper.class);
29
+
30
+ public <T extends Metadata> boolean match(T m1, T m2) {
31
+ if (m1 == null || m2 == null) {
32
+ return false;
33
+ }
34
+ return Objects.equals(m1.getKey(), m2.getKey()) && Objects.equals(m1.getValue(), m2.getValue()) && m1.isMandatory() == m2.isMandatory();
35
+ }
36
+
37
+ public <T extends Metadata> Metadata findByKey(String key, Collection<T> listMd) {
38
+ return listMd.parallelStream().filter(m -> Objects.equals(key, m.getKey())).findAny().orElse(null);
39
+ }
40
+
41
+ public <T extends Metadata> boolean match(Set<T> listMd1, Set<T> listMd2) {
42
+ if (listMd1.size() != listMd2.size()) {
43
+ return false;
44
+ }
45
+ return listMd1.parallelStream().allMatch(m -> this.match(m, findByKey(m.getKey(), listMd2)));
46
+ }
47
+
48
+ public <T extends Metadata, K extends Metadata> void mergeMetadata(EntityManager em, Set<T> srcListMd, Set<K> tgtListMd, Set<String> keys) {
49
+
50
+ Set<K> mdToRemove = tgtListMd.parallelStream() //
51
+ .filter(md -> !keys.contains(md.getKey())) //
52
+ .collect(Collectors.toSet());
53
+ for (K tgtMd : mdToRemove) {
54
+ log.info("MD key to remove: {} - {}", tgtMd.getKey(), tgtMd);
55
+ if (tgtMd instanceof LicenseTypeMetadata) {
56
+ log.info("LT: {}, tx: {}, contans: {}", LicenseTypeMetadata.class.cast(tgtMd).getLicenseType(), em.isJoinedToTransaction(), em.contains(tgtMd));
57
+ }
58
+ em.remove(tgtMd);
59
+ }
60
+ Set<K> keysToUpdate = tgtListMd.parallelStream() //
61
+ .filter(md -> keys.contains(md.getKey())) //
62
+ .collect(Collectors.toSet());
63
+ for (K tgtMd : keysToUpdate) {
64
+ Metadata md = this.findByKey(tgtMd.getKey(), srcListMd);
65
+ if (md.isMandatory() != tgtMd.isMandatory() || !Objects.equals(md.getValue(), tgtMd.getValue())) {
66
+ tgtMd.setMandatory(md.isMandatory());
67
+ tgtMd.setValue(md.getValue());
68
+ log.info("MD key to update: {}", tgtMd.getKey());
69
+ em.merge(tgtMd);
70
+ }
71
+ }
72
+ }
73
+
74
+ private Set<LicenseTypeMetadata> createNewMetadata(Set<ApplicationMetadata> appMd, Set<LicenseTypeMetadata> existingMd, LicenseType licenseType) {
75
+ Set<String> oldKeys = existingMd.stream().map(md -> md.getKey()).collect(Collectors.toSet());
76
+ return appMd.parallelStream() //
77
+ .filter(md -> !oldKeys.contains(md.getKey())) //
78
+ .map(appmd -> {
79
+ LicenseTypeMetadata ltmd = new LicenseTypeMetadata();
80
+ ltmd.setLicenseType(licenseType);
81
+ ltmd.setKey(appmd.getKey());
82
+ ltmd.setValue(appmd.getValue());
83
+ ltmd.setMandatory(appmd.isMandatory());
84
+ return ltmd;
85
+ }).collect(Collectors.toSet());
86
+ }
87
+
88
+ private Set<PackMetadata> createNewMetadata(Set<LicenseTypeMetadata> ltMd, Set<PackMetadata> existingMd, Pack pack) {
89
+ Set<String> oldKeys = existingMd.stream().map(md -> md.getKey()).collect(Collectors.toSet());
90
+ return ltMd.parallelStream() //
91
+ .filter(md -> !oldKeys.contains(md.getKey())) //
92
+ .map(md -> {
93
+ PackMetadata pmd = new PackMetadata();
94
+ pmd.setPack(pack);
95
+ pmd.setKey(md.getKey());
96
+ pmd.setValue(md.getValue());
97
+ pmd.setMandatory(md.isMandatory());
98
+ return pmd;
99
+ }).collect(Collectors.toSet());
100
+ }
101
+
102
+ /**
103
+ * Copy the modified app metadata to LicenseTypes and Packs
104
+ *
105
+ * @param em
106
+ * @param app
107
+ */
108
+ public void propagateMetadata(EntityManager em, Application app) {
109
+ Set<ApplicationMetadata> appMd = app.getApplicationMetadata();
110
+ Set<String> keys = appMd.parallelStream().map(md -> md.getKey()).collect(Collectors.toSet());
111
+ log.info("App metadata keys: {}", keys);
112
+ for (LicenseType lt : app.getLicenseTypes()) {
113
+ log.info("Lic type to update: {}", lt.getCode());
114
+ this.mergeMetadata(em, appMd, lt.getMetadata(), keys);
115
+ Set<LicenseTypeMetadata> newMdList = createNewMetadata(appMd, lt.getMetadata(), lt);
116
+ for (LicenseTypeMetadata newMetadata : newMdList) {
117
+ log.info("MD key to add to lt: {}", newMetadata.getKey());
118
+ em.persist(newMetadata);
119
+ }
120
+ em.detach(lt);
121
+ // Probably there is a better way to get the final metadata from JPA...
122
+ TypedQuery<LicenseTypeMetadata> updatedMdQuery = em.createNamedQuery("list-licensetype-metadata", LicenseTypeMetadata.class);
123
+ updatedMdQuery.setParameter("licenseTypeId", lt.getId());
124
+ Set<LicenseTypeMetadata> updatedMd = new HashSet<>(updatedMdQuery.getResultList());
125
+
126
+ lt.setMetadata(updatedMd);
127
+ propagateMetadata(em, lt, keys);
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Copy the modified licenseType metadata to Packs
133
+ *
134
+ * @param em
135
+ * @param lt
136
+ * @param keys
137
+ */
138
+ public void propagateMetadata(EntityManager em, LicenseType lt, Set<String> keys) {
139
+ Set<LicenseTypeMetadata> ltMd = lt.getMetadata();
140
+ TypedQuery<Pack> packsQuery = em.createNamedQuery("list-packs-by-lic-type", Pack.class);
141
+ packsQuery.setParameter("lt_id", lt.getId());
142
+ List<Pack> packs = packsQuery.getResultList();
143
+ log.info("Packs to update the metadata: {}", packs.size());
144
+ for (Pack pack : packs) {
145
+ this.mergeMetadata(em, ltMd, pack.getMetadata(), keys);
146
+ Set<PackMetadata> newMdList = createNewMetadata(ltMd, pack.getMetadata(), pack);
147
+ for (PackMetadata newMetadata : newMdList) {
148
+ log.info("MD key to add to pack: {}", newMetadata.getKey());
149
+ em.persist(newMetadata);
150
+ }
151
+ em.detach(pack);
152
+ }
153
+ }
154
+
155
+}