rsanchez
2016-04-21 c5a690c83a7c45d39fdfa635f1d22dfe5809f347
#0 fix - Custom error if current license has been deleted
1 files modified
changed files
securis/src/main/java/net/curisit/securis/services/ApiResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/ApiResource.java
....@@ -17,6 +17,11 @@
1717 import javax.ws.rs.core.MediaType;
1818 import javax.ws.rs.core.Response;
1919
20
+import org.apache.commons.lang.time.DateUtils;
21
+import org.apache.logging.log4j.LogManager;
22
+import org.apache.logging.log4j.Logger;
23
+import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
24
+
2025 import net.curisit.securis.LicenseGenerator;
2126 import net.curisit.securis.LicenseManager;
2227 import net.curisit.securis.SeCurisException;
....@@ -41,11 +46,6 @@
4146 import net.curisit.securis.utils.SignatureHelper;
4247 import net.curisit.securis.utils.TokenHelper;
4348
44
-import org.apache.commons.lang.time.DateUtils;
45
-import org.apache.logging.log4j.LogManager;
46
-import org.apache.logging.log4j.Logger;
47
-import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
48
-
4949 /**
5050 * External API to be accessed by third parties
5151 *
....@@ -54,445 +54,427 @@
5454 @Path("/api")
5555 public class ApiResource {
5656
57
- private static final Logger LOG = LogManager.getLogger(ApiResource.class);
57
+ private static final Logger LOG = LogManager.getLogger(ApiResource.class);
5858
59
- @Inject
60
- TokenHelper tokenHelper;
59
+ @Inject
60
+ TokenHelper tokenHelper;
6161
62
- @Inject
63
- private LicenseHelper licenseHelper;
62
+ @Inject
63
+ private LicenseHelper licenseHelper;
6464
65
- @Context
66
- EntityManager em;
65
+ @Context
66
+ EntityManager em;
6767
68
- @Inject
69
- LicenseGenerator licenseGenerator;
68
+ @Inject
69
+ LicenseGenerator licenseGenerator;
7070
71
- public static final String API_CLIENT_USERNAME = "_client";
71
+ public static final String API_CLIENT_USERNAME = "_client";
7272
73
- public ApiResource() {
74
- }
73
+ public ApiResource() {
74
+ }
7575
76
- /**
77
- *
78
- * @return Simple text message to check API status
79
- */
80
- @GET
81
- @Path("/")
82
- @Produces({
83
- MediaType.TEXT_PLAIN
84
- })
85
- public Response index() {
86
- return Response.ok("SeCuris API. Date: " + new Date()).build();
87
- }
76
+ /**
77
+ *
78
+ * @return Simple text message to check API status
79
+ */
80
+ @GET
81
+ @Path("/")
82
+ @Produces({ MediaType.TEXT_PLAIN })
83
+ public Response index() {
84
+ return Response.ok("SeCuris API. Date: " + new Date()).build();
85
+ }
8886
89
- /**
90
- *
91
- * @return Simple text message to check API status
92
- */
93
- @GET
94
- @Path("/ping")
95
- @Produces({
96
- MediaType.APPLICATION_JSON
97
- })
98
- public Response ping() {
99
- StatusBean status = new StatusBean();
100
- status.setDate(new Date());
101
- status.setMessage(LicenseManager.PING_MESSAGE);
102
- return Response.ok(status).build();
103
- }
87
+ /**
88
+ *
89
+ * @return Simple text message to check API status
90
+ */
91
+ @GET
92
+ @Path("/ping")
93
+ @Produces({ MediaType.APPLICATION_JSON })
94
+ public Response ping() {
95
+ StatusBean status = new StatusBean();
96
+ status.setDate(new Date());
97
+ status.setMessage(LicenseManager.PING_MESSAGE);
98
+ return Response.ok(status).build();
99
+ }
104100
105
- /**
106
- * Request a new license file based in a RequestBean object sent as
107
- * parameter
108
- *
109
- * @param mpfdi
110
- * @param bsc
111
- * @return
112
- * @throws IOException
113
- * @throws SeCurisServiceException
114
- */
115
- @POST
116
- @Path("/request")
117
- @Consumes(MediaType.APPLICATION_JSON)
118
- @Securable
119
- @Produces({
120
- MediaType.APPLICATION_JSON
121
- })
122
- @EnsureTransaction
123
- public Response createFromRequest(RequestBean request, @HeaderParam(LicenseManager.HEADER_LICENSE_NAME_OR_REFERENCE) String nameOrReference,
124
- @HeaderParam(LicenseManager.HEADER_LICENSE_EMAIL) String userEmail) throws IOException, SeCurisServiceException, SeCurisException {
125
- LOG.info("Request to get license: {}", request);
126
- SignedLicenseBean lic = createLicense(request, em, nameOrReference, userEmail);
101
+ /**
102
+ * Request a new license file based in a RequestBean object sent as
103
+ * parameter
104
+ *
105
+ * @param mpfdi
106
+ * @param bsc
107
+ * @return
108
+ * @throws IOException
109
+ * @throws SeCurisServiceException
110
+ */
111
+ @POST
112
+ @Path("/request")
113
+ @Consumes(MediaType.APPLICATION_JSON)
114
+ @Securable
115
+ @Produces({ MediaType.APPLICATION_JSON })
116
+ @EnsureTransaction
117
+ public Response createFromRequest(RequestBean request, @HeaderParam(LicenseManager.HEADER_LICENSE_NAME_OR_REFERENCE) String nameOrReference,
118
+ @HeaderParam(LicenseManager.HEADER_LICENSE_EMAIL) String userEmail) throws IOException, SeCurisServiceException, SeCurisException {
119
+ LOG.info("Request to get license: {}", request);
120
+ SignedLicenseBean lic = createLicense(request, em, nameOrReference, userEmail);
127121
128
- return Response.ok(lic).build();
129
- }
122
+ return Response.ok(lic).build();
123
+ }
130124
131
- /**
132
- * Returns a License file in JSON format from an uploaded Request file
133
- *
134
- * @param mpfdi
135
- * @param bsc
136
- * @return
137
- * @throws IOException
138
- * @throws SeCurisServiceException
139
- * @throws SeCurisException
140
- */
141
- @POST
142
- @Path("/request")
143
- @Consumes(MediaType.MULTIPART_FORM_DATA)
144
- @Securable
145
- @Produces({
146
- MediaType.APPLICATION_JSON
147
- })
148
- @EnsureTransaction
149
- @SuppressWarnings("unchecked")
150
- public Response createFromRequestFile(MultipartFormDataInput mpfdi,
151
- @HeaderParam(LicenseManager.HEADER_LICENSE_NAME_OR_REFERENCE) String nameOrReference,
152
- @HeaderParam(LicenseManager.HEADER_LICENSE_EMAIL) String userEmail) throws IOException, SeCurisServiceException, SeCurisException {
153
- RequestBean req = new RequestBean();
154
- req.setAppCode(mpfdi.getFormDataPart("appCode", String.class, null));
155
- req.setActivationCode(mpfdi.getFormDataPart("activationCode", String.class, null));
156
- req.setPackCode(mpfdi.getFormDataPart("packCode", String.class, null));
157
- req.setLicenseTypeCode(mpfdi.getFormDataPart("licenseTypeCode", String.class, null));
158
- req.setCustomerCode(mpfdi.getFormDataPart("customerCode", String.class, null));
159
- req.setArch(mpfdi.getFormDataPart("arch", String.class, null));
160
- req.setCrcLogo(mpfdi.getFormDataPart("crcLogo", String.class, null));
161
- req.setMacAddresses(mpfdi.getFormDataPart("macAddresses", List.class, null));
162
- req.setOsName(mpfdi.getFormDataPart("osName", String.class, null));
125
+ /**
126
+ * Returns a License file in JSON format from an uploaded Request file
127
+ *
128
+ * @param mpfdi
129
+ * @param bsc
130
+ * @return
131
+ * @throws IOException
132
+ * @throws SeCurisServiceException
133
+ * @throws SeCurisException
134
+ */
135
+ @POST
136
+ @Path("/request")
137
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
138
+ @Securable
139
+ @Produces({ MediaType.APPLICATION_JSON })
140
+ @EnsureTransaction
141
+ @SuppressWarnings("unchecked")
142
+ public Response createFromRequestFile(MultipartFormDataInput mpfdi, @HeaderParam(LicenseManager.HEADER_LICENSE_NAME_OR_REFERENCE) String nameOrReference,
143
+ @HeaderParam(LicenseManager.HEADER_LICENSE_EMAIL) String userEmail) throws IOException, SeCurisServiceException, SeCurisException {
144
+ RequestBean req = new RequestBean();
145
+ req.setAppCode(mpfdi.getFormDataPart("appCode", String.class, null));
146
+ req.setActivationCode(mpfdi.getFormDataPart("activationCode", String.class, null));
147
+ req.setPackCode(mpfdi.getFormDataPart("packCode", String.class, null));
148
+ req.setLicenseTypeCode(mpfdi.getFormDataPart("licenseTypeCode", String.class, null));
149
+ req.setCustomerCode(mpfdi.getFormDataPart("customerCode", String.class, null));
150
+ req.setArch(mpfdi.getFormDataPart("arch", String.class, null));
151
+ req.setCrcLogo(mpfdi.getFormDataPart("crcLogo", String.class, null));
152
+ req.setMacAddresses(mpfdi.getFormDataPart("macAddresses", List.class, null));
153
+ req.setOsName(mpfdi.getFormDataPart("osName", String.class, null));
163154
164
- return createFromRequest(req, nameOrReference, userEmail);
165
- }
155
+ return createFromRequest(req, nameOrReference, userEmail);
156
+ }
166157
167
- /**
168
- * Create a new License file based in a previous one
169
- *
170
- * @param request
171
- * @param bsc
172
- * @return
173
- * @throws IOException
174
- * @throws SeCurisServiceException
175
- * @throws SeCurisException
176
- */
177
- @POST
178
- @Path("/renew")
179
- @Consumes(MediaType.APPLICATION_JSON)
180
- @Securable
181
- @Produces({
182
- MediaType.APPLICATION_JSON
183
- })
184
- @EnsureTransaction
185
- public Response renewFromPreviousLicense(LicenseBean previousLic, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException,
186
- SeCurisException {
187
- LOG.info("Renew license: {}", previousLic);
158
+ /**
159
+ * Create a new License file based in a previous one
160
+ *
161
+ * @param request
162
+ * @param bsc
163
+ * @return
164
+ * @throws IOException
165
+ * @throws SeCurisServiceException
166
+ * @throws SeCurisException
167
+ */
168
+ @POST
169
+ @Path("/renew")
170
+ @Consumes(MediaType.APPLICATION_JSON)
171
+ @Securable
172
+ @Produces({ MediaType.APPLICATION_JSON })
173
+ @EnsureTransaction
174
+ public Response renewFromPreviousLicense(LicenseBean previousLic, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException, SeCurisException {
175
+ LOG.info("Renew license: {}", previousLic);
188176
189
- if (previousLic.getExpirationDate().after(DateUtils.addMonths(new Date(), 1))) {
190
- throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "The license is still valid, not ready for renew");
191
- }
177
+ if (previousLic.getExpirationDate().after(DateUtils.addMonths(new Date(), 1))) {
178
+ throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "The license is still valid, not ready for renew");
179
+ }
192180
193
- // EntityManager em = emProvider.get();
194
- License lic = License.findLicenseByCode(previousLic.getLicenseCode(), em);
195
- if (lic.getStatus() != LicenseStatus.ACTIVE) {
196
- throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "Only licenses with status 'Active' can be renew");
197
- }
181
+ // EntityManager em = emProvider.get();
182
+ License lic = License.findLicenseByCode(previousLic.getLicenseCode(), em);
183
+ if (lic == null) {
184
+ throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "Current license is missing in DB");
185
+ }
198186
199
- SignedLicenseBean signedLic = renewLicense(previousLic, em);
200
- LOG.info("Renewed license code: {}, until: {}", signedLic.getLicenseCode(), signedLic.getExpirationDate());
187
+ if (lic.getStatus() != LicenseStatus.ACTIVE) {
188
+ throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "Only licenses with status 'Active' can be renew");
189
+ }
201190
202
- return Response.ok(signedLic).build();
203
- }
191
+ SignedLicenseBean signedLic = renewLicense(previousLic, em);
192
+ LOG.info("Renewed license code: {}, until: {}", signedLic.getLicenseCode(), signedLic.getExpirationDate());
204193
205
- /**
206
- * License validation on server side, in this case we validate that the
207
- * current licenses has not been cancelled.
208
- *
209
- * @param currentLic
210
- * @param bsc
211
- * @return
212
- * @throws IOException
213
- * @throws SeCurisServiceException
214
- * @throws SeCurisException
215
- */
216
- @POST
217
- @Path("/validate")
218
- @Consumes(MediaType.APPLICATION_JSON)
219
- @Securable
220
- @Produces({
221
- MediaType.APPLICATION_JSON
222
- })
223
- @EnsureTransaction
224
- public Response validate(LicenseBean currentLic, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException, SeCurisException {
225
- LOG.info("Validate license: {}", currentLic);
194
+ return Response.ok(signedLic).build();
195
+ }
226196
227
- if (currentLic.getExpirationDate().before(new Date())) {
228
- throw new SeCurisServiceException(ErrorCodes.LICENSE_IS_EXPIRED, "The license is expired");
229
- }
197
+ /**
198
+ * License validation on server side, in this case we validate that the
199
+ * current licenses has not been cancelled.
200
+ *
201
+ * @param currentLic
202
+ * @param bsc
203
+ * @return
204
+ * @throws IOException
205
+ * @throws SeCurisServiceException
206
+ * @throws SeCurisException
207
+ */
208
+ @POST
209
+ @Path("/validate")
210
+ @Consumes(MediaType.APPLICATION_JSON)
211
+ @Securable
212
+ @Produces({ MediaType.APPLICATION_JSON })
213
+ @EnsureTransaction
214
+ public Response validate(LicenseBean currentLic, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException, SeCurisException {
215
+ LOG.info("Validate license: {}", currentLic);
230216
231
- try {
232
- SignatureHelper.getInstance().validateSignature(currentLic);
233
- } catch (SeCurisException ex) {
234
- throw new SeCurisServiceException(ErrorCodes.LICENSE_DATA_IS_NOT_VALID, "The license signature is not valid");
235
- }
236
- licenseHelper.assertLicenseStatusIsActive(currentLic, em);
217
+ if (currentLic.getExpirationDate().before(new Date())) {
218
+ throw new SeCurisServiceException(ErrorCodes.LICENSE_IS_EXPIRED, "The license is expired");
219
+ }
237220
238
- return Response.ok(currentLic).build();
239
- }
221
+ try {
222
+ SignatureHelper.getInstance().validateSignature(currentLic);
223
+ } catch (SeCurisException ex) {
224
+ throw new SeCurisServiceException(ErrorCodes.LICENSE_DATA_IS_NOT_VALID, "The license signature is not valid");
225
+ }
226
+ licenseHelper.assertLicenseStatusIsActive(currentLic, em);
240227
241
- /**
242
- * Returns a new License file in JSON format based in a previous license
243
- * There is 2 /renew services with json input and with upload file
244
- *
245
- * @param mpfdi
246
- * @param bsc
247
- * @return
248
- * @throws IOException
249
- * @throws SeCurisServiceException
250
- * @throws SeCurisException
251
- */
252
- @POST
253
- @Path("/renew")
254
- @Consumes(MediaType.MULTIPART_FORM_DATA)
255
- @Securable
256
- @Produces({
257
- MediaType.APPLICATION_JSON
258
- })
259
- @EnsureTransaction
260
- @SuppressWarnings("unchecked")
261
- public Response renewFromLicenseFile(MultipartFormDataInput mpfdi, @Context BasicSecurityContext bsc) throws IOException,
262
- SeCurisServiceException, SeCurisException {
263
- LicenseBean lic = new LicenseBean();
228
+ return Response.ok(currentLic).build();
229
+ }
264230
265
- lic.setAppCode(mpfdi.getFormDataPart("appCode", String.class, null));
266
- lic.setActivationCode(mpfdi.getFormDataPart("activationName", String.class, null));
267
- lic.setAppName(mpfdi.getFormDataPart("appName", String.class, null));
268
- lic.setArch(mpfdi.getFormDataPart("arch", String.class, null));
269
- lic.setCrcLogo(mpfdi.getFormDataPart("crcLogo", String.class, null));
270
- lic.setPackCode(mpfdi.getFormDataPart("packCode", String.class, null));
271
- lic.setLicenseTypeCode(mpfdi.getFormDataPart("licenseCode", String.class, null));
272
- lic.setCustomerCode(mpfdi.getFormDataPart("customerCode", String.class, null));
273
- lic.setMacAddresses(mpfdi.getFormDataPart("macAddresses", List.class, null));
274
- lic.setOsName(mpfdi.getFormDataPart("osName", String.class, null));
275
- lic.setExpirationDate(mpfdi.getFormDataPart("expirationDate", Date.class, null));
276
- LOG.info("Lic expires at: {}", lic.getExpirationDate());
277
- if (lic.getExpirationDate().after(DateUtils.addMonths(new Date(), 1))) {
278
- throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "The license is still valid, not ready for renew");
279
- }
231
+ /**
232
+ * Returns a new License file in JSON format based in a previous license
233
+ * There is 2 /renew services with json input and with upload file
234
+ *
235
+ * @param mpfdi
236
+ * @param bsc
237
+ * @return
238
+ * @throws IOException
239
+ * @throws SeCurisServiceException
240
+ * @throws SeCurisException
241
+ */
242
+ @POST
243
+ @Path("/renew")
244
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
245
+ @Securable
246
+ @Produces({ MediaType.APPLICATION_JSON })
247
+ @EnsureTransaction
248
+ @SuppressWarnings("unchecked")
249
+ public Response renewFromLicenseFile(MultipartFormDataInput mpfdi, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException, SeCurisException {
250
+ LicenseBean lic = new LicenseBean();
280251
281
- return renewFromPreviousLicense(lic, bsc);
282
- }
252
+ lic.setAppCode(mpfdi.getFormDataPart("appCode", String.class, null));
253
+ lic.setActivationCode(mpfdi.getFormDataPart("activationName", String.class, null));
254
+ lic.setAppName(mpfdi.getFormDataPart("appName", String.class, null));
255
+ lic.setArch(mpfdi.getFormDataPart("arch", String.class, null));
256
+ lic.setCrcLogo(mpfdi.getFormDataPart("crcLogo", String.class, null));
257
+ lic.setPackCode(mpfdi.getFormDataPart("packCode", String.class, null));
258
+ lic.setLicenseTypeCode(mpfdi.getFormDataPart("licenseCode", String.class, null));
259
+ lic.setCustomerCode(mpfdi.getFormDataPart("customerCode", String.class, null));
260
+ lic.setMacAddresses(mpfdi.getFormDataPart("macAddresses", List.class, null));
261
+ lic.setOsName(mpfdi.getFormDataPart("osName", String.class, null));
262
+ lic.setExpirationDate(mpfdi.getFormDataPart("expirationDate", Date.class, null));
263
+ LOG.info("Lic expires at: {}", lic.getExpirationDate());
264
+ if (lic.getExpirationDate().after(DateUtils.addMonths(new Date(), 1))) {
265
+ throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "The license is still valid, not ready for renew");
266
+ }
283267
284
- private SignedLicenseBean renewLicense(RequestBean req, EntityManager em) throws SeCurisServiceException {
285
- return renewLicense(req, em);
286
- }
268
+ return renewFromPreviousLicense(lic, bsc);
269
+ }
287270
288
- /**
289
- * Creates a new signed license from request data or from previous license
290
- * if It's a renew
291
- *
292
- * @param req
293
- * @param em
294
- * @param renew
295
- * @return
296
- * @throws SeCurisServiceException
297
- */
298
- private SignedLicenseBean createLicense(RequestBean req, EntityManager em, String nameOrReference, String email) throws SeCurisServiceException {
299
- License lic = null;
271
+ private SignedLicenseBean renewLicense(RequestBean req, EntityManager em) throws SeCurisServiceException {
272
+ return renewLicense(req, em);
273
+ }
300274
301
- if (req.getActivationCode() != null) {
302
- lic = License.findLicenseByActivationCode(req.getActivationCode(), em);
303
- if (lic == null) {
304
- throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The given activation code is invalid: " + req.getActivationCode());
305
- }
306
- if (lic.getStatus() == LicenseStatus.ACTIVE) {
307
- RequestBean initialRequest;
308
- try {
309
- initialRequest = JsonUtils.json2object(lic.getRequestData(), RequestBean.class);
310
- if (!req.match(initialRequest)) {
311
- throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "There is already an active license for given activation code: "
312
- + req.getActivationCode());
313
- } else {
314
- return JsonUtils.json2object(lic.getLicenseData(), SignedLicenseBean.class);
315
- }
316
- } catch (SeCurisException e) {
317
- LOG.error("Error getting existing license", e);
318
- throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Original request is wrong");
319
- }
320
- } else {
321
- if (req.getAppCode() != null && !req.getAppCode().equals(lic.getPack().getLicenseType().getApplication().getCode())) {
322
- LOG.error("Activation code {} belongs to app: {} but was sent by: {}", req.getActivationCode(), lic.getPack().getLicenseType()
323
- .getApplication().getCode(), req.getAppCode());
324
- throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The given activation code belongs to a different application: "
325
- + req.getActivationCode());
326
- }
327
- }
328
- // We validate if the HW is the same, otherwise an error is
329
- // thrown
330
- } else {
331
- try {
332
- lic = License.findValidLicenseByRequestData(JsonUtils.toJSON(req), em);
333
- } catch (SeCurisException e1) {
334
- throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Request sent is not valid");
335
- }
336
- if (lic != null) {
337
- try {
338
- if (lic.getStatus() == LicenseStatus.ACTIVE || lic.getStatus() == LicenseStatus.PRE_ACTIVE) {
339
- return JsonUtils.json2object(lic.getLicenseData(), SignedLicenseBean.class);
340
- }
341
- } catch (SeCurisException e) {
342
- throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error trying to get the license bean from license code: "
343
- + lic.getCode());
344
- }
345
- } else {
346
- lic = new License();
347
- }
348
- }
275
+ /**
276
+ * Creates a new signed license from request data or from previous license
277
+ * if It's a renew
278
+ *
279
+ * @param req
280
+ * @param em
281
+ * @param renew
282
+ * @return
283
+ * @throws SeCurisServiceException
284
+ */
285
+ private SignedLicenseBean createLicense(RequestBean req, EntityManager em, String nameOrReference, String email) throws SeCurisServiceException {
286
+ License lic = null;
349287
350
- Pack pack;
351
- if (lic.getActivationCode() == null) {
352
- try {
353
- pack = em.createNamedQuery("pack-by-code", Pack.class).setParameter("code", req.getPackCode()).getSingleResult();
354
- } catch (NoResultException e) {
355
- throw new SeCurisServiceException(ErrorCodes.NOT_FOUND, "No pack found for code: " + req.getPackCode());
356
- }
288
+ if (req.getActivationCode() != null) {
289
+ lic = License.findLicenseByActivationCode(req.getActivationCode(), em);
290
+ if (lic == null) {
291
+ throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The given activation code is invalid: " + req.getActivationCode());
292
+ }
293
+ if (lic.getStatus() == LicenseStatus.ACTIVE) {
294
+ RequestBean initialRequest;
295
+ try {
296
+ initialRequest = JsonUtils.json2object(lic.getRequestData(), RequestBean.class);
297
+ if (!req.match(initialRequest)) {
298
+ throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "There is already an active license for given activation code: " + req.getActivationCode());
299
+ } else {
300
+ return JsonUtils.json2object(lic.getLicenseData(), SignedLicenseBean.class);
301
+ }
302
+ } catch (SeCurisException e) {
303
+ LOG.error("Error getting existing license", e);
304
+ throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Original request is wrong");
305
+ }
306
+ } else {
307
+ if (req.getAppCode() != null && !req.getAppCode().equals(lic.getPack().getLicenseType().getApplication().getCode())) {
308
+ LOG.error("Activation code {} belongs to app: {} but was sent by: {}", req.getActivationCode(), lic.getPack().getLicenseType().getApplication().getCode(),
309
+ req.getAppCode());
310
+ throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The given activation code belongs to a different application: " + req.getActivationCode());
311
+ }
312
+ }
313
+ // We validate if the HW is the same, otherwise an error is
314
+ // thrown
315
+ } else {
316
+ try {
317
+ lic = License.findValidLicenseByRequestData(JsonUtils.toJSON(req), em);
318
+ } catch (SeCurisException e1) {
319
+ throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Request sent is not valid");
320
+ }
321
+ if (lic != null) {
322
+ try {
323
+ if (lic.getStatus() == LicenseStatus.ACTIVE || lic.getStatus() == LicenseStatus.PRE_ACTIVE) {
324
+ return JsonUtils.json2object(lic.getLicenseData(), SignedLicenseBean.class);
325
+ }
326
+ } catch (SeCurisException e) {
327
+ throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error trying to get the license bean from license code: " + lic.getCode());
328
+ }
329
+ } else {
330
+ lic = new License();
331
+ }
332
+ }
357333
358
- if (pack.getNumAvailables() <= 0) {
359
- throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "The current pack has no licenses availables");
360
- }
361
- if (lic.getStatus() == LicenseStatus.REQUESTED && !pack.isLicensePreactivation()) {
362
- throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "Current pack doesn't allow license preactivation");
363
- }
334
+ Pack pack;
335
+ if (lic.getActivationCode() == null) {
336
+ try {
337
+ pack = em.createNamedQuery("pack-by-code", Pack.class).setParameter("code", req.getPackCode()).getSingleResult();
338
+ } catch (NoResultException e) {
339
+ throw new SeCurisServiceException(ErrorCodes.NOT_FOUND, "No pack found for code: " + req.getPackCode());
340
+ }
364341
365
- if (!req.getCustomerCode().equals(pack.getOrganization().getCode())) {
366
- throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Customer code is not valid: " + req.getCustomerCode());
367
- }
342
+ if (pack.getNumAvailables() <= 0) {
343
+ throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "The current pack has no licenses availables");
344
+ }
345
+ if (lic.getStatus() == LicenseStatus.REQUESTED && !pack.isLicensePreactivation()) {
346
+ throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "Current pack doesn't allow license preactivation");
347
+ }
368348
369
- if (!req.getLicenseTypeCode().equals(pack.getLicenseTypeCode())) {
370
- throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "License type code is not valid: "
371
- + req.getLicenseTypeCode());
372
- }
373
- } else {
374
- pack = lic.getPack();
375
- }
376
- SignedLicenseBean signedLicense;
377
- try {
378
- String licCode;
379
- if (lic.getCode() == null) {
380
- licCode = LicUtils.getLicenseCode(pack.getCode(), licenseHelper.getNextCodeSuffix(pack.getId(), em));
381
- } else {
382
- licCode = lic.getCode();
383
- }
384
- Date expirationDate = licenseHelper.getExpirationDateFromPack(pack, lic.getActivationCode() == null);
349
+ if (!req.getCustomerCode().equals(pack.getOrganization().getCode())) {
350
+ throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Customer code is not valid: " + req.getCustomerCode());
351
+ }
385352
386
- LicenseBean lb = licenseGenerator.generateLicense(req, licenseHelper.extractPackMetadata(pack.getMetadata()), expirationDate, licCode,
387
- pack.getAppName());
388
- signedLicense = new SignedLicenseBean(lb);
389
- } catch (SeCurisException e) {
390
- throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Error generating license: " + e.toString());
391
- }
392
- try {
393
- lic.setRequestData(JsonUtils.toJSON(req));
394
- if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
395
- throw new SeCurisServiceException(ErrorCodes.BLOCKED_REQUEST_DATA, "Given request data is blocked and cannot be activated");
396
- }
397
- lic.setLicenseData(JsonUtils.toJSON(signedLicense));
398
- } catch (SeCurisException e) {
399
- LOG.error("Error generating license JSON", e);
400
- throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generating license JSON");
401
- }
353
+ if (!req.getLicenseTypeCode().equals(pack.getLicenseTypeCode())) {
354
+ throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "License type code is not valid: " + req.getLicenseTypeCode());
355
+ }
356
+ } else {
357
+ pack = lic.getPack();
358
+ }
359
+ SignedLicenseBean signedLicense;
360
+ try {
361
+ String licCode;
362
+ if (lic.getCode() == null) {
363
+ licCode = LicUtils.getLicenseCode(pack.getCode(), licenseHelper.getNextCodeSuffix(pack.getId(), em));
364
+ } else {
365
+ licCode = lic.getCode();
366
+ }
367
+ Date expirationDate = licenseHelper.getExpirationDateFromPack(pack, lic.getActivationCode() == null);
402368
403
- lic.setModificationTimestamp(new Date());
404
- lic.setExpirationDate(signedLicense.getExpirationDate());
405
- User user = em.find(User.class, API_CLIENT_USERNAME);
406
- if (lic.getStatus() != LicenseStatus.REQUESTED) {
407
- lic.setPack(pack);
408
- lic.setCreatedBy(user);
409
- lic.setCreationTimestamp(new Date());
410
- if (lic.getActivationCode() != null) {
411
- lic.setStatus(LicenseStatus.ACTIVE);
412
- } else {
413
- lic.setStatus(pack.isLicensePreactivation() ? LicenseStatus.PRE_ACTIVE : LicenseStatus.REQUESTED);
414
- }
415
- lic.setCode(signedLicense.getLicenseCode());
416
- lic.setCodeSuffix(LicUtils.getLicenseCodeSuffix(signedLicense.getLicenseCode()));
417
- if (lic.getEmail() == null || "".equals(lic.getEmail())) {
418
- lic.setEmail(email);
419
- }
420
- if (lic.getFullName() == null || "".equals(lic.getFullName())) {
421
- lic.setFullName(nameOrReference);
422
- }
423
- if (lic.getId() != null) {
424
- em.merge(lic);
425
- } else {
426
- em.persist(lic);
427
- }
428
- em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.CREATE));
429
- if (lic.getActivationCode() != null) {
430
- em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.ACTIVATE, "Activated by code on creation"));
431
- } else {
432
- if (pack.isLicensePreactivation()) {
433
- em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.PRE_ACTIVATE, "Pre-activated on creation"));
434
- } else {
435
- LOG.warn("License ({}) created, but the pack doesn't allow preactivation", lic.getCode());
436
- throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "Current pack doesn't allow license preactivation");
437
- }
438
- }
439
- } else {
440
- lic.setStatus(LicenseStatus.PRE_ACTIVE);
441
- em.merge(lic);
442
- em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.PRE_ACTIVATE, "Pre-activated after request"));
443
- }
369
+ LicenseBean lb = licenseGenerator.generateLicense(req, licenseHelper.extractPackMetadata(pack.getMetadata()), expirationDate, licCode, pack.getAppName());
370
+ signedLicense = new SignedLicenseBean(lb);
371
+ } catch (SeCurisException e) {
372
+ throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Error generating license: " + e.toString());
373
+ }
374
+ try {
375
+ lic.setRequestData(JsonUtils.toJSON(req));
376
+ if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
377
+ throw new SeCurisServiceException(ErrorCodes.BLOCKED_REQUEST_DATA, "Given request data is blocked and cannot be activated");
378
+ }
379
+ lic.setLicenseData(JsonUtils.toJSON(signedLicense));
380
+ } catch (SeCurisException e) {
381
+ LOG.error("Error generating license JSON", e);
382
+ throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generating license JSON");
383
+ }
444384
445
- return signedLicense;
446
- }
385
+ lic.setModificationTimestamp(new Date());
386
+ lic.setExpirationDate(signedLicense.getExpirationDate());
387
+ User user = em.find(User.class, API_CLIENT_USERNAME);
388
+ if (lic.getStatus() != LicenseStatus.REQUESTED) {
389
+ lic.setPack(pack);
390
+ lic.setCreatedBy(user);
391
+ lic.setCreationTimestamp(new Date());
392
+ if (lic.getActivationCode() != null) {
393
+ lic.setStatus(LicenseStatus.ACTIVE);
394
+ } else {
395
+ lic.setStatus(pack.isLicensePreactivation() ? LicenseStatus.PRE_ACTIVE : LicenseStatus.REQUESTED);
396
+ }
397
+ lic.setCode(signedLicense.getLicenseCode());
398
+ lic.setCodeSuffix(LicUtils.getLicenseCodeSuffix(signedLicense.getLicenseCode()));
399
+ if (lic.getEmail() == null || "".equals(lic.getEmail())) {
400
+ lic.setEmail(email);
401
+ }
402
+ if (lic.getFullName() == null || "".equals(lic.getFullName())) {
403
+ lic.setFullName(nameOrReference);
404
+ }
405
+ if (lic.getId() != null) {
406
+ em.merge(lic);
407
+ } else {
408
+ em.persist(lic);
409
+ }
410
+ em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.CREATE));
411
+ if (lic.getActivationCode() != null) {
412
+ em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.ACTIVATE, "Activated by code on creation"));
413
+ } else {
414
+ if (pack.isLicensePreactivation()) {
415
+ em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.PRE_ACTIVATE, "Pre-activated on creation"));
416
+ } else {
417
+ LOG.warn("License ({}) created, but the pack doesn't allow preactivation", lic.getCode());
418
+ throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "Current pack doesn't allow license preactivation");
419
+ }
420
+ }
421
+ } else {
422
+ lic.setStatus(LicenseStatus.PRE_ACTIVE);
423
+ em.merge(lic);
424
+ em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.PRE_ACTIVATE, "Pre-activated after request"));
425
+ }
447426
448
- /**
449
- * Creates a new signed license from request data or from previous license
450
- * if It's a renew
451
- *
452
- * @param req
453
- * @param em
454
- * @param renew
455
- * @return
456
- * @throws SeCurisServiceException
457
- */
458
- private SignedLicenseBean renewLicense(LicenseBean previousLicenseBean, EntityManager em) throws SeCurisServiceException {
427
+ return signedLicense;
428
+ }
459429
460
- License lic = License.findLicenseByCode(previousLicenseBean.getLicenseCode(), em);
461
- if (lic.getStatus() != LicenseStatus.ACTIVE && lic.getStatus() != LicenseStatus.PRE_ACTIVE) {
462
- throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The current license has been cancelled");
463
- }
430
+ /**
431
+ * Creates a new signed license from request data or from previous license
432
+ * if It's a renew
433
+ *
434
+ * @param req
435
+ * @param em
436
+ * @param renew
437
+ * @return
438
+ * @throws SeCurisServiceException
439
+ */
440
+ private SignedLicenseBean renewLicense(LicenseBean previousLicenseBean, EntityManager em) throws SeCurisServiceException {
464441
465
- Pack pack = lic.getPack();
466
- SignedLicenseBean signedLicense;
467
- try {
468
- String licCode = lic.getCode();
469
- Date expirationDate = licenseHelper.getExpirationDateFromPack(pack, false);
442
+ License lic = License.findLicenseByCode(previousLicenseBean.getLicenseCode(), em);
443
+ if (lic.getStatus() != LicenseStatus.ACTIVE && lic.getStatus() != LicenseStatus.PRE_ACTIVE) {
444
+ throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The current license has been cancelled");
445
+ }
470446
471
- LicenseBean lb = licenseGenerator.generateLicense(previousLicenseBean, licenseHelper.extractPackMetadata(pack.getMetadata()),
472
- expirationDate, licCode, pack.getAppName());
473
- signedLicense = new SignedLicenseBean(lb);
474
- } catch (SeCurisException e) {
475
- throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Error generating license: " + e.toString());
476
- }
477
- try {
478
- lic.setRequestData(JsonUtils.toJSON(signedLicense, RequestBean.class));
479
- if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
480
- throw new SeCurisServiceException(ErrorCodes.BLOCKED_REQUEST_DATA, "Given request data is blocked and cannot be activated");
481
- }
482
- lic.setLicenseData(JsonUtils.toJSON(signedLicense));
483
- } catch (SeCurisException e) {
484
- LOG.error("Error generating license JSON", e);
485
- throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generating license JSON");
486
- }
447
+ Pack pack = lic.getPack();
448
+ SignedLicenseBean signedLicense;
449
+ try {
450
+ String licCode = lic.getCode();
451
+ Date expirationDate = licenseHelper.getExpirationDateFromPack(pack, false);
487452
488
- lic.setModificationTimestamp(new Date());
489
- lic.setExpirationDate(signedLicense.getExpirationDate());
490
- User user = em.find(User.class, API_CLIENT_USERNAME);
453
+ LicenseBean lb = licenseGenerator.generateLicense(previousLicenseBean, licenseHelper.extractPackMetadata(pack.getMetadata()), expirationDate, licCode,
454
+ pack.getAppName());
455
+ signedLicense = new SignedLicenseBean(lb);
456
+ } catch (SeCurisException e) {
457
+ throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Error generating license: " + e.toString());
458
+ }
459
+ try {
460
+ lic.setRequestData(JsonUtils.toJSON(signedLicense, RequestBean.class));
461
+ if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
462
+ throw new SeCurisServiceException(ErrorCodes.BLOCKED_REQUEST_DATA, "Given request data is blocked and cannot be activated");
463
+ }
464
+ lic.setLicenseData(JsonUtils.toJSON(signedLicense));
465
+ } catch (SeCurisException e) {
466
+ LOG.error("Error generating license JSON", e);
467
+ throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generating license JSON");
468
+ }
491469
492
- lic.setStatus(LicenseStatus.ACTIVE);
493
- em.merge(lic);
494
- em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.RENEW));
470
+ lic.setModificationTimestamp(new Date());
471
+ lic.setExpirationDate(signedLicense.getExpirationDate());
472
+ User user = em.find(User.class, API_CLIENT_USERNAME);
495473
496
- return signedLicense;
497
- }
474
+ lic.setStatus(LicenseStatus.ACTIVE);
475
+ em.merge(lic);
476
+ em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.RENEW));
477
+
478
+ return signedLicense;
479
+ }
498480 }