From c4d513ca26fe80946a5d90264de5d8e13e4ea974 Mon Sep 17 00:00:00 2001
From: rsanchez <rsanchez@curisit.net>
Date: Thu, 23 Oct 2014 17:21:24 +0000
Subject: [PATCH] #2021 feature - Added pack actions in server and in frontend

---
 securis/src/main/java/net/curisit/securis/services/LicenseResource.java |  115 +++++++++++++++++++++++++++++++++++++++++++++------------
 1 files changed, 91 insertions(+), 24 deletions(-)

diff --git a/securis/src/main/java/net/curisit/securis/services/LicenseResource.java b/securis/src/main/java/net/curisit/securis/services/LicenseResource.java
index 93192c7..351500f 100644
--- a/securis/src/main/java/net/curisit/securis/services/LicenseResource.java
+++ b/securis/src/main/java/net/curisit/securis/services/LicenseResource.java
@@ -45,6 +45,7 @@
 import net.curisit.securis.db.LicenseStatus;
 import net.curisit.securis.db.Pack;
 import net.curisit.securis.db.PackMetadata;
+import net.curisit.securis.db.PackStatus;
 import net.curisit.securis.db.User;
 import net.curisit.securis.security.BasicSecurityContext;
 import net.curisit.securis.security.Securable;
@@ -56,6 +57,7 @@
 import net.curisit.securis.utils.TokenHelper;
 
 import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.ObjectUtils;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;
 
@@ -158,7 +160,7 @@
         }
         if (License.Status.isActionValid(License.Action.DOWNLOAD, lic.getStatus())) {
             LOG.error("License with id {} is not active, so It can not downloaded", licId, bsc.getUserPrincipal());
-            throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License is not active, so It can not be downloaded");
+            throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "License is not active, so It can not be downloaded");
         }
         em.persist(createLicenseHistoryAction(lic, getUser(bsc, em), LicenseHistory.Actions.DOWNLOAD));
         return Response
@@ -193,6 +195,15 @@
             LOG.error("License with id {} can not be activated from current license status", licId);
             throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License with id " + licId
                     + " can not be activated from the current license status");
+        }
+        validateRequestData(lic.getPack(), lic.getRequestData());
+
+        License existingLicense = License.findLicenseByRequestData(lic.getRequestData(), em);
+        if (existingLicense != null) {
+            return Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE)
+                    .header(DefaultExceptionHandler.ERROR_CODE_MESSAGE_HEADER, ErrorCodes.DUPLICATED_REQUEST_DATA)
+                    .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "There is already an active license for current request data")
+                    .type(MediaType.APPLICATION_JSON).entity(existingLicense).build();
         }
 
         lic.setStatus(LicenseStatus.ACTIVE);
@@ -291,10 +302,11 @@
         }
 
         lic.setStatus(LicenseStatus.CANCELLED);
+        lic.setCancelledById(bsc.getUserPrincipal().getName());
         lic.setModificationTimestamp(new Date());
         em.persist(lic);
 
-        em.persist(createLicenseHistoryAction(lic, getUser(bsc, em), LicenseHistory.Actions.CANCEL, "Cancelation reason: " + reason));
+        em.persist(createLicenseHistoryAction(lic, getUser(bsc, em), LicenseHistory.Actions.CANCEL, "Cancellation reason: " + reason));
         return Response.ok(lic).build();
     }
 
@@ -321,11 +333,22 @@
                 LOG.error("License for pack with id {} can not be created by user {}", pack.getId(), bsc.getUserPrincipal());
                 throw new SeCurisServiceException(ErrorCodes.UNAUTHORIZED_ACCESS, "Unathorized action on pack license");
             }
+            if (pack.getStatus() != PackStatus.ACTIVE) {
+                LOG.error("Current pack, {}, is not active so licenses cannot be created", pack.getId());
+                throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "Current pack is not active so licenses cannot be created");
+            }
         }
 
         User createdBy = getUser(bsc.getUserPrincipal().getName(), em);
 
         if (lic.getRequestData() != null) {
+            License existingLicense = License.findLicenseByRequestData(lic.getRequestData(), em);
+            if (existingLicense != null) {
+                return Response.status(DefaultExceptionHandler.DEFAULT_APP_ERROR_STATUS_CODE)
+                        .header(DefaultExceptionHandler.ERROR_CODE_MESSAGE_HEADER, ErrorCodes.DUPLICATED_REQUEST_DATA)
+                        .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "There is already an active license for current request data")
+                        .type(MediaType.APPLICATION_JSON).entity(existingLicense).build();
+            }
             SignedLicenseBean signedLicense = generateLicense(lic, em);
             // If user provide a request data the license status is passed
             // directly to ACTIVE
