securis/src/main/java/net/curisit/securis/db/Application.java
.. .. @@ -64,7 +64,7 @@ 64 64 @OneToMany(fetch = FetchType.LAZY, mappedBy = "application") 65 65 private Set<LicenseType> licenseTypes; 66 66 67 - @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "application")67 + @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.REFRESH }, mappedBy = "application")68 68 @JsonManagedReference 69 69 private Set<ApplicationMetadata> metadata; 70 70 .. .. @@ -110,20 +110,6 @@ 110 110 this.metadata = metadata; 111 111 } 112 112 113 - @Override114 - 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 - @Override122 - public int hashCode() {123 -124 - return (id == null ? 0 : id.hashCode());125 - }126 -127 113 public String getLicenseFilename() { 128 114 return licenseFilename; 129 115 } .. .. @@ -148,4 +134,19 @@ 148 134 public void setCode(String code) { 149 135 this.code = code; 150 136 } 137 +138 + @Override139 + 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 + @Override147 + public int hashCode() {148 +149 + return (id == null ? 0 : id.hashCode());150 + }151 +151 152 } securis/src/main/java/net/curisit/securis/db/ApplicationMetadata.java
.. .. @@ -2,6 +2,7 @@ 2 2 3 3 import java.io.Serializable; 4 4 import java.util.Date; 5 +import java.util.Objects;5 6 6 7 import javax.persistence.Column; 7 8 import javax.persistence.Entity; .. .. @@ -22,6 +23,8 @@ 22 23 import com.fasterxml.jackson.annotation.JsonInclude.Include; 23 24 import com.fasterxml.jackson.annotation.JsonProperty; 24 25 26 +import net.curisit.securis.db.common.Metadata;27 +25 28 /** 26 29 * Entity implementation class for Entity: application_metadata 27 30 * .. .. @@ -32,7 +35,7 @@ 32 35 @Table(name = "application_metadata") 33 36 @JsonIgnoreProperties(ignoreUnknown = true) 34 37 @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 {36 39 37 40 private static final Logger LOG = LogManager.getLogger(ApplicationMetadata.class); 38 41 .. .. @@ -100,7 +103,20 @@ 100 103 @Override 101 104 public String toString() { 102 105 103 - return String.format("ApplicationMetadata (%s)", this.key);106 + return String.format("AppMd (%s: %s)", this.key, value);107 + }108 +109 + @Override110 + 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 + @Override118 + public int hashCode() {119 + return Objects.hash(key, application);104 120 } 105 121 106 122 } securis/src/main/java/net/curisit/securis/db/LicenseType.java
.. .. @@ -62,7 +62,7 @@ 62 62 @JoinColumn(name = "application_id") 63 63 private Application application; 64 64 65 - @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "licenseType")65 + @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.REFRESH }, mappedBy = "licenseType")66 66 @JsonManagedReference 67 67 private Set<LicenseTypeMetadata> metadata; 68 68 .. .. @@ -152,7 +152,11 @@ 152 152 153 153 @Override 154 154 public int hashCode() { 155 -156 155 return (id == null ? 0 : id.hashCode()); 157 156 } 157 +158 + @Override159 + public String toString() {160 + return String.format("LT: ID: %d, code: %s", id, code);161 + }158 162 } securis/src/main/java/net/curisit/securis/db/LicenseTypeMetadata.java
.. .. @@ -1,6 +1,7 @@ 1 1 package net.curisit.securis.db; 2 2 3 3 import java.io.Serializable; 4 +import java.util.Objects;4 5 5 6 import javax.persistence.Column; 6 7 import javax.persistence.Entity; .. .. @@ -17,6 +18,8 @@ 17 18 import com.fasterxml.jackson.annotation.JsonInclude; 18 19 import com.fasterxml.jackson.annotation.JsonInclude.Include; 19 20 21 +import net.curisit.securis.db.common.Metadata;22 +20 23 /** 21 24 * Entity implementation class for Entity: licensetype_metadata 22 25 * .. .. @@ -27,7 +30,7 @@ 27 30 @Table(name = "licensetype_metadata") 28 31 @JsonIgnoreProperties(ignoreUnknown = true) 29 32 @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 {31 34 32 35 private static final long serialVersionUID = 1L; 33 36 .. .. @@ -76,4 +79,22 @@ 76 79 public void setMandatory(boolean mandatory) { 77 80 this.mandatory = mandatory; 78 81 } 82 +83 + @Override84 + 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 + @Override92 + public int hashCode() {93 + return Objects.hash(key, licenseType);94 + }95 +96 + @Override97 + public String toString() {98 + return String.format("LTMD (%s: %s)", key, value);99 + }79 100 } securis/src/main/java/net/curisit/securis/db/Pack.java
.. .. @@ -20,8 +20,6 @@ 20 20 import javax.persistence.OneToMany; 21 21 import javax.persistence.Table; 22 22 23 -import net.curisit.integrity.commons.Utils;24 -25 23 import org.hibernate.annotations.Type; 26 24 27 25 import com.fasterxml.jackson.annotation.JsonAutoDetect; .. .. @@ -30,6 +28,8 @@ 30 28 import com.fasterxml.jackson.annotation.JsonInclude; 31 29 import com.fasterxml.jackson.annotation.JsonInclude.Include; 32 30 import com.fasterxml.jackson.annotation.JsonProperty; 31 +32 +import net.curisit.integrity.commons.Utils;33 33 34 34 /** 35 35 * Entity implementation class for Entity: pack .. .. @@ -40,358 +40,360 @@ 40 40 @Entity 41 41 @Table(name = "pack") 42 42 @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") })48 47 public class Pack implements Serializable { 49 48 50 - private static final long serialVersionUID = 1L;49 + private static final long serialVersionUID = 1L;51 50 52 - @Id53 - @GeneratedValue54 - private Integer id;51 + @Id52 + @GeneratedValue53 + private Integer id;55 54 56 - private String code;55 + private String code;57 56 58 - private String comments;57 + private String comments;59 58 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;63 62 64 - @JsonIgnore65 - @ManyToOne66 - @JoinColumn(name = "organization_id")67 - private Organization organization;63 + @JsonIgnore64 + @ManyToOne65 + @JoinColumn(name = "organization_id")66 + private Organization organization;68 67 69 - @JsonIgnore70 - @ManyToOne71 - @JoinColumn(name = "license_type_id")72 - private LicenseType licenseType;68 + @JsonIgnore69 + @ManyToOne70 + @JoinColumn(name = "license_type_id")71 + private LicenseType licenseType;73 72 74 - @JsonIgnore75 - @ManyToOne76 - @JoinColumn(name = "created_by")77 - private User createdBy;73 + @JsonIgnore74 + @ManyToOne75 + @JoinColumn(name = "created_by")76 + private User createdBy;78 77 79 - @JsonIgnore80 - @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "pack")81 - private Set<License> licenses;78 + @JsonIgnore79 + @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.REFRESH }, mappedBy = "pack")80 + private Set<License> licenses;82 81 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;86 85 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;90 89 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;94 93 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;97 96 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;101 100 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;105 104 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;109 108 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;112 111 113 - public Integer getId() {114 - return id;115 - }112 + public Integer getId() {113 + return id;114 + }116 115 117 - public void setId(Integer id) {118 - this.id = id;119 - }116 + public void setId(Integer id) {117 + this.id = id;118 + }120 119 121 - public String getCode() {122 - return code;123 - }120 + public String getCode() {121 + return code;122 + }124 123 125 - public void setCode(String code) {126 - this.code = code;127 - }124 + public void setCode(String code) {125 + this.code = code;126 + }128 127 129 - public Date getCreationTimestamp() {130 - return creationTimestamp;131 - }128 + public Date getCreationTimestamp() {129 + return creationTimestamp;130 + }132 131 133 - public void setCreationTimestamp(Date creationTimestamp) {134 - this.creationTimestamp = creationTimestamp;135 - }132 + public void setCreationTimestamp(Date creationTimestamp) {133 + this.creationTimestamp = creationTimestamp;134 + }136 135 137 - public Organization getOrganization() {138 - return organization;139 - }136 + public Organization getOrganization() {137 + return organization;138 + }140 139 141 - public void setOrganization(Organization organization) {142 - this.organization = organization;143 - }140 + public void setOrganization(Organization organization) {141 + this.organization = organization;142 + }144 143 145 - public LicenseType getLicenseType() {146 - return licenseType;147 - }144 + public LicenseType getLicenseType() {145 + return licenseType;146 + }148 147 149 - public void setLicenseType(LicenseType licenseType) {150 - this.licenseType = licenseType;151 - }148 + public void setLicenseType(LicenseType licenseType) {149 + this.licenseType = licenseType;150 + }152 151 153 - public User getCreatedBy() {154 - return createdBy;155 - }152 + public User getCreatedBy() {153 + return createdBy;154 + }156 155 157 - public void setCreatedBy(User createdBy) {158 - this.createdBy = createdBy;159 - }156 + public void setCreatedBy(User createdBy) {157 + this.createdBy = createdBy;158 + }160 159 161 - public int getNumLicenses() {162 - return numLicenses;163 - }160 + public int getNumLicenses() {161 + return numLicenses;162 + }164 163 165 - public void setNumLicenses(int numLicenses) {166 - this.numLicenses = numLicenses;167 - }164 + public void setNumLicenses(int numLicenses) {165 + this.numLicenses = numLicenses;166 + }168 167 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 + }182 181 183 - /**184 - * Counts all created licenses, It counts active licenses and licenses185 - * waiting for activation This number will be used to control the max number186 - * of licenses created. Ignore canceled licenses.187 - *188 - * @return189 - */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 licenses184 + * waiting for activation This number will be used to control the max number185 + * of licenses created. Ignore canceled licenses.186 + *187 + * @return188 + */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 + }203 202 204 - /**205 - * Number of available licenses in this pack206 - *207 - * @return208 - */209 - @JsonProperty("num_available")210 - public int getNumAvailables() {211 - return numLicenses - getNumActivations();212 - }203 + /**204 + * Number of available licenses in this pack205 + *206 + * @return207 + */208 + @JsonProperty("num_available")209 + public int getNumAvailables() {210 + return numLicenses - getNumActivations();211 + }213 212 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 + }218 217 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 + }227 226 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 + }232 231 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 + }242 241 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 + }252 251 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 + }257 256 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 + }262 261 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 + }268 267 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 ? null271 + : String.format("%s %s (%s)", createdBy.getFirstName(), createdBy.getLastName() != null ? createdBy.getLastName() : "", createdBy.getUsername());272 + }274 273 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 + }279 278 280 - public String getComments() {281 - return comments;282 - }279 + public String getComments() {280 + return comments;281 + }283 282 284 - public void setComments(String comments) {285 - this.comments = comments;286 - }283 + public void setComments(String comments) {284 + this.comments = comments;285 + }287 286 288 - public boolean isLicensePreactivation() {289 - return licensePreactivation;290 - }287 + public boolean isLicensePreactivation() {288 + return licensePreactivation;289 + }291 290 292 - public void setLicensePreactivation(boolean licensePreactivation) {293 - this.licensePreactivation = licensePreactivation;294 - }291 + public void setLicensePreactivation(boolean licensePreactivation) {292 + this.licensePreactivation = licensePreactivation;293 + }295 294 296 - public Set<PackMetadata> getMetadata() {297 - return metadata;298 - }295 + public Set<PackMetadata> getMetadata() {296 + return metadata;297 + }299 298 300 - public void setMetadata(Set<PackMetadata> metadata) {301 - this.metadata = metadata;302 - }299 + public void setMetadata(Set<PackMetadata> metadata) {300 + this.metadata = metadata;301 + }303 302 304 - public PackStatus getStatus() {305 - return status;306 - }303 + public PackStatus getStatus() {304 + return status;305 + }307 306 308 - public void setStatus(PackStatus status) {309 - this.status = status;310 - }307 + public void setStatus(PackStatus status) {308 + this.status = status;309 + }311 310 312 - public Date getInitValidDate() {313 - return initValidDate;314 - }311 + public Date getInitValidDate() {312 + return initValidDate;313 + }315 314 316 - public void setInitValidDate(Date initValidDate) {317 - this.initValidDate = initValidDate;318 - }315 + public void setInitValidDate(Date initValidDate) {316 + this.initValidDate = initValidDate;317 + }319 318 320 - public Date getEndValidDate() {321 - return endValidDate;322 - }319 + public Date getEndValidDate() {320 + return endValidDate;321 + }323 322 324 - public void setEndValidDate(Date endValidDate) {325 - this.endValidDate = endValidDate;326 - }323 + public void setEndValidDate(Date endValidDate) {324 + this.endValidDate = endValidDate;325 + }327 326 328 - public Set<License> getLicenses() {329 - return licenses;330 - }327 + public Set<License> getLicenses() {328 + return licenses;329 + }331 330 332 - public void setLicenses(Set<License> licenses) {333 - this.licenses = licenses;334 - }331 + public void setLicenses(Set<License> licenses) {332 + this.licenses = licenses;333 + }335 334 336 - @Override337 - 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 + }343 338 344 - @Override345 - public int hashCode() {339 + public void setPreactivationValidPeriod(Integer preactivationValidPeriod) {340 + this.preactivationValidPeriod = preactivationValidPeriod;341 + }346 342 347 - return (id == null ? 0 : id.hashCode());348 - }343 + public Integer getRenewValidPeriod() {344 + return renewValidPeriod;345 + }349 346 350 - public Integer getPreactivationValidPeriod() {351 - return preactivationValidPeriod;352 - }347 + public void setRenewValidPeriod(Integer renewValidPeriod) {348 + this.renewValidPeriod = renewValidPeriod;349 + }353 350 354 - public void setPreactivationValidPeriod(Integer preactivationValidPeriod) {355 - this.preactivationValidPeriod = preactivationValidPeriod;356 - }351 + @Override352 + public boolean equals(Object obj) {353 + if (!(obj instanceof Application))354 + return false;355 + return id.equals(Pack.class.cast(obj).id);356 + }357 357 358 - public Integer getRenewValidPeriod() {359 - return renewValidPeriod;360 - }358 + @Override359 + public int hashCode() {360 + return (id == null ? 0 : id.hashCode());361 + }361 362 362 - public void setRenewValidPeriod(Integer renewValidPeriod) {363 - this.renewValidPeriod = renewValidPeriod;364 - }363 + @Override364 + public String toString() {365 + return String.format("Pack: ID: %d, code: %s", id, code);366 + }365 367 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 + }373 375 374 - public static class Status {376 + public static class Status {375 377 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 + );382 384 383 - /**384 - * It checks if a given action is valid for the License, passing the385 - * action and the current license status386 - *387 - * @param oldStatus388 - * @param newStatus389 - * @return390 - */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 the387 + * action and the current license status388 + *389 + * @param oldStatus390 + * @param newStatus391 + * @return392 + */393 + public static boolean isActionValid(Integer action, PackStatus currentStatus) {394 + List<PackStatus> validStatuses = transitions.get(action);393 395 394 - return validStatuses != null && validStatuses.contains(currentStatus);395 - }396 - }396 + return validStatuses != null && validStatuses.contains(currentStatus);397 + }398 + }397 399 } securis/src/main/java/net/curisit/securis/db/PackMetadata.java
.. .. @@ -1,6 +1,7 @@ 1 1 package net.curisit.securis.db; 2 2 3 3 import java.io.Serializable; 4 +import java.util.Objects;4 5 5 6 import javax.persistence.Column; 6 7 import javax.persistence.Entity; .. .. @@ -18,6 +19,8 @@ 18 19 import com.fasterxml.jackson.annotation.JsonInclude.Include; 19 20 import com.fasterxml.jackson.annotation.JsonProperty; 20 21 22 +import net.curisit.securis.db.common.Metadata;23 +21 24 /** 22 25 * Entity implementation class for Entity: pack_metadata 23 26 * .. .. @@ -28,7 +31,7 @@ 28 31 @Table(name = "pack_metadata") 29 32 @JsonIgnoreProperties(ignoreUnknown = true) 30 33 @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 {32 35 33 36 private static final long serialVersionUID = 1L; 34 37 .. .. @@ -103,4 +106,22 @@ 103 106 this.mandatory = mandatory; 104 107 } 105 108 109 + @Override110 + public String toString() {111 + return String.format("PackMD (%s: %s)", key, value);112 + }113 +114 + @Override115 + 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 + @Override123 + public int hashCode() {124 + return Objects.hash(key, pack);125 + }126 +106 127 } 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 @@ 25 25 import javax.ws.rs.core.Response; 26 26 import javax.ws.rs.core.Response.Status; 27 27 28 +import org.apache.logging.log4j.LogManager;29 +import org.apache.logging.log4j.Logger;30 +28 31 import net.curisit.integrity.commons.Utils; 29 32 import net.curisit.securis.DefaultExceptionHandler; 30 33 import net.curisit.securis.db.Application; .. .. @@ -34,10 +37,8 @@ 34 37 import net.curisit.securis.security.Securable; 35 38 import net.curisit.securis.services.exception.SeCurisServiceException; 36 39 import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes; 40 +import net.curisit.securis.services.helpers.MetadataHelper;37 41 import net.curisit.securis.utils.TokenHelper; 38 -39 -import org.apache.logging.log4j.LogManager;40 -import org.apache.logging.log4j.Logger;41 42 42 43 /** 43 44 * Application resource, this service will provide methods to create, modify and .. .. @@ -48,191 +49,185 @@ 48 49 @Path("/application") 49 50 public class ApplicationResource { 50 51 51 - @Inject52 - TokenHelper tokenHelper;52 + @Inject53 + TokenHelper tokenHelper;53 54 54 - @Context55 - EntityManager em;55 + @Inject56 + MetadataHelper metadataHelper;56 57 57 - private static final Logger LOG = LogManager.getLogger(ApplicationResource.class);58 + @Context59 + EntityManager em;58 60 59 - public ApplicationResource() {60 - }61 + private static final Logger LOG = LogManager.getLogger(ApplicationResource.class);61 62 62 - /**63 - *64 - * @return the server version in format majorVersion.minorVersion65 - */66 - @GET67 - @Path("/")68 - @Produces({69 - MediaType.APPLICATION_JSON70 - })71 - @Securable72 - public Response index() {73 - LOG.info("Getting applications list ");63 + public ApplicationResource() {64 + }74 65 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.minorVersion69 + */70 + @GET71 + @Path("/")72 + @Produces({ MediaType.APPLICATION_JSON })73 + @Securable74 + public Response index() {75 + LOG.info("Getting applications list ");79 76 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();82 81 83 - /**84 - *85 - * @return the server version in format majorVersion.minorVersion86 - * @throws SeCurisServiceException87 - */88 - @GET89 - @Path("/{appid}")90 - @Produces({91 - MediaType.APPLICATION_JSON92 - })93 - @Securable94 - 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 + }100 84 101 - em.clear();85 + /**86 + *87 + * @return the server version in format majorVersion.minorVersion88 + * @throws SeCurisServiceException89 + */90 + @GET91 + @Path("/{appid}")92 + @Produces({ MediaType.APPLICATION_JSON })93 + @Securable94 + 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 + }102 100 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();114 102 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 + }117 114 118 - @POST119 - @Path("/")120 - @Consumes(MediaType.APPLICATION_JSON)121 - @Produces({122 - MediaType.APPLICATION_JSON123 - })124 - @EnsureTransaction125 - @Securable126 - @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 + }132 117 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 + @POST119 + @Path("/")120 + @Consumes(MediaType.APPLICATION_JSON)121 + @Produces({ MediaType.APPLICATION_JSON })122 + @EnsureTransaction123 + @Securable124 + @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);141 130 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());144 139 145 - @PUT146 - @POST147 - @Path("/{appid}")148 - @EnsureTransaction149 - @Consumes(MediaType.APPLICATION_JSON)150 - @Produces({151 - MediaType.APPLICATION_JSON152 - })153 - @Securable154 - @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 + }168 142 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 + @PUT144 + @POST145 + @Path("/{appid}")146 + @EnsureTransaction147 + @Consumes(MediaType.APPLICATION_JSON)148 + @Produces({ MediaType.APPLICATION_JSON })149 + @Securable150 + @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());178 163 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 + }199 175 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 + }209 197 210 - @DELETE211 - @Path("/{appid}")212 - @EnsureTransaction213 - @Produces({214 - MediaType.APPLICATION_JSON215 - })216 - @Securable217 - @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 new230 - * 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 + @DELETE209 + @Path("/{appid}")210 + @EnsureTransaction211 + @Produces({ MediaType.APPLICATION_JSON })212 + @Securable213 + @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 new225 + * 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 + }237 232 238 233 } securis/src/main/java/net/curisit/securis/services/BasicServices.java
.. .. @@ -7,8 +7,8 @@ 7 7 8 8 import javax.enterprise.context.ApplicationScoped; 9 9 import javax.inject.Inject; 10 +import javax.persistence.EntityManager;10 11 import javax.servlet.http.HttpServletRequest; 11 -import javax.ws.rs.FormParam;12 12 import javax.ws.rs.GET; 13 13 import javax.ws.rs.HeaderParam; 14 14 import javax.ws.rs.POST; .. .. @@ -44,6 +44,9 @@ 44 44 @Inject 45 45 TokenHelper tokenHelper; 46 46 47 + @Context48 + EntityManager em;49 +47 50 @Inject 48 51 public BasicServices() { 49 52 } .. .. @@ -74,16 +77,6 @@ 74 77 String page = "/index.jsp"; 75 78 URI uri = UriBuilder.fromUri(page).build(); 76 79 return Response.seeOther(uri).build(); 77 - }78 -79 - @POST80 - @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();87 80 } 88 81 89 82 /** securis/src/main/java/net/curisit/securis/services/LicenseTypeResource.java
.. .. @@ -4,6 +4,7 @@ 4 4 import java.util.HashSet; 5 5 import java.util.List; 6 6 import java.util.Set; 7 +import java.util.stream.Collectors;7 8 8 9 import javax.annotation.security.RolesAllowed; 9 10 import javax.inject.Inject; .. .. @@ -24,6 +25,9 @@ 24 25 import javax.ws.rs.core.Response; 25 26 import javax.ws.rs.core.Response.Status; 26 27 28 +import org.apache.logging.log4j.LogManager;29 +import org.apache.logging.log4j.Logger;30 +27 31 import net.curisit.integrity.commons.Utils; 28 32 import net.curisit.securis.DefaultExceptionHandler; 29 33 import net.curisit.securis.SeCurisException; .. .. @@ -35,10 +39,8 @@ 35 39 import net.curisit.securis.security.Securable; 36 40 import net.curisit.securis.services.exception.SeCurisServiceException; 37 41 import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes; 42 +import net.curisit.securis.services.helpers.MetadataHelper;38 43 import net.curisit.securis.utils.TokenHelper; 39 -40 -import org.apache.logging.log4j.LogManager;41 -import org.apache.logging.log4j.Logger;42 44 43 45 /** 44 46 * LicenseType resource, this service will provide methods to create, modify and .. .. @@ -49,206 +51,204 @@ 49 51 @Path("/licensetype") 50 52 public class LicenseTypeResource { 51 53 52 - private static final Logger LOG = LogManager.getLogger(LicenseTypeResource.class);54 + private static final Logger LOG = LogManager.getLogger(LicenseTypeResource.class);53 55 54 - @Inject55 - TokenHelper tokenHelper;56 + @Inject57 + TokenHelper tokenHelper;56 58 57 - @Context58 - EntityManager em;59 + @Inject60 + MetadataHelper metadataHelper;59 61 60 - public LicenseTypeResource() {61 - }62 + @Context63 + EntityManager em;62 64 63 - /**64 - *65 - * @return the server version in format majorVersion.minorVersion66 - */67 - @GET68 - @Path("/")69 - @Produces({70 - MediaType.APPLICATION_JSON71 - })72 - @Securable73 - public Response index() {74 - LOG.info("Getting license types list ");65 + public LicenseTypeResource() {66 + }75 67 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.minorVersion71 + */72 + @GET73 + @Path("/")74 + @Produces({ MediaType.APPLICATION_JSON })75 + @Securable76 + public Response index() {77 + LOG.info("Getting license types list ");80 78 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();83 83 84 - /**85 - *86 - * @return the server version in format majorVersion.minorVersion87 - * @throws SeCurisServiceException88 - */89 - @GET90 - @Path("/{ltid}")91 - @Produces({92 - MediaType.APPLICATION_JSON93 - })94 - @Securable95 - 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 + }101 86 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.minorVersion90 + * @throws SeCurisServiceException91 + */92 + @GET93 + @Path("/{ltid}")94 + @Produces({ MediaType.APPLICATION_JSON })95 + @Securable96 + 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 + }111 102 112 - @POST113 - @Path("/")114 - @Consumes(MediaType.APPLICATION_JSON)115 - @Produces({116 - MediaType.APPLICATION_JSON117 - })118 - @EnsureTransaction119 - @Securable120 - @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 + }124 112 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 + @POST114 + @Path("/")115 + @Consumes(MediaType.APPLICATION_JSON)116 + @Produces({ MediaType.APPLICATION_JSON })117 + @EnsureTransaction118 + @Securable119 + @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();130 123 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 + }136 129 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 + }140 134 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();148 138 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);151 146 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 + }161 149 162 - @PUT163 - @POST164 - @Path("/{ltid}")165 - @EnsureTransaction166 - @Consumes(MediaType.APPLICATION_JSON)167 - @Produces({168 - MediaType.APPLICATION_JSON169 - })170 - @Securable171 - @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 + }181 159 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 + @PUT161 + @POST162 + @Path("/{ltid}")163 + @EnsureTransaction164 + @Consumes(MediaType.APPLICATION_JSON)165 + @Produces({ MediaType.APPLICATION_JSON })166 + @Securable167 + @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 + }187 176 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 + }191 182 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());200 186 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 + }204 198 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);216 201 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 + }219 218 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 + }226 221 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);232 228 233 - @DELETE234 - @Path("/{ltid}")235 - @EnsureTransaction236 - @Produces({237 - MediaType.APPLICATION_JSON238 - })239 - @Securable240 - @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 + }249 234 250 - em.remove(app);251 - return Response.ok(Utils.createMap("success", true, "id", ltid)).build();252 - }235 + @DELETE236 + @Path("/{ltid}")237 + @EnsureTransaction238 + @Produces({ MediaType.APPLICATION_JSON })239 + @Securable240 + @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 + }253 253 254 254 } securis/src/main/java/net/curisit/securis/services/PackResource.java
.. .. @@ -86,10 +86,10 @@ 86 86 LOG.info("Getting all packs for user: " + bsc.getUserPrincipal()); 87 87 q = em.createNamedQuery("list-packs", Pack.class); 88 88 } else { 89 - q = em.createNamedQuery("list-packs-by-orgs", Pack.class);90 89 if (bsc.getOrganizationsIds() == null) { 91 - Response.ok().build();90 + return Response.ok().build();92 91 } 92 + q = em.createNamedQuery("list-packs-by-orgs", Pack.class);93 93 q.setParameter("list_ids", bsc.getOrganizationsIds()); 94 94 } 95 95 securis/src/main/java/net/curisit/securis/services/UserResource.java
.. .. @@ -264,10 +264,9 @@ 264 264 em.getTransaction().rollback(); 265 265 } 266 266 clearUserCache(username); 267 -267 + String userFullName = String.format("%s %s", user.getFirstName(), user.getLastName() == null ? "" : user.getLastName()).trim();268 268 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();271 270 } 272 271 273 272 /** 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 +@ApplicationScoped26 +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 Packs104 + *105 + * @param em106 + * @param app107 + */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 Packs133 + *134 + * @param em135 + * @param lt136 + * @param keys137 + */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 +}