rsanchez
2016-12-05 1ed7bc42993b3d23d92dfc38dfd34026a4619ae7
#3410 #3411 fix - Fixed user roles and organizations and Pack date
fields on saving action
1 files added
5 files modified
changed files
securis/changes.sql patch | view | blame | history
securis/pom.xml patch | view | blame | history
securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.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/services/PackResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/UserResource.java patch | view | blame | history
securis/changes.sql
....@@ -0,0 +1,5 @@
1
+ALTER TABLE license ADD activation_code VARCHAR(100) NULL;
2
+ALTER TABLE application ADD code VARCHAR(4) NULL;
3
+alter table application_metadata modify column value VARCHAR(512) NULL;
4
+alter table licensetype_metadata modify column value VARCHAR(512) NULL;
5
+alter table pack_metadata modify column value VARCHAR(512) NULL;
securis/pom.xml
....@@ -3,7 +3,7 @@
33 <modelVersion>4.0.0</modelVersion>
44 <groupId>net.curisit</groupId>
55 <artifactId>securis-server</artifactId>
6
- <version>1.1.7</version>
6
+ <version>1.1.8</version>
77 <name>SeCuris</name>
88 <description>CurisTEC Server Licenses</description>
99 <dependencies>
securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.java
....@@ -11,65 +11,65 @@
1111 import javax.ws.rs.ext.ExceptionMapper;
1212 import javax.ws.rs.ext.Provider;
1313
14
-import net.curisit.securis.services.exception.SeCurisServiceException;
15
-import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
16
-
1714 import org.apache.logging.log4j.LogManager;
1815 import org.apache.logging.log4j.Logger;
1916
17
+import net.curisit.securis.services.exception.SeCurisServiceException;
18
+import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
19
+
2020 @Provider
2121 public class DefaultExceptionHandler implements ExceptionMapper<Exception> {
22
- private static final Logger LOG = LogManager.getLogger(DefaultExceptionHandler.class);
22
+ private static final Logger LOG = LogManager.getLogger(DefaultExceptionHandler.class);
2323
24
- public static final int DEFAULT_APP_ERROR_STATUS_CODE = 418;
25
- public static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR-MSG";
26
- public static final String ERROR_CODE_MESSAGE_HEADER = "X-SECURIS-ERROR-CODE";
24
+ public static final int DEFAULT_APP_ERROR_STATUS_CODE = 418;
25
+ public static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR-MSG";
26
+ public static final String ERROR_CODE_MESSAGE_HEADER = "X-SECURIS-ERROR-CODE";
2727
28
- public DefaultExceptionHandler() {
29
- LOG.info("Creating DefaultExceptionHandler ");
30
- }
28
+ public DefaultExceptionHandler() {
29
+ LOG.info("Creating DefaultExceptionHandler ");
30
+ }
3131
32
- @Context
33
- HttpServletRequest request;
34
- @Context
35
- SecurityContext bsc;
36
- @Context
37
- EntityManager em;
32
+ @Context
33
+ HttpServletRequest request;
34
+ @Context
35
+ SecurityContext bsc;
36
+ @Context
37
+ EntityManager em;
3838
39
- @Override
40
- public Response toResponse(Exception e) {
41
- releaseEntityManager();
42
- if (e instanceof ForbiddenException) {
43
- LOG.warn("ForbiddenException: {}", e);
44
- return Response.status(Status.UNAUTHORIZED).header(ERROR_CODE_MESSAGE_HEADER, ErrorCodes.INVALID_CREDENTIALS)
45
- .header(ERROR_MESSAGE_HEADER, "Unathorized access to the application").type(MediaType.APPLICATION_JSON).build();
46
- }
39
+ @Override
40
+ public Response toResponse(Exception e) {
41
+ releaseEntityManager();
42
+ if (e instanceof ForbiddenException) {
43
+ LOG.warn("ForbiddenException: {}", e.toString());
44
+ return Response.status(Status.UNAUTHORIZED).header(ERROR_CODE_MESSAGE_HEADER, ErrorCodes.INVALID_CREDENTIALS)
45
+ .header(ERROR_MESSAGE_HEADER, "Unathorized access to the application").type(MediaType.APPLICATION_JSON).build();
46
+ }
4747
48
- if (e instanceof SeCurisServiceException) {
49
- LOG.warn("SeCurisServiceException: {}", e);
50
- return Response.status(DEFAULT_APP_ERROR_STATUS_CODE).header(ERROR_CODE_MESSAGE_HEADER, ((SeCurisServiceException) e).getStatus())
51
- .header(ERROR_MESSAGE_HEADER, e.getMessage()).type(MediaType.APPLICATION_JSON).build();
52
- }
48
+ if (e instanceof SeCurisServiceException) {
49
+ LOG.warn("SeCurisServiceException: {}", e.toString());
50
+ return Response.status(DEFAULT_APP_ERROR_STATUS_CODE).header(ERROR_CODE_MESSAGE_HEADER, ((SeCurisServiceException) e).getStatus())
51
+ .header(ERROR_MESSAGE_HEADER, e.getMessage()).type(MediaType.APPLICATION_JSON).build();
52
+ }
5353
54
- LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal());
55
- LOG.error("Request sent from {}, with User-Agent: {}", request.getRemoteHost(), request.getHeader("User-Agent"));
56
- LOG.error("Request url: " + request.getRequestURL(), e);
57
- return Response.serverError().header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString()).type(MediaType.APPLICATION_JSON).build();
58
- }
54
+ LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal());
55
+ LOG.error("Request sent from {}, with User-Agent: {}", request.getRemoteHost(), request.getHeader("User-Agent"));
56
+ LOG.error("Request url: " + request.getRequestURL(), e);
57
+ return Response.serverError().header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString()).type(MediaType.APPLICATION_JSON).build();
58
+ }
5959
60
- private void releaseEntityManager() {
61
- try {
62
- if (em != null && em.isOpen()) {
63
- LOG.debug("CLOSING EM: {}, trans: {}", em, em.isJoinedToTransaction());
64
- if (em.isJoinedToTransaction()) {
65
- em.getTransaction().rollback();
66
- LOG.info("ROLLBACK");
67
- }
68
- em.close();
69
- }
70
- } catch (Exception ex) {
71
- ex.printStackTrace();
72
- LOG.error("Error closing EM: {}, {}", em, ex);
73
- }
74
- }
60
+ private void releaseEntityManager() {
61
+ try {
62
+ if (em != null && em.isOpen()) {
63
+ LOG.debug("CLOSING EM: {}, trans: {}", em, em.isJoinedToTransaction());
64
+ if (em.isJoinedToTransaction()) {
65
+ em.getTransaction().rollback();
66
+ LOG.info("ROLLBACK");
67
+ }
68
+ em.close();
69
+ }
70
+ } catch (Exception ex) {
71
+ ex.printStackTrace();
72
+ LOG.error("Error closing EM: {}, {}", em, ex);
73
+ }
74
+ }
7575 }
securis/src/main/java/net/curisit/securis/db/LicenseType.java
....@@ -37,125 +37,122 @@
3737 @JsonIgnoreProperties(ignoreUnknown = true)
3838 @Entity
3939 @Table(name = "license_type")
40
-@NamedQueries({
41
- @NamedQuery(name = "list-license_types", query = "SELECT lt FROM LicenseType lt"),
42
- @NamedQuery(name = "list-application-license_types", query = "SELECT lt FROM LicenseType lt where lt.application.id = :appId")
43
-})
40
+@NamedQueries({ @NamedQuery(name = "list-license_types", query = "SELECT lt FROM LicenseType lt"),
41
+ @NamedQuery(name = "list-application-license_types", query = "SELECT lt FROM LicenseType lt where lt.application.id = :appId") })
4442 public class LicenseType implements Serializable {
4543
46
- @SuppressWarnings("unused")
47
- private static final Logger LOG = LogManager.getLogger(LicenseType.class);
48
- private static final long serialVersionUID = 1L;
44
+ @SuppressWarnings("unused")
45
+ private static final Logger LOG = LogManager.getLogger(LicenseType.class);
46
+ private static final long serialVersionUID = 1L;
4947
50
- @Id
51
- @GeneratedValue
52
- private Integer id;
48
+ @Id
49
+ @GeneratedValue
50
+ private Integer id;
5351
54
- private String code;
55
- private String name;
56
- private String description;
52
+ private String code;
53
+ private String name;
54
+ private String description;
5755
58
- @Column(name = "creation_timestamp")
59
- @JsonProperty("creation_timestamp")
60
- private Date creationTimestamp;
56
+ @Column(name = "creation_timestamp")
57
+ @JsonProperty("creation_timestamp")
58
+ private Date creationTimestamp;
6159
62
- @JsonIgnore
63
- @ManyToOne(fetch = FetchType.LAZY)
64
- @JoinColumn(name = "application_id")
65
- private Application application;
60
+ @JsonIgnore
61
+ @ManyToOne(fetch = FetchType.LAZY)
62
+ @JoinColumn(name = "application_id")
63
+ private Application application;
6664
67
- @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "licenseType")
68
- @JsonManagedReference
69
- private Set<LicenseTypeMetadata> metadata;
65
+ @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "licenseType")
66
+ @JsonManagedReference
67
+ private Set<LicenseTypeMetadata> metadata;
7068
71
- public Set<LicenseTypeMetadata> getMetadata() {
72
- return metadata;
73
- }
69
+ public Set<LicenseTypeMetadata> getMetadata() {
70
+ return metadata;
71
+ }
7472
75
- public void setMetadata(Set<LicenseTypeMetadata> metadata) {
76
- this.metadata = metadata;
77
- }
73
+ public void setMetadata(Set<LicenseTypeMetadata> metadata) {
74
+ this.metadata = metadata;
75
+ }
7876
79
- public Integer getId() {
80
- return id;
81
- }
77
+ public Integer getId() {
78
+ return id;
79
+ }
8280
83
- public void setId(Integer id) {
84
- this.id = id;
85
- }
81
+ public void setId(Integer id) {
82
+ this.id = id;
83
+ }
8684
87
- public String getName() {
88
- return name;
89
- }
85
+ public String getName() {
86
+ return name;
87
+ }
9088
91
- public void setName(String name) {
92
- this.name = name;
93
- }
89
+ public void setName(String name) {
90
+ this.name = name;
91
+ }
9492
95
- public String getDescription() {
96
- return description;
97
- }
93
+ public String getDescription() {
94
+ return description;
95
+ }
9896
99
- public void setDescription(String description) {
100
- this.description = description;
101
- }
97
+ public void setDescription(String description) {
98
+ this.description = description;
99
+ }
102100
103
- public String getCode() {
104
- return code;
105
- }
101
+ public String getCode() {
102
+ return code;
103
+ }
106104
107
- public void setCode(String code) {
108
- this.code = code;
109
- }
105
+ public void setCode(String code) {
106
+ this.code = code;
107
+ }
110108
111
- public Application getApplication() {
112
- LOG.info("Getting APP from LicType");
113
- return application;
114
- }
109
+ public Application getApplication() {
110
+ return application;
111
+ }
115112
116
- @JsonProperty("application_name")
117
- public String getApplicationName() {
118
- return application == null ? null : application.getName();
119
- }
113
+ @JsonProperty("application_name")
114
+ public String getApplicationName() {
115
+ return application == null ? null : application.getName();
116
+ }
120117
121
- @JsonProperty("application_id")
122
- public Integer getApplicationId() {
123
- return application == null ? null : application.getId();
124
- }
118
+ @JsonProperty("application_id")
119
+ public Integer getApplicationId() {
120
+ return application == null ? null : application.getId();
121
+ }
125122
126
- @JsonProperty("application_id")
127
- public void setApplicationId(Integer appId) {
128
- if (appId == null) {
129
- application = null;
130
- } else {
131
- application = new Application();
132
- application.setId(appId);
133
- }
134
- }
123
+ @JsonProperty("application_id")
124
+ public void setApplicationId(Integer appId) {
125
+ if (appId == null) {
126
+ application = null;
127
+ } else {
128
+ application = new Application();
129
+ application.setId(appId);
130
+ }
131
+ }
135132
136
- public void setApplication(Application application) {
137
- this.application = application;
138
- }
133
+ public void setApplication(Application application) {
134
+ this.application = application;
135
+ }
139136
140
- public Date getCreationTimestamp() {
141
- return creationTimestamp;
142
- }
137
+ public Date getCreationTimestamp() {
138
+ return creationTimestamp;
139
+ }
143140
144
- public void setCreationTimestamp(Date creationTimestamp) {
145
- this.creationTimestamp = creationTimestamp;
146
- }
141
+ public void setCreationTimestamp(Date creationTimestamp) {
142
+ this.creationTimestamp = creationTimestamp;
143
+ }
147144
148
- @Override
149
- public boolean equals(Object obj) {
150
- if (!(obj instanceof LicenseType))
151
- return false;
152
- LicenseType other = (LicenseType) obj;
153
- return id.equals(other.id);
154
- }
145
+ @Override
146
+ public boolean equals(Object obj) {
147
+ if (!(obj instanceof LicenseType))
148
+ return false;
149
+ LicenseType other = (LicenseType) obj;
150
+ return id.equals(other.id);
151
+ }
155152
156
- @Override
157
- public int hashCode() {
153
+ @Override
154
+ public int hashCode() {
158155
159
- return (id == null ? 0 : id.hashCode());
160
- }
156
+ return (id == null ? 0 : id.hashCode());
157
+ }
161158 }
securis/src/main/java/net/curisit/securis/services/PackResource.java
....@@ -24,6 +24,9 @@
2424 import javax.ws.rs.core.Response;
2525 import javax.ws.rs.core.Response.Status;
2626
27
+import org.apache.logging.log4j.LogManager;
28
+import org.apache.logging.log4j.Logger;
29
+
2730 import net.curisit.integrity.commons.Utils;
2831 import net.curisit.securis.DefaultExceptionHandler;
2932 import net.curisit.securis.SeCurisException;
....@@ -44,9 +47,6 @@
4447 import net.curisit.securis.utils.LicUtils;
4548 import net.curisit.securis.utils.TokenHelper;
4649
47
-import org.apache.logging.log4j.LogManager;
48
-import org.apache.logging.log4j.Logger;
49
-
5050 /**
5151 * Pack resource, this service will provide methods to create, modify and delete
5252 * packs
....@@ -56,383 +56,363 @@
5656 @Path("/pack")
5757 public class PackResource {
5858
59
- private static final Logger LOG = LogManager.getLogger(PackResource.class);
59
+ private static final Logger LOG = LogManager.getLogger(PackResource.class);
6060
61
- @Inject
62
- TokenHelper tokenHelper;
61
+ @Inject
62
+ TokenHelper tokenHelper;
6363
64
- @Context
65
- EntityManager em;
64
+ @Context
65
+ EntityManager em;
6666
67
- @Inject
68
- private LicenseHelper licenseHelper;
67
+ @Inject
68
+ private LicenseHelper licenseHelper;
6969
70
- /**
71
- *
72
- * @return the server version in format majorVersion.minorVersion
73
- */
74
- @GET
75
- @Path("/")
76
- @Securable
77
- @Produces({
78
- MediaType.APPLICATION_JSON
79
- })
80
- public Response index(@Context BasicSecurityContext bsc) {
81
- LOG.info("Getting packs list ");
70
+ /**
71
+ *
72
+ * @return the server version in format majorVersion.minorVersion
73
+ */
74
+ @GET
75
+ @Path("/")
76
+ @Securable
77
+ @Produces({ MediaType.APPLICATION_JSON })
78
+ public Response index(@Context BasicSecurityContext bsc) {
79
+ LOG.info("Getting packs list ");
8280
83
- // EntityManager em = emProvider.get();
84
- em.clear();
81
+ // EntityManager em = emProvider.get();
82
+ em.clear();
8583
86
- TypedQuery<Pack> q;
87
- if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
88
- LOG.info("Getting all packs for user: " + bsc.getUserPrincipal());
89
- q = em.createNamedQuery("list-packs", Pack.class);
90
- } else {
91
- q = em.createNamedQuery("list-packs-by-orgs", Pack.class);
92
- if (bsc.getOrganizationsIds() == null) {
93
- Response.ok().build();
94
- }
95
- q.setParameter("list_ids", bsc.getOrganizationsIds());
96
- }
84
+ TypedQuery<Pack> q;
85
+ if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
86
+ LOG.info("Getting all packs for user: " + bsc.getUserPrincipal());
87
+ q = em.createNamedQuery("list-packs", Pack.class);
88
+ } else {
89
+ q = em.createNamedQuery("list-packs-by-orgs", Pack.class);
90
+ if (bsc.getOrganizationsIds() == null) {
91
+ Response.ok().build();
92
+ }
93
+ q.setParameter("list_ids", bsc.getOrganizationsIds());
94
+ }
9795
98
- List<Pack> list = q.getResultList();
96
+ List<Pack> list = q.getResultList();
9997
100
- return Response.ok(list).build();
101
- }
98
+ return Response.ok(list).build();
99
+ }
102100
103
- private Response generateErrorUnathorizedAccess(Pack pack, Principal user) {
104
- LOG.error("Pack with id {} not accesible by user {}", pack, user);
105
- return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack").build();
106
- }
101
+ private Response generateErrorUnathorizedAccess(Pack pack, Principal user) {
102
+ LOG.error("Pack with id {} not accesible by user {}", pack, user);
103
+ return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack").build();
104
+ }
107105
108
- /**
109
- *
110
- * @return the server version in format majorVersion.minorVersion
111
- */
112
- @GET
113
- @Path("/{packId}")
114
- @Securable
115
- @Produces({
116
- MediaType.APPLICATION_JSON
117
- })
118
- public Response get(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
119
- LOG.info("Getting pack data for id: {}: ", packId);
120
- if (packId == null || "".equals(packId)) {
121
- LOG.error("Pack ID is mandatory");
122
- return Response.status(Status.NOT_FOUND).build();
123
- }
106
+ /**
107
+ *
108
+ * @return the server version in format majorVersion.minorVersion
109
+ */
110
+ @GET
111
+ @Path("/{packId}")
112
+ @Securable
113
+ @Produces({ MediaType.APPLICATION_JSON })
114
+ public Response get(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
115
+ LOG.info("Getting pack data for id: {}: ", packId);
116
+ if (packId == null || "".equals(packId)) {
117
+ LOG.error("Pack ID is mandatory");
118
+ return Response.status(Status.NOT_FOUND).build();
119
+ }
124120
125
- // EntityManager em = emProvider.get();
126
- em.clear();
127
- Pack pack = em.find(Pack.class, packId);
128
- if (pack == null) {
129
- LOG.error("Pack with id {} not found in DB", packId);
130
- return Response.status(Status.NOT_FOUND).build();
131
- }
132
- if (bsc.isUserInRole(BasicSecurityContext.ROL_ADVANCE)
133
- && (bsc.getOrganizationsIds() == null || !bsc.getOrganizationsIds().contains(pack.getOrgId()))) {
134
- return generateErrorUnathorizedAccess(pack, bsc.getUserPrincipal());
135
- }
136
- return Response.ok(pack).build();
137
- }
121
+ // EntityManager em = emProvider.get();
122
+ em.clear();
123
+ Pack pack = em.find(Pack.class, packId);
124
+ if (pack == null) {
125
+ LOG.error("Pack with id {} not found in DB", packId);
126
+ return Response.status(Status.NOT_FOUND).build();
127
+ }
128
+ if (bsc.isUserInRole(BasicSecurityContext.ROL_ADVANCE) && (bsc.getOrganizationsIds() == null || !bsc.getOrganizationsIds().contains(pack.getOrgId()))) {
129
+ return generateErrorUnathorizedAccess(pack, bsc.getUserPrincipal());
130
+ }
131
+ return Response.ok(pack).build();
132
+ }
138133
139
- @POST
140
- @Path("/")
141
- @Securable
142
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
143
- @Consumes(MediaType.APPLICATION_JSON)
144
- @Produces({
145
- MediaType.APPLICATION_JSON
146
- })
147
- @EnsureTransaction
148
- public Response create(Pack pack, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
149
- LOG.info("Creating new pack");
150
- // EntityManager em = emProvider.get();
134
+ @POST
135
+ @Path("/")
136
+ @Securable
137
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
138
+ @Consumes(MediaType.APPLICATION_JSON)
139
+ @Produces({ MediaType.APPLICATION_JSON })
140
+ @EnsureTransaction
141
+ public Response create(Pack pack, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
142
+ LOG.info("Creating new pack");
143
+ // EntityManager em = emProvider.get();
151144
152
- if (checkIfCodeExists(pack.getCode(), em)) {
153
- throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is already used in an existing pack");
154
- }
145
+ if (checkIfCodeExists(pack.getCode(), em)) {
146
+ throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is already used in an existing pack");
147
+ }
155148
156
- try {
157
- setPackOrganization(pack, pack.getOrgId(), em);
158
- } catch (SeCurisException e) {
159
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
160
- }
149
+ try {
150
+ setPackOrganization(pack, pack.getOrgId(), em);
151
+ } catch (SeCurisException e) {
152
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
153
+ }
161154
162
- try {
163
- setPackLicenseType(pack, pack.getLicTypeId(), em);
164
- } catch (SeCurisException e) {
165
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
166
- }
155
+ try {
156
+ setPackLicenseType(pack, pack.getLicTypeId(), em);
157
+ } catch (SeCurisException e) {
158
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
159
+ }
167160
168
- User user = em.find(User.class, bsc.getUserPrincipal().getName());
161
+ User user = em.find(User.class, bsc.getUserPrincipal().getName());
169162
170
- pack.setStatus(PackStatus.CREATED);
171
- pack.setCreatedBy(user);
172
- pack.setCreationTimestamp(new Date());
173
- em.persist(pack);
174
- Set<PackMetadata> newMD = pack.getMetadata();
163
+ pack.setStatus(PackStatus.CREATED);
164
+ pack.setCreatedBy(user);
165
+ pack.setCreationTimestamp(new Date());
166
+ em.persist(pack);
167
+ Set<PackMetadata> newMD = pack.getMetadata();
175168
176
- if (newMD != null) {
177
- for (PackMetadata md : newMD) {
178
- md.setPack(pack);
179
- em.persist(md);
180
- }
181
- }
182
- pack.setMetadata(newMD);
183
- return Response.ok(pack).build();
184
- }
169
+ if (newMD != null) {
170
+ for (PackMetadata md : newMD) {
171
+ md.setPack(pack);
172
+ em.persist(md);
173
+ }
174
+ }
175
+ pack.setMetadata(newMD);
176
+ return Response.ok(pack).build();
177
+ }
185178
186
- /**
187
- * Check if there is some pack with the same code
188
- *
189
- * @param code
190
- * Pack code
191
- * @param em
192
- * DB session object
193
- * @return <code>true</code> if code is already used, <code>false</code>
194
- * otherwise
195
- */
196
- private boolean checkIfCodeExists(String code, EntityManager em) {
197
- TypedQuery<Pack> query = em.createNamedQuery("pack-by-code", Pack.class);
198
- query.setParameter("code", code);
199
- int packs = query.getResultList().size();
200
- return packs > 0;
201
- }
179
+ /**
180
+ * Check if there is some pack with the same code
181
+ *
182
+ * @param code
183
+ * Pack code
184
+ * @param em
185
+ * DB session object
186
+ * @return <code>true</code> if code is already used, <code>false</code>
187
+ * otherwise
188
+ */
189
+ private boolean checkIfCodeExists(String code, EntityManager em) {
190
+ TypedQuery<Pack> query = em.createNamedQuery("pack-by-code", Pack.class);
191
+ query.setParameter("code", code);
192
+ int packs = query.getResultList().size();
193
+ return packs > 0;
194
+ }
202195
203
- /**
204
- *
205
- * @return The next available code suffix in pack for license code
206
- * @throws SeCurisServiceException
207
- */
208
- @GET
209
- @Path("/{packId}/next_license_code")
210
- @Securable
211
- @Produces({
212
- MediaType.TEXT_PLAIN
213
- })
214
- public Response getCodeSuffix(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
215
- // EntityManager em = emProvider.get();
196
+ /**
197
+ *
198
+ * @return The next available code suffix in pack for license code
199
+ * @throws SeCurisServiceException
200
+ */
201
+ @GET
202
+ @Path("/{packId}/next_license_code")
203
+ @Securable
204
+ @Produces({ MediaType.TEXT_PLAIN })
205
+ public Response getCodeSuffix(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
206
+ // EntityManager em = emProvider.get();
216207
217
- if (packId == null) {
218
- throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is mandatory");
219
- }
220
- Integer codeSuffix = licenseHelper.getNextCodeSuffix(packId, em);
221
- Pack pack = em.find(Pack.class, packId);
222
- ;
208
+ if (packId == null) {
209
+ throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The pack code is mandatory");
210
+ }
211
+ Integer codeSuffix = licenseHelper.getNextCodeSuffix(packId, em);
212
+ Pack pack = em.find(Pack.class, packId);
213
+ ;
223214
224
- String licCode = LicUtils.getLicenseCode(pack.getCode(), codeSuffix);
225
- return Response.ok(licCode).build();
226
- }
215
+ String licCode = LicUtils.getLicenseCode(pack.getCode(), codeSuffix);
216
+ return Response.ok(licCode).build();
217
+ }
227218
228
- private void setPackLicenseType(Pack pack, Integer licTypeId, EntityManager em) throws SeCurisException {
229
- LicenseType lt = null;
230
- if (licTypeId != null) {
231
- lt = em.find(LicenseType.class, pack.getLicTypeId());
232
- if (lt == null) {
233
- LOG.error("Pack license type with id {} not found in DB", licTypeId);
234
- throw new SeCurisException("Pack license type not found with ID: " + licTypeId);
235
- }
236
- }
237
- pack.setLicenseType(lt);
238
- }
219
+ private void setPackLicenseType(Pack pack, Integer licTypeId, EntityManager em) throws SeCurisException {
220
+ LicenseType lt = null;
221
+ if (licTypeId != null) {
222
+ lt = em.find(LicenseType.class, pack.getLicTypeId());
223
+ if (lt == null) {
224
+ LOG.error("Pack license type with id {} not found in DB", licTypeId);
225
+ throw new SeCurisException("Pack license type not found with ID: " + licTypeId);
226
+ }
227
+ }
228
+ pack.setLicenseType(lt);
229
+ }
239230
240
- private Set<String> getMdKeys(Set<PackMetadata> mds) {
241
- Set<String> ids = new HashSet<String>();
242
- if (mds != null) {
243
- for (PackMetadata md : mds) {
244
- ids.add(md.getKey());
245
- }
246
- }
247
- return ids;
248
- }
231
+ private Set<String> getMdKeys(Set<PackMetadata> mds) {
232
+ Set<String> ids = new HashSet<String>();
233
+ if (mds != null) {
234
+ for (PackMetadata md : mds) {
235
+ ids.add(md.getKey());
236
+ }
237
+ }
238
+ return ids;
239
+ }
249240
250
- @PUT
251
- @POST
252
- @Path("/{packId}")
253
- @EnsureTransaction
254
- @Securable
255
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
256
- @Consumes(MediaType.APPLICATION_JSON)
257
- @Produces({
258
- MediaType.APPLICATION_JSON
259
- })
260
- public Response modify(Pack pack, @PathParam("packId") Integer packId) {
261
- LOG.info("Modifying pack with id: {}", packId);
262
- // EntityManager em = emProvider.get();
263
- Pack currentPack = em.find(Pack.class, packId);
241
+ @PUT
242
+ @POST
243
+ @Path("/{packId}")
244
+ @EnsureTransaction
245
+ @Securable
246
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
247
+ @Consumes(MediaType.APPLICATION_JSON)
248
+ @Produces({ MediaType.APPLICATION_JSON })
249
+ public Response modify(Pack pack, @PathParam("packId") Integer packId) {
250
+ LOG.info("Modifying pack with id: {}", packId);
251
+ // EntityManager em = emProvider.get();
252
+ Pack currentPack = em.find(Pack.class, packId);
264253
265
- try {
266
- setPackOrganization(currentPack, pack.getOrgId(), em);
267
- } catch (SeCurisException e) {
268
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
269
- }
254
+ try {
255
+ setPackOrganization(currentPack, pack.getOrgId(), em);
256
+ } catch (SeCurisException e) {
257
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
258
+ }
270259
271
- try {
272
- setPackLicenseType(currentPack, pack.getLicTypeId(), em);
273
- } catch (SeCurisException e) {
274
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
275
- }
260
+ try {
261
+ setPackLicenseType(currentPack, pack.getLicTypeId(), em);
262
+ } catch (SeCurisException e) {
263
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
264
+ }
276265
277
- currentPack.setLicensePreactivation(pack.isLicensePreactivation());
278
- currentPack.setCode(pack.getCode());
279
- currentPack.setComments(pack.getComments());
280
- currentPack.setNumLicenses(pack.getNumLicenses());
281
- currentPack.setPreactivationValidPeriod(pack.getPreactivationValidPeriod());
282
- currentPack.setRenewValidPeriod(pack.getRenewValidPeriod());
266
+ currentPack.setLicensePreactivation(pack.isLicensePreactivation());
267
+ currentPack.setCode(pack.getCode());
268
+ currentPack.setComments(pack.getComments());
269
+ currentPack.setNumLicenses(pack.getNumLicenses());
270
+ currentPack.setPreactivationValidPeriod(pack.getPreactivationValidPeriod());
271
+ currentPack.setRenewValidPeriod(pack.getRenewValidPeriod());
272
+ currentPack.setInitValidDate(pack.getInitValidDate());
273
+ currentPack.setEndValidDate(pack.getEndValidDate());
283274
284
- Set<PackMetadata> newMD = pack.getMetadata();
285
- Set<String> newMdKeys = getMdKeys(newMD);
286
- for (PackMetadata currentMd : currentPack.getMetadata()) {
287
- if (!newMdKeys.contains(currentMd.getKey())) {
288
- em.remove(currentMd);
289
- }
290
- }
275
+ Set<PackMetadata> newMD = pack.getMetadata();
276
+ Set<String> newMdKeys = getMdKeys(newMD);
277
+ for (PackMetadata currentMd : currentPack.getMetadata()) {
278
+ if (!newMdKeys.contains(currentMd.getKey())) {
279
+ em.remove(currentMd);
280
+ }
281
+ }
291282
292
- if (newMD != null) {
293
- Set<PackMetadata> oldMD = currentPack.getMetadata();
294
- Set<String> oldMdKeys = getMdKeys(newMD);
295
- for (PackMetadata md : newMD) {
296
- if (oldMdKeys.contains(md.getKey())) {
297
- em.merge(md);
298
- } else {
299
- md.setPack(currentPack);
300
- em.persist(md);
301
- }
302
- }
303
- }
304
- currentPack.setMetadata(newMD);
305
- em.merge(currentPack);
283
+ if (newMD != null) {
284
+ Set<String> oldMdKeys = getMdKeys(newMD);
285
+ for (PackMetadata md : newMD) {
286
+ if (oldMdKeys.contains(md.getKey())) {
287
+ em.merge(md);
288
+ } else {
289
+ md.setPack(currentPack);
290
+ em.persist(md);
291
+ }
292
+ }
293
+ }
294
+ currentPack.setMetadata(newMD);
295
+ em.merge(currentPack);
306296
307
- return Response.ok(currentPack).build();
308
- }
297
+ return Response.ok(currentPack).build();
298
+ }
309299
310
- @POST
311
- @Path("/{packId}/activate")
312
- @EnsureTransaction
313
- @Securable
314
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
315
- @Consumes(MediaType.APPLICATION_JSON)
316
- @Produces({
317
- MediaType.APPLICATION_JSON
318
- })
319
- public Response activate(@PathParam("packId") Integer packId) throws SeCurisServiceException {
320
- LOG.info("Activating pack with id: {}", packId);
321
- // EntityManager em = emProvider.get();
300
+ @POST
301
+ @Path("/{packId}/activate")
302
+ @EnsureTransaction
303
+ @Securable
304
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
305
+ @Consumes(MediaType.APPLICATION_JSON)
306
+ @Produces({ MediaType.APPLICATION_JSON })
307
+ public Response activate(@PathParam("packId") Integer packId) throws SeCurisServiceException {
308
+ LOG.info("Activating pack with id: {}", packId);
309
+ // EntityManager em = emProvider.get();
322310
323
- Pack currentPack = em.find(Pack.class, packId);
311
+ Pack currentPack = em.find(Pack.class, packId);
324312
325
- if (!Pack.Status.isActionValid(Pack.Action.ACTIVATION, currentPack.getStatus())) {
326
- LOG.error("Pack with id {} cannot be activaed from status {}", packId, currentPack.getStatus().name());
327
- throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be activated in status: " + currentPack.getStatus().name());
328
- }
313
+ if (!Pack.Status.isActionValid(Pack.Action.ACTIVATION, currentPack.getStatus())) {
314
+ LOG.error("Pack with id {} cannot be activaed from status {}", packId, currentPack.getStatus().name());
315
+ throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be activated in status: " + currentPack.getStatus().name());
316
+ }
329317
330
- currentPack.setStatus(PackStatus.ACTIVE);
331
- em.persist(currentPack);
318
+ currentPack.setStatus(PackStatus.ACTIVE);
319
+ em.persist(currentPack);
332320
333
- return Response.ok(currentPack).build();
334
- }
321
+ return Response.ok(currentPack).build();
322
+ }
335323
336
- @POST
337
- @Path("/{packId}/putonhold")
338
- @EnsureTransaction
339
- @Securable
340
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
341
- @Consumes(MediaType.APPLICATION_JSON)
342
- @Produces({
343
- MediaType.APPLICATION_JSON
344
- })
345
- public Response onhold(@PathParam("packId") Integer packId) throws SeCurisServiceException {
346
- LOG.info("Putting On hold pack with id: {}", packId);
347
- // EntityManager em = emProvider.get();
324
+ @POST
325
+ @Path("/{packId}/putonhold")
326
+ @EnsureTransaction
327
+ @Securable
328
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
329
+ @Consumes(MediaType.APPLICATION_JSON)
330
+ @Produces({ MediaType.APPLICATION_JSON })
331
+ public Response onhold(@PathParam("packId") Integer packId) throws SeCurisServiceException {
332
+ LOG.info("Putting On hold pack with id: {}", packId);
333
+ // EntityManager em = emProvider.get();
348334
349
- Pack currentPack = em.find(Pack.class, packId);
335
+ Pack currentPack = em.find(Pack.class, packId);
350336
351
- if (!Pack.Status.isActionValid(Pack.Action.PUT_ONHOLD, currentPack.getStatus())) {
352
- LOG.error("Pack with id {} cannot be put on hold from status {}", packId, currentPack.getStatus().name());
353
- throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be put on hold in status: " + currentPack.getStatus().name());
354
- }
337
+ if (!Pack.Status.isActionValid(Pack.Action.PUT_ONHOLD, currentPack.getStatus())) {
338
+ LOG.error("Pack with id {} cannot be put on hold from status {}", packId, currentPack.getStatus().name());
339
+ throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be put on hold in status: " + currentPack.getStatus().name());
340
+ }
355341
356
- currentPack.setStatus(PackStatus.ON_HOLD);
357
- em.persist(currentPack);
342
+ currentPack.setStatus(PackStatus.ON_HOLD);
343
+ em.persist(currentPack);
358344
359
- return Response.ok(currentPack).build();
360
- }
345
+ return Response.ok(currentPack).build();
346
+ }
361347
362
- @POST
363
- @Path("/{packId}/cancel")
364
- @EnsureTransaction
365
- @Securable
366
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
367
- @Consumes(MediaType.APPLICATION_JSON)
368
- @Produces({
369
- MediaType.APPLICATION_JSON
370
- })
371
- public Response cancel(@PathParam("packId") Integer packId, @FormParam("reason") String reason, @Context BasicSecurityContext bsc)
372
- throws SeCurisServiceException {
373
- LOG.info("Cancelling pack with id: {}", packId);
374
- // EntityManager em = emProvider.get();
348
+ @POST
349
+ @Path("/{packId}/cancel")
350
+ @EnsureTransaction
351
+ @Securable
352
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
353
+ @Consumes(MediaType.APPLICATION_JSON)
354
+ @Produces({ MediaType.APPLICATION_JSON })
355
+ public Response cancel(@PathParam("packId") Integer packId, @FormParam("reason") String reason, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
356
+ LOG.info("Cancelling pack with id: {}", packId);
357
+ // EntityManager em = emProvider.get();
375358
376
- Pack currentPack = em.find(Pack.class, packId);
359
+ Pack currentPack = em.find(Pack.class, packId);
377360
378
- if (!Pack.Status.isActionValid(Pack.Action.CANCEL, currentPack.getStatus())) {
379
- LOG.error("Pack with id {} cannot cancelled from status {}", packId, currentPack.getStatus().name());
380
- throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be cancelled in status: " + currentPack.getStatus().name());
381
- }
361
+ if (!Pack.Status.isActionValid(Pack.Action.CANCEL, currentPack.getStatus())) {
362
+ LOG.error("Pack with id {} cannot cancelled from status {}", packId, currentPack.getStatus().name());
363
+ throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Pack cannot be cancelled in status: " + currentPack.getStatus().name());
364
+ }
382365
383
- Set<License> licenses = currentPack.getLicenses();
384
- for (License license : licenses) {
385
- if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {
386
- licenseHelper.cancelLicense(license, "Pack cancellation. " + reason, bsc, em);
387
- }
388
- }
389
- currentPack.setStatus(PackStatus.CANCELLED);
390
- em.persist(currentPack);
366
+ Set<License> licenses = currentPack.getLicenses();
367
+ for (License license : licenses) {
368
+ if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {
369
+ licenseHelper.cancelLicense(license, "Pack cancellation. " + reason, bsc, em);
370
+ }
371
+ }
372
+ currentPack.setStatus(PackStatus.CANCELLED);
373
+ em.persist(currentPack);
391374
392
- return Response.ok(currentPack).build();
393
- }
375
+ return Response.ok(currentPack).build();
376
+ }
394377
395
- private void setPackOrganization(Pack currentPack, Integer orgId, EntityManager em) throws SeCurisException {
396
- Organization org = null;
397
- if (orgId != null) {
398
- org = em.find(Organization.class, orgId);
399
- if (org == null) {
400
- LOG.error("Organization pack with id {} not found in DB", orgId);
401
- throw new SeCurisException("Pack organization not found with ID: " + orgId);
402
- }
403
- }
404
- currentPack.setOrganization(org);
405
- }
378
+ private void setPackOrganization(Pack currentPack, Integer orgId, EntityManager em) throws SeCurisException {
379
+ Organization org = null;
380
+ if (orgId != null) {
381
+ org = em.find(Organization.class, orgId);
382
+ if (org == null) {
383
+ LOG.error("Organization pack with id {} not found in DB", orgId);
384
+ throw new SeCurisException("Pack organization not found with ID: " + orgId);
385
+ }
386
+ }
387
+ currentPack.setOrganization(org);
388
+ }
406389
407
- @DELETE
408
- @Path("/{packId}")
409
- @Securable
410
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
411
- @EnsureTransaction
412
- @Produces({
413
- MediaType.APPLICATION_JSON
414
- })
415
- public Response delete(@PathParam("packId") String packId) throws SeCurisServiceException {
416
- LOG.info("Deleting pack with id: {}", packId);
417
- // EntityManager em = emProvider.get();
418
- Pack pack = em.find(Pack.class, Integer.parseInt(packId));
419
- if (pack == null) {
420
- LOG.error("Pack with id {} can not be deleted, It was not found in DB", packId);
421
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Pack was not found, ID: " + packId)
422
- .build();
423
- }
424
- // Pack metadata is removed in cascade automatically.
390
+ @DELETE
391
+ @Path("/{packId}")
392
+ @Securable
393
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
394
+ @EnsureTransaction
395
+ @Produces({ MediaType.APPLICATION_JSON })
396
+ public Response delete(@PathParam("packId") String packId) throws SeCurisServiceException {
397
+ LOG.info("Deleting pack with id: {}", packId);
398
+ // EntityManager em = emProvider.get();
399
+ Pack pack = em.find(Pack.class, Integer.parseInt(packId));
400
+ if (pack == null) {
401
+ LOG.error("Pack with id {} can not be deleted, It was not found in DB", packId);
402
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Pack was not found, ID: " + packId).build();
403
+ }
404
+ // Pack metadata is removed in cascade automatically.
425405
426
- Set<License> licenses = pack.getLicenses();
427
- for (License license : licenses) {
428
- if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {
429
- throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "An active license cannot be deleted. License code: " + license.getCode());
430
- }
431
- em.remove(license);
432
- }
406
+ Set<License> licenses = pack.getLicenses();
407
+ for (License license : licenses) {
408
+ if (license.getStatus() == LicenseStatus.ACTIVE || license.getStatus() == LicenseStatus.PRE_ACTIVE) {
409
+ throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "An active license cannot be deleted. License code: " + license.getCode());
410
+ }
411
+ em.remove(license);
412
+ }
433413
434
- em.remove(pack);
435
- return Response.ok(Utils.createMap("success", true, "id", packId)).build();
436
- }
414
+ em.remove(pack);
415
+ return Response.ok(Utils.createMap("success", true, "id", packId)).build();
416
+ }
437417
438418 }
securis/src/main/java/net/curisit/securis/services/UserResource.java
....@@ -28,6 +28,9 @@
2828 import javax.ws.rs.core.Response;
2929 import javax.ws.rs.core.Response.Status;
3030
31
+import org.apache.logging.log4j.LogManager;
32
+import org.apache.logging.log4j.Logger;
33
+
3134 import net.curisit.integrity.commons.Utils;
3235 import net.curisit.securis.DefaultExceptionHandler;
3336 import net.curisit.securis.SeCurisException;
....@@ -38,10 +41,8 @@
3841 import net.curisit.securis.security.Securable;
3942 import net.curisit.securis.services.exception.SeCurisServiceException;
4043 import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
44
+import net.curisit.securis.utils.CacheTTL;
4145 import net.curisit.securis.utils.TokenHelper;
42
-
43
-import org.apache.logging.log4j.LogManager;
44
-import org.apache.logging.log4j.Logger;
4546
4647 /**
4748 * User resource
....@@ -52,266 +53,258 @@
5253 @RequestScoped
5354 public class UserResource {
5455
55
- @Inject
56
- TokenHelper tokenHelper;
56
+ @Inject
57
+ TokenHelper tokenHelper;
5758
58
- @Context
59
- EntityManager em;
59
+ @Inject
60
+ private CacheTTL cache;
6061
61
- private static final Logger LOG = LogManager.getLogger(UserResource.class);
62
+ @Context
63
+ EntityManager em;
6264
63
- public UserResource() {
64
- }
65
+ private static final Logger LOG = LogManager.getLogger(UserResource.class);
6566
66
- /**
67
- *
68
- * @return the server version in format majorVersion.minorVersion
69
- */
70
- @GET
71
- @Path("/")
72
- @Produces({
73
- MediaType.APPLICATION_JSON
74
- })
75
- @Securable
76
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
77
- public Response index() {
78
- LOG.info("Getting users list ");
67
+ public UserResource() {
68
+ }
7969
80
- // EntityManager em = emProvider.get();
81
- em.clear();
82
- TypedQuery<User> q = em.createNamedQuery("list-users", User.class);
70
+ /**
71
+ *
72
+ * @return the server version in format majorVersion.minorVersion
73
+ */
74
+ @GET
75
+ @Path("/")
76
+ @Produces({ MediaType.APPLICATION_JSON })
77
+ @Securable
78
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
79
+ public Response index() {
80
+ LOG.info("Getting users list ");
8381
84
- List<User> list = q.getResultList();
82
+ // EntityManager em = emProvider.get();
83
+ em.clear();
84
+ TypedQuery<User> q = em.createNamedQuery("list-users", User.class);
8585
86
- return Response.ok(list).build();
87
- }
86
+ List<User> list = q.getResultList();
8887
89
- /**
90
- *
91
- * @return The user
92
- */
93
- @GET
94
- @Path("/{uid}")
95
- @Produces({
96
- MediaType.APPLICATION_JSON
97
- })
98
- @Securable
99
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
100
- public Response get(@PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
101
- LOG.info("Getting user data for id: {}: ", uid);
102
- if (uid == null || "".equals(uid)) {
103
- LOG.error("User ID is mandatory");
104
- return Response.status(Status.NOT_FOUND).build();
105
- }
88
+ return Response.ok(list).build();
89
+ }
10690
107
- // EntityManager em = emProvider.get();
108
- em.clear();
109
- User lt = em.find(User.class, uid);
110
- if (lt == null) {
111
- LOG.error("User with id {} not found in DB", uid);
112
- return Response.status(Status.NOT_FOUND).build();
113
- }
114
- return Response.ok(lt).build();
115
- }
91
+ /**
92
+ *
93
+ * @return The user
94
+ */
95
+ @GET
96
+ @Path("/{uid}")
97
+ @Produces({ MediaType.APPLICATION_JSON })
98
+ @Securable
99
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
100
+ public Response get(@PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
101
+ LOG.info("Getting user data for id: {}: ", uid);
102
+ if (uid == null || "".equals(uid)) {
103
+ LOG.error("User ID is mandatory");
104
+ return Response.status(Status.NOT_FOUND).build();
105
+ }
116106
117
- @POST
118
- @Path("/")
119
- @Consumes(MediaType.APPLICATION_JSON)
120
- @Produces({
121
- MediaType.APPLICATION_JSON
122
- })
123
- @EnsureTransaction
124
- @Securable
125
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
126
- public Response create(User user, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
127
- LOG.info("Creating new user");
128
- // EntityManager em = emProvider.get();
129
- User currentUser = em.find(User.class, user.getUsername());
130
- if (currentUser != null) {
131
- LOG.info("User with id {} was found in DB, we'll try to modify it", user.getUsername());
132
- return modify(user, user.getUsername(), token);
133
- }
107
+ // EntityManager em = emProvider.get();
108
+ em.clear();
109
+ User lt = em.find(User.class, uid);
110
+ if (lt == null) {
111
+ LOG.error("User with id {} not found in DB", uid);
112
+ return Response.status(Status.NOT_FOUND).build();
113
+ }
114
+ return Response.ok(lt).build();
115
+ }
134116
135
- try {
136
- this.setUserOrg(user, user.getOrgsIds(), em);
137
- } catch (SeCurisException e) {
138
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
139
- }
140
- if (user.getPassword() != null && !"".equals(user.getPassword())) {
141
- user.setPassword(Utils.sha256(user.getPassword()));
142
- } else {
143
- return Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE)
144
- .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "User password is mandatory").build();
145
- }
146
- user.setModificationTimestamp(new Date());
147
- user.setLastLogin(null);
148
- user.setCreationTimestamp(new Date());
149
- em.persist(user);
117
+ @POST
118
+ @Path("/")
119
+ @Consumes(MediaType.APPLICATION_JSON)
120
+ @Produces({ MediaType.APPLICATION_JSON })
121
+ @EnsureTransaction
122
+ @Securable
123
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
124
+ public Response create(User user, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
125
+ LOG.info("Creating new user");
126
+ // EntityManager em = emProvider.get();
127
+ User currentUser = em.find(User.class, user.getUsername());
128
+ if (currentUser != null) {
129
+ LOG.info("User with id {} was found in DB, we'll try to modify it", user.getUsername());
130
+ return modify(user, user.getUsername(), token);
131
+ }
150132
151
- return Response.ok(user).build();
152
- }
133
+ try {
134
+ this.setUserOrg(user, user.getOrgsIds(), em);
135
+ } catch (SeCurisException e) {
136
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
137
+ }
138
+ if (user.getPassword() != null && !"".equals(user.getPassword())) {
139
+ user.setPassword(Utils.sha256(user.getPassword()));
140
+ } else {
141
+ return Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "User password is mandatory")
142
+ .build();
143
+ }
144
+ user.setModificationTimestamp(new Date());
145
+ user.setLastLogin(null);
146
+ user.setCreationTimestamp(new Date());
147
+ em.persist(user);
153148
154
- private void setUserOrg(User user, Set<Integer> orgsIds, EntityManager em) throws SeCurisException {
155
- Set<Organization> orgs = null;
156
- if (orgsIds != null && !orgsIds.isEmpty()) {
157
- orgs = new HashSet<>();
158
- for (Integer orgId : orgsIds) {
159
- Organization o = em.find(Organization.class, orgId);
160
- if (o == null) {
161
- LOG.error("User organization with id {} not found in DB", orgId);
162
- throw new SeCurisException("User's organization not found with ID: " + orgId);
163
- }
164
- orgs.add(o);
165
- }
166
- }
149
+ return Response.ok(user).build();
150
+ }
167151
168
- user.setOrganizations(orgs);
152
+ private void setUserOrg(User user, Set<Integer> orgsIds, EntityManager em) throws SeCurisException {
153
+ Set<Organization> orgs = null;
154
+ if (orgsIds != null && !orgsIds.isEmpty()) {
155
+ orgs = new HashSet<>();
156
+ for (Integer orgId : orgsIds) {
157
+ Organization o = em.find(Organization.class, orgId);
158
+ if (o == null) {
159
+ LOG.error("User organization with id {} not found in DB", orgId);
160
+ throw new SeCurisException("User's organization not found with ID: " + orgId);
161
+ }
162
+ orgs.add(o);
163
+ }
164
+ }
169165
170
- }
166
+ user.setOrganizations(orgs);
171167
172
- @PUT
173
- @POST
174
- @Path("/{uid}")
175
- @EnsureTransaction
176
- @Consumes(MediaType.APPLICATION_JSON)
177
- @Produces({
178
- MediaType.APPLICATION_JSON
179
- })
180
- @Securable
181
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
182
- public Response modify(User user, @PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
183
- LOG.info("Modifying user with id: {}", uid);
184
- // EntityManager em = emProvider.get();
185
- User currentUser = em.find(User.class, uid);
186
- if (currentUser == null) {
187
- LOG.info("User with id {} not found in DB, we'll try to create it", uid);
188
- return create(user, token);
189
- }
168
+ }
190169
191
- try {
192
- this.setUserOrg(currentUser, user.getOrgsIds(), em);
193
- } catch (SeCurisException e) {
194
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
195
- }
196
- currentUser.setFirstName(user.getFirstName());
197
- currentUser.setLastName(user.getLastName());
198
- currentUser.setRoles(user.getRoles());
199
- currentUser.setLang(user.getLang());
200
- currentUser.setModificationTimestamp(new Date());
201
- if (user.getPassword() != null && !"".equals(user.getPassword())) {
202
- currentUser.setPassword(Utils.sha256(user.getPassword()));
203
- } else {
204
- // Password has not been modified
205
- // return
206
- // Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER,
207
- // "User password is mandatory").build();
208
- }
170
+ @PUT
171
+ @POST
172
+ @Path("/{uid}")
173
+ @EnsureTransaction
174
+ @Consumes(MediaType.APPLICATION_JSON)
175
+ @Produces({ MediaType.APPLICATION_JSON })
176
+ @Securable
177
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
178
+ public Response modify(User user, @PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
179
+ LOG.info("Modifying user with id: {}", uid);
180
+ // EntityManager em = emProvider.get();
181
+ User currentUser = em.find(User.class, uid);
182
+ if (currentUser == null) {
183
+ LOG.info("User with id {} not found in DB, we'll try to create it", uid);
184
+ return create(user, token);
185
+ }
209186
210
- currentUser.setLastLogin(user.getLastLogin());
187
+ try {
188
+ this.setUserOrg(currentUser, user.getOrgsIds(), em);
189
+ } catch (SeCurisException e) {
190
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
191
+ }
192
+ currentUser.setFirstName(user.getFirstName());
193
+ currentUser.setLastName(user.getLastName());
194
+ currentUser.setRoles(user.getRoles());
195
+ currentUser.setLang(user.getLang());
196
+ currentUser.setModificationTimestamp(new Date());
197
+ if (user.getPassword() != null && !"".equals(user.getPassword())) {
198
+ currentUser.setPassword(Utils.sha256(user.getPassword()));
199
+ } else {
200
+ // Password has not been modified
201
+ // return
202
+ // Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER,
203
+ // "User password is mandatory").build();
204
+ }
211205
212
- em.persist(currentUser);
206
+ currentUser.setLastLogin(user.getLastLogin());
213207
214
- return Response.ok(currentUser).build();
215
- }
208
+ em.persist(currentUser);
209
+ clearUserCache(currentUser.getUsername());
216210
217
- @DELETE
218
- @Path("/{uid}")
219
- @EnsureTransaction
220
- @Produces({
221
- MediaType.APPLICATION_JSON
222
- })
223
- @Securable
224
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
225
- public Response delete(@PathParam("uid") String uid, @Context HttpServletRequest request) {
226
- LOG.info("Deleting app with id: {}", uid);
227
- // EntityManager em = emProvider.get();
228
- User app = em.find(User.class, uid);
229
- if (app == null) {
230
- LOG.error("User with id {} can not be deleted, It was not found in DB", uid);
231
- return Response.status(Status.NOT_FOUND).build();
232
- }
211
+ return Response.ok(currentUser).build();
212
+ }
233213
234
- em.remove(app);
235
- return Response.ok(Utils.createMap("success", true, "id", uid)).build();
236
- }
214
+ @DELETE
215
+ @Path("/{uid}")
216
+ @EnsureTransaction
217
+ @Produces({ MediaType.APPLICATION_JSON })
218
+ @Securable
219
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
220
+ public Response delete(@PathParam("uid") String uid, @Context HttpServletRequest request) {
221
+ LOG.info("Deleting app with id: {}", uid);
222
+ // EntityManager em = emProvider.get();
223
+ User user = em.find(User.class, uid);
224
+ if (user == null) {
225
+ LOG.error("User with id {} can not be deleted, It was not found in DB", uid);
226
+ return Response.status(Status.NOT_FOUND).build();
227
+ }
237228
238
- @POST
239
- @Path("/login")
240
- @Produces({
241
- MediaType.APPLICATION_JSON
242
- })
243
- public Response login(@FormParam("username") String username, @FormParam("password") String password, @Context HttpServletRequest request)
244
- throws SeCurisServiceException {
245
- LOG.info("index session: " + request.getSession());
246
- LOG.info("user: {}, pass: {}", username, password);
247
- LOG.info("is user in role: {} == {} ? ", "advance", request.isUserInRole("advance"));
248
- LOG.info("is user in role: {} == {} ? ", "admin", request.isUserInRole("admin"));
229
+ em.remove(user);
230
+ clearUserCache(user.getUsername());
231
+ return Response.ok(Utils.createMap("success", true, "id", uid)).build();
232
+ }
249233
250
- // EntityManager em = emProvider.get();
251
- User user = em.find(User.class, username);
252
- if (user == null) {
253
- LOG.error("Inknown username {} used in login service", username);
254
- throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");
255
- }
256
- String securedPassword = Utils.sha256(password);
234
+ private void clearUserCache(String username) {
235
+ cache.remove("roles_" + username);
236
+ cache.remove("orgs_" + username);
237
+ }
257238
258
- if (securedPassword == null || !securedPassword.equals(user.getPassword())) {
259
- throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");
260
- }
261
- user.setLastLogin(new Date());
262
- em.getTransaction().begin();
263
- try {
264
- em.persist(user);
265
- em.getTransaction().commit();
266
- } catch (PersistenceException ex) {
267
- LOG.error("Error updating last login date for user: {}", username);
268
- LOG.error(ex);
269
- em.getTransaction().rollback();
270
- }
271
- String tokenAuth = tokenHelper.generateToken(username);
272
- return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();
273
- }
239
+ @POST
240
+ @Path("/login")
241
+ @Produces({ MediaType.APPLICATION_JSON })
242
+ public Response login(@FormParam("username") String username, @FormParam("password") String password, @Context HttpServletRequest request) throws SeCurisServiceException {
243
+ LOG.info("index session: " + request.getSession());
274244
275
- /**
276
- * Check if current token is valid
277
- *
278
- * @param user
279
- * @param password
280
- * @param request
281
- * @return
282
- */
283
- @POST
284
- @Path("/check")
285
- @Produces({
286
- MediaType.APPLICATION_JSON
287
- })
288
- public Response check(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token, @QueryParam("token") String token2) {
289
- if (token == null) {
290
- token = token2;
291
- }
292
- if (token == null) {
293
- return Response.status(Status.FORBIDDEN).build();
294
- }
245
+ // EntityManager em = emProvider.get();
246
+ User user = em.find(User.class, username);
247
+ if (user == null) {
248
+ LOG.error("Unknown username {} used in login service", username);
249
+ throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");
250
+ }
251
+ String securedPassword = Utils.sha256(password);
295252
296
- LOG.info("Token : " + token);
297
- String user = tokenHelper.extractUserFromToken(token);
298
- LOG.info("Token user: " + user);
299
- Date date = tokenHelper.extractDateCreationFromToken(token);
300
- LOG.info("Token date: " + date);
301
- boolean valid = tokenHelper.isTokenValid(token);
253
+ if (securedPassword == null || !securedPassword.equals(user.getPassword())) {
254
+ throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Wrong credentials");
255
+ }
256
+ user.setLastLogin(new Date());
257
+ em.getTransaction().begin();
258
+ try {
259
+ em.persist(user);
260
+ em.getTransaction().commit();
261
+ } catch (PersistenceException ex) {
262
+ LOG.error("Error updating last login date for user: {}", username);
263
+ LOG.error(ex);
264
+ em.getTransaction().rollback();
265
+ }
266
+ clearUserCache(username);
302267
303
- LOG.info("Is Token valid: " + valid);
268
+ String tokenAuth = tokenHelper.generateToken(username);
269
+ return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();
270
+ }
304271
305
- return Response.ok(Utils.createMap("valid", true, "user", user, "date", date, "token", token)).build();
306
- }
272
+ /**
273
+ * Check if current token is valid
274
+ *
275
+ * @param user
276
+ * @param password
277
+ * @param request
278
+ * @return
279
+ */
280
+ @POST
281
+ @Path("/check")
282
+ @Produces({ MediaType.APPLICATION_JSON })
283
+ public Response check(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token, @QueryParam("token") String token2) {
284
+ if (token == null) {
285
+ token = token2;
286
+ }
287
+ if (token == null) {
288
+ return Response.status(Status.FORBIDDEN).build();
289
+ }
307290
308
- @GET
309
- @Path("/logout")
310
- @Produces({
311
- MediaType.APPLICATION_JSON
312
- })
313
- public Response logout(@Context HttpServletRequest request) {
314
- request.getSession().invalidate();
315
- return Response.ok().build();
316
- }
291
+ LOG.info("Token : " + token);
292
+ String user = tokenHelper.extractUserFromToken(token);
293
+ LOG.info("Token user: " + user);
294
+ Date date = tokenHelper.extractDateCreationFromToken(token);
295
+ LOG.info("Token date: " + date);
296
+ boolean valid = tokenHelper.isTokenValid(token);
297
+
298
+ LOG.info("Is Token valid: " + valid);
299
+
300
+ return Response.ok(Utils.createMap("valid", true, "user", user, "date", date, "token", token)).build();
301
+ }
302
+
303
+ @GET
304
+ @Path("/logout")
305
+ @Produces({ MediaType.APPLICATION_JSON })
306
+ public Response logout(@Context HttpServletRequest request) {
307
+ request.getSession().invalidate();
308
+ return Response.ok().build();
309
+ }
317310 }