@@ -338,7 +361,7 @@
                 lic.setLicenseData(JsonUtils.toJSON(signedLicense));
             } catch (SeCurisException e) {
                 LOG.error("Error generaing license JSON", e);
-                throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generaing license JSON");
+                throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generating license JSON");
             }
         } else {
             lic.setStatus(LicenseStatus.CREATED);
@@ -387,6 +410,9 @@
      * @throws SeCurisServiceException
      */
     private RequestBean validateRequestData(Pack pack, String requestData) throws SeCurisServiceException {
+        if (requestData == null) {
+            throw new SeCurisServiceException(ErrorCodes.INVALID_REQUEST_DATA, "Request data is empty");
+        }
         RequestBean rb = null;
         try {
             rb = JsonUtils.json2object(requestData, RequestBean.class);
@@ -422,27 +448,32 @@
         EntityManager em = emProvider.get();
 
         License currentLicense = getCurrentLicense(licId, bsc, em);
-
-        currentLicense.setCode(lic.getCode());
+        currentLicense.setComments(lic.getComments());
         currentLicense.setFullName(lic.getFullName());
         currentLicense.setEmail(lic.getEmail());
-        if (lic.getRequestData() != null && currentLicense.getStatus() == LicenseStatus.CREATED) {
-            SignedLicenseBean signedLicense = generateLicense(lic, em);
-            lic.setStatus(LicenseStatus.ACTIVE);
-            try {
-                // Next line is necessary to normalize the String that contains
-                // the request.
-                lic.setRequestData(JsonUtils.toJSON((RequestBean) signedLicense));
-                if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
-                    throw new SeCurisServiceException(ErrorCodes.BLOCKED_REQUEST_DATA, "Given request data is blocked and cannot be activate");
+
+        if (currentLicense.getStatus() == LicenseStatus.CREATED && !ObjectUtils.equals(currentLicense.getReqDataHash(), lic.getReqDataHash())) {
+            if (lic.getRequestData() != null) {
+                SignedLicenseBean signedLicense = generateLicense(lic, em);
+                try {
+                    // Next line is necessary to normalize the String that
+                    // contains
+                    // the request.
+                    lic.setRequestData(JsonUtils.toJSON((RequestBean) signedLicense));
+                    if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
+                        throw new SeCurisServiceException(ErrorCodes.BLOCKED_REQUEST_DATA, "Given request data is blocked and cannot be used again");
+                    }
+                    lic.setLicenseData(JsonUtils.toJSON(signedLicense));
+                } catch (SeCurisException e) {
+                    LOG.error("Error generaing license JSON", e);
+                    throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generaing license JSON");
                 }
-                lic.setLicenseData(JsonUtils.toJSON(signedLicense));
-            } catch (SeCurisException e) {
-                LOG.error("Error generaing license JSON", e);
-                throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generaing license JSON");
+            } else {
+                // This set method could pass a null value
+                currentLicense.setRequestData(null);
             }
-            currentLicense.setRequestData(lic.getRequestData());
         }
+
         currentLicense.setModificationTimestamp(new Date());
         em.persist(currentLicense);
         em.persist(createLicenseHistoryAction(lic, getUser(bsc, em), LicenseHistory.Actions.MODIFY));
@@ -462,17 +493,30 @@
         EntityManager em = emProvider.get();
         License lic = getCurrentLicense(licId, bsc, em);
 
-        if (lic.getStatus() != LicenseStatus.CANCELLED || lic.getStatus() != LicenseStatus.CREATED) {
+        if (License.Status.isActionValid(License.Action.DELETE, lic.getStatus())) {
             LOG.error("License {} can not be deleted with status {}", lic.getCode(), lic.getStatus());
-            return Response.status(Status.FORBIDDEN)
-                    .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License can not be deleted in current status").build();
+            throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "License can not be deleted in current status: " + lic.getStatus().name());
+        }
+        if (lic.getStatus() == LicenseStatus.CANCELLED) {
+            // If license is removed and it's blocked then the blocked request
+            // should be removed, that is,
+            // the license deletion will unblock the request data
+            TypedQuery<License> query = em.createNamedQuery("list-licenses-by-req-data", License.class);
+            query.setParameter("hash", lic.getReqDataHash());
+            List<License> list = query.getResultList();
+            if (list == null || list.size() == 0) {
+                BlockedRequest br = em.find(BlockedRequest.class, lic.getReqDataHash());
+                if (br != null) {
+                    em.remove(br);
+                }
+            }
         }
 
         em.remove(lic);
         return Response.ok(Utils.createMap("success", true, "id", licId)).build();
     }
 
-    @DELETE
+    @POST
     @Path("/{licId}/block")
     @Transactional
     @Securable
@@ -484,7 +528,7 @@
         EntityManager em = emProvider.get();
         License lic = getCurrentLicense(licId, bsc, em);
 
-        if (lic.getStatus() != LicenseStatus.CANCELLED) {
+        if (!License.Status.isActionValid(License.Action.BLOCK, lic.getStatus())) {
             LOG.error("License can only be blocked in CANCELLED status, current: {}", lic.getStatus().name());
             throw new SeCurisServiceException(ErrorCodes.WRONG_STATUS, "License can only be blocked in CANCELLED status");
         }
@@ -502,6 +546,29 @@
         return Response.ok(Utils.createMap("success", true, "id", licId)).build();
     }
 
+    @POST
+    @Path("/{licId}/unblock")
+    @Transactional
+    @Securable
+    @Produces({
+        MediaType.APPLICATION_JSON
+    })
+    public Response unblock(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
+        LOG.info("Unblocking license with id: {}", licId);
+        EntityManager em = emProvider.get();
+        License lic = getCurrentLicense(licId, bsc, em);
+
+        if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
+            BlockedRequest blockedReq = em.find(BlockedRequest.class, lic.getReqDataHash());
+            em.remove(blockedReq);
+            em.persist(createLicenseHistoryAction(lic, getUser(bsc, em), LicenseHistory.Actions.UNBLOCK));
+        } else {
+            LOG.info("Request data for license {} is NOT blocked", licId);
+        }
+
+        return Response.ok(Utils.createMap("success", true, "id", licId)).build();
+    }
+
     private License getCurrentLicense(Integer licId, BasicSecurityContext bsc, EntityManager em) throws SeCurisServiceException {
         if (licId == null || "".equals(licId)) {
             LOG.error("License ID is mandatory");

--
Gitblit v1.3.2