From c5a690c83a7c45d39fdfa635f1d22dfe5809f347 Mon Sep 17 00:00:00 2001
From: rsanchez <rsanchez@curisit.net>
Date: Thu, 21 Apr 2016 08:06:25 +0000
Subject: [PATCH] #0 fix - Custom error if current license has been deleted

---
 securis/src/main/java/net/curisit/securis/services/ApiResource.java |  792 +++++++++++++++++++++++++++----------------------------
 1 files changed, 387 insertions(+), 405 deletions(-)

diff --git a/securis/src/main/java/net/curisit/securis/services/ApiResource.java b/securis/src/main/java/net/curisit/securis/services/ApiResource.java
index 4f3def4..26eea8a 100644
--- a/securis/src/main/java/net/curisit/securis/services/ApiResource.java
+++ b/securis/src/main/java/net/curisit/securis/services/ApiResource.java
@@ -17,6 +17,11 @@
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 
+import org.apache.commons.lang.time.DateUtils;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
+
 import net.curisit.securis.LicenseGenerator;
 import net.curisit.securis.LicenseManager;
 import net.curisit.securis.SeCurisException;
@@ -41,11 +46,6 @@
 import net.curisit.securis.utils.SignatureHelper;
 import net.curisit.securis.utils.TokenHelper;
 
-import org.apache.commons.lang.time.DateUtils;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
-
 /**
  * External API to be accessed by third parties
  * 
@@ -54,445 +54,427 @@
 @Path("/api")
 public class ApiResource {
 
-    private static final Logger LOG = LogManager.getLogger(ApiResource.class);
+	private static final Logger LOG = LogManager.getLogger(ApiResource.class);
 
-    @Inject
-    TokenHelper tokenHelper;
+	@Inject
+	TokenHelper tokenHelper;
 
-    @Inject
-    private LicenseHelper licenseHelper;
+	@Inject
+	private LicenseHelper licenseHelper;
 
-    @Context
-    EntityManager em;
+	@Context
+	EntityManager em;
 
-    @Inject
-    LicenseGenerator licenseGenerator;
+	@Inject
+	LicenseGenerator licenseGenerator;
 
-    public static final String API_CLIENT_USERNAME = "_client";
+	public static final String API_CLIENT_USERNAME = "_client";
 
-    public ApiResource() {
-    }
+	public ApiResource() {
+	}
 
-    /**
-     * 
-     * @return Simple text message to check API status
-     */
-    @GET
-    @Path("/")
-    @Produces({
-        MediaType.TEXT_PLAIN
-    })
-    public Response index() {
-        return Response.ok("SeCuris API. Date: " + new Date()).build();
-    }
+	/**
+	 * 
+	 * @return Simple text message to check API status
+	 */
+	@GET
+	@Path("/")
+	@Produces({ MediaType.TEXT_PLAIN })
+	public Response index() {
+		return Response.ok("SeCuris API. Date: " + new Date()).build();
+	}
 
-    /**
-     * 
-     * @return Simple text message to check API status
-     */
-    @GET
-    @Path("/ping")
-    @Produces({
-        MediaType.APPLICATION_JSON
-    })
-    public Response ping() {
-        StatusBean status = new StatusBean();
-        status.setDate(new Date());
-        status.setMessage(LicenseManager.PING_MESSAGE);
-        return Response.ok(status).build();
-    }
+	/**
+	 * 
+	 * @return Simple text message to check API status
+	 */
+	@GET
+	@Path("/ping")
+	@Produces({ MediaType.APPLICATION_JSON })
+	public Response ping() {
+		StatusBean status = new StatusBean();
+		status.setDate(new Date());
+		status.setMessage(LicenseManager.PING_MESSAGE);
+		return Response.ok(status).build();
+	}
 
-    /**
-     * Request a new license file based in a RequestBean object sent as
-     * parameter
-     * 
-     * @param mpfdi
-     * @param bsc
-     * @return
-     * @throws IOException
-     * @throws SeCurisServiceException
-     */
-    @POST
-    @Path("/request")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Securable
-    @Produces({
-        MediaType.APPLICATION_JSON
-    })
-    @EnsureTransaction
-    public Response createFromRequest(RequestBean request, @HeaderParam(LicenseManager.HEADER_LICENSE_NAME_OR_REFERENCE) String nameOrReference,
-            @HeaderParam(LicenseManager.HEADER_LICENSE_EMAIL) String userEmail) throws IOException, SeCurisServiceException, SeCurisException {
-        LOG.info("Request to get license: {}", request);
-        SignedLicenseBean lic = createLicense(request, em, nameOrReference, userEmail);
+	/**
+	 * Request a new license file based in a RequestBean object sent as
+	 * parameter
+	 * 
+	 * @param mpfdi
+	 * @param bsc
+	 * @return
+	 * @throws IOException
+	 * @throws SeCurisServiceException
+	 */
+	@POST
+	@Path("/request")
+	@Consumes(MediaType.APPLICATION_JSON)
+	@Securable
+	@Produces({ MediaType.APPLICATION_JSON })
+	@EnsureTransaction
+	public Response createFromRequest(RequestBean request, @HeaderParam(LicenseManager.HEADER_LICENSE_NAME_OR_REFERENCE) String nameOrReference,
+			@HeaderParam(LicenseManager.HEADER_LICENSE_EMAIL) String userEmail) throws IOException, SeCurisServiceException, SeCurisException {
+		LOG.info("Request to get license: {}", request);
+		SignedLicenseBean lic = createLicense(request, em, nameOrReference, userEmail);
 
-        return Response.ok(lic).build();
-    }
+		return Response.ok(lic).build();
+	}
 
-    /**
-     * Returns a License file in JSON format from an uploaded Request file
-     * 
-     * @param mpfdi
-     * @param bsc
-     * @return
-     * @throws IOException
-     * @throws SeCurisServiceException
-     * @throws SeCurisException
-     */
-    @POST
-    @Path("/request")
-    @Consumes(MediaType.MULTIPART_FORM_DATA)
-    @Securable
-    @Produces({
-        MediaType.APPLICATION_JSON
-    })
-    @EnsureTransaction
-    @SuppressWarnings("unchecked")
-    public Response createFromRequestFile(MultipartFormDataInput mpfdi,
-            @HeaderParam(LicenseManager.HEADER_LICENSE_NAME_OR_REFERENCE) String nameOrReference,
-            @HeaderParam(LicenseManager.HEADER_LICENSE_EMAIL) String userEmail) throws IOException, SeCurisServiceException, SeCurisException {
-        RequestBean req = new RequestBean();
-        req.setAppCode(mpfdi.getFormDataPart("appCode", String.class, null));
-        req.setActivationCode(mpfdi.getFormDataPart("activationCode", String.class, null));
-        req.setPackCode(mpfdi.getFormDataPart("packCode", String.class, null));
-        req.setLicenseTypeCode(mpfdi.getFormDataPart("licenseTypeCode", String.class, null));
-        req.setCustomerCode(mpfdi.getFormDataPart("customerCode", String.class, null));
-        req.setArch(mpfdi.getFormDataPart("arch", String.class, null));
-        req.setCrcLogo(mpfdi.getFormDataPart("crcLogo", String.class, null));
-        req.setMacAddresses(mpfdi.getFormDataPart("macAddresses", List.class, null));
-        req.setOsName(mpfdi.getFormDataPart("osName", String.class, null));
+	/**
+	 * Returns a License file in JSON format from an uploaded Request file
+	 * 
+	 * @param mpfdi
+	 * @param bsc
+	 * @return
+	 * @throws IOException
+	 * @throws SeCurisServiceException
+	 * @throws SeCurisException
+	 */
+	@POST
+	@Path("/request")
+	@Consumes(MediaType.MULTIPART_FORM_DATA)
+	@Securable
+	@Produces({ MediaType.APPLICATION_JSON })
+	@EnsureTransaction
+	@SuppressWarnings("unchecked")
+	public Response createFromRequestFile(MultipartFormDataInput mpfdi, @HeaderParam(LicenseManager.HEADER_LICENSE_NAME_OR_REFERENCE) String nameOrReference,
+			@HeaderParam(LicenseManager.HEADER_LICENSE_EMAIL) String userEmail) throws IOException, SeCurisServiceException, SeCurisException {
+		RequestBean req = new RequestBean();
+		req.setAppCode(mpfdi.getFormDataPart("appCode", String.class, null));
+		req.setActivationCode(mpfdi.getFormDataPart("activationCode", String.class, null));
+		req.setPackCode(mpfdi.getFormDataPart("packCode", String.class, null));
+		req.setLicenseTypeCode(mpfdi.getFormDataPart("licenseTypeCode", String.class, null));
+		req.setCustomerCode(mpfdi.getFormDataPart("customerCode", String.class, null));
+		req.setArch(mpfdi.getFormDataPart("arch", String.class, null));
+		req.setCrcLogo(mpfdi.getFormDataPart("crcLogo", String.class, null));
+		req.setMacAddresses(mpfdi.getFormDataPart("macAddresses", List.class, null));
+		req.setOsName(mpfdi.getFormDataPart("osName", String.class, null));
 
-        return createFromRequest(req, nameOrReference, userEmail);
-    }
+		return createFromRequest(req, nameOrReference, userEmail);
+	}
 
-    /**
-     * Create a new License file based in a previous one
-     * 
-     * @param request
-     * @param bsc
-     * @return
-     * @throws IOException
-     * @throws SeCurisServiceException
-     * @throws SeCurisException
-     */
-    @POST
-    @Path("/renew")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Securable
-    @Produces({
-        MediaType.APPLICATION_JSON
-    })
-    @EnsureTransaction
-    public Response renewFromPreviousLicense(LicenseBean previousLic, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException,
-            SeCurisException {
-        LOG.info("Renew license: {}", previousLic);
+	/**
+	 * Create a new License file based in a previous one
+	 * 
+	 * @param request
+	 * @param bsc
+	 * @return
+	 * @throws IOException
+	 * @throws SeCurisServiceException
+	 * @throws SeCurisException
+	 */
+	@POST
+	@Path("/renew")
+	@Consumes(MediaType.APPLICATION_JSON)
+	@Securable
+	@Produces({ MediaType.APPLICATION_JSON })
+	@EnsureTransaction
+	public Response renewFromPreviousLicense(LicenseBean previousLic, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException, SeCurisException {
+		LOG.info("Renew license: {}", previousLic);
 
-        if (previousLic.getExpirationDate().after(DateUtils.addMonths(new Date(), 1))) {
-            throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "The license is still valid, not ready for renew");
-        }
+		if (previousLic.getExpirationDate().after(DateUtils.addMonths(new Date(), 1))) {
+			throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "The license is still valid, not ready for renew");
+		}
 
-        // EntityManager em = emProvider.get();
-        License lic = License.findLicenseByCode(previousLic.getLicenseCode(), em);
-        if (lic.getStatus() != LicenseStatus.ACTIVE) {
-            throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "Only licenses with status 'Active' can be renew");
-        }
+		// EntityManager em = emProvider.get();
+		License lic = License.findLicenseByCode(previousLic.getLicenseCode(), em);
+		if (lic == null) {
+			throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "Current license is missing in DB");
+		}
 
-        SignedLicenseBean signedLic = renewLicense(previousLic, em);
-        LOG.info("Renewed license code: {}, until: {}", signedLic.getLicenseCode(), signedLic.getExpirationDate());
+		if (lic.getStatus() != LicenseStatus.ACTIVE) {
+			throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "Only licenses with status 'Active' can be renew");
+		}
 
-        return Response.ok(signedLic).build();
-    }
+		SignedLicenseBean signedLic = renewLicense(previousLic, em);
+		LOG.info("Renewed license code: {}, until: {}", signedLic.getLicenseCode(), signedLic.getExpirationDate());
 
-    /**
-     * License validation on server side, in this case we validate that the
-     * current licenses has not been cancelled.
-     * 
-     * @param currentLic
-     * @param bsc
-     * @return
-     * @throws IOException
-     * @throws SeCurisServiceException
-     * @throws SeCurisException
-     */
-    @POST
-    @Path("/validate")
-    @Consumes(MediaType.APPLICATION_JSON)
-    @Securable
-    @Produces({
-        MediaType.APPLICATION_JSON
-    })
-    @EnsureTransaction
-    public Response validate(LicenseBean currentLic, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException, SeCurisException {
-        LOG.info("Validate license: {}", currentLic);
+		return Response.ok(signedLic).build();
+	}
 
-        if (currentLic.getExpirationDate().before(new Date())) {
-            throw new SeCurisServiceException(ErrorCodes.LICENSE_IS_EXPIRED, "The license is expired");
-        }
+	/**
+	 * License validation on server side, in this case we validate that the
+	 * current licenses has not been cancelled.
+	 * 
+	 * @param currentLic
+	 * @param bsc
+	 * @return
+	 * @throws IOException
+	 * @throws SeCurisServiceException
+	 * @throws SeCurisException
+	 */
+	@POST
+	@Path("/validate")
+	@Consumes(MediaType.APPLICATION_JSON)
+	@Securable
+	@Produces({ MediaType.APPLICATION_JSON })
+	@EnsureTransaction
+	public Response validate(LicenseBean currentLic, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException, SeCurisException {
+		LOG.info("Validate license: {}", currentLic);
 
-        try {
-            SignatureHelper.getInstance().validateSignature(currentLic);
-        } catch (SeCurisException ex) {
-            throw new SeCurisServiceException(ErrorCodes.LICENSE_DATA_IS_NOT_VALID, "The license signature is not valid");
-        }
-        licenseHelper.assertLicenseStatusIsActive(currentLic, em);
+		if (currentLic.getExpirationDate().before(new Date())) {
+			throw new SeCurisServiceException(ErrorCodes.LICENSE_IS_EXPIRED, "The license is expired");
+		}
 
-        return Response.ok(currentLic).build();
-    }
+		try {
+			SignatureHelper.getInstance().validateSignature(currentLic);
+		} catch (SeCurisException ex) {
+			throw new SeCurisServiceException(ErrorCodes.LICENSE_DATA_IS_NOT_VALID, "The license signature is not valid");
+		}
+		licenseHelper.assertLicenseStatusIsActive(currentLic, em);
 
-    /**
-     * Returns a new License file in JSON format based in a previous license
-     * There is 2 /renew services with json input and with upload file
-     * 
-     * @param mpfdi
-     * @param bsc
-     * @return
-     * @throws IOException
-     * @throws SeCurisServiceException
-     * @throws SeCurisException
-     */
-    @POST
-    @Path("/renew")
-    @Consumes(MediaType.MULTIPART_FORM_DATA)
-    @Securable
-    @Produces({
-        MediaType.APPLICATION_JSON
-    })
-    @EnsureTransaction
-    @SuppressWarnings("unchecked")
-    public Response renewFromLicenseFile(MultipartFormDataInput mpfdi, @Context BasicSecurityContext bsc) throws IOException,
-            SeCurisServiceException, SeCurisException {
-        LicenseBean lic = new LicenseBean();
+		return Response.ok(currentLic).build();
+	}
 
-        lic.setAppCode(mpfdi.getFormDataPart("appCode", String.class, null));
-        lic.setActivationCode(mpfdi.getFormDataPart("activationName", String.class, null));
-        lic.setAppName(mpfdi.getFormDataPart("appName", String.class, null));
-        lic.setArch(mpfdi.getFormDataPart("arch", String.class, null));
-        lic.setCrcLogo(mpfdi.getFormDataPart("crcLogo", String.class, null));
-        lic.setPackCode(mpfdi.getFormDataPart("packCode", String.class, null));
-        lic.setLicenseTypeCode(mpfdi.getFormDataPart("licenseCode", String.class, null));
-        lic.setCustomerCode(mpfdi.getFormDataPart("customerCode", String.class, null));
-        lic.setMacAddresses(mpfdi.getFormDataPart("macAddresses", List.class, null));
-        lic.setOsName(mpfdi.getFormDataPart("osName", String.class, null));
-        lic.setExpirationDate(mpfdi.getFormDataPart("expirationDate", Date.class, null));
-        LOG.info("Lic expires at: {}", lic.getExpirationDate());
-        if (lic.getExpirationDate().after(DateUtils.addMonths(new Date(), 1))) {
-            throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "The license is still valid, not ready for renew");
-        }
+	/**
+	 * Returns a new License file in JSON format based in a previous license
+	 * There is 2 /renew services with json input and with upload file
+	 * 
+	 * @param mpfdi
+	 * @param bsc
+	 * @return
+	 * @throws IOException
+	 * @throws SeCurisServiceException
+	 * @throws SeCurisException
+	 */
+	@POST
+	@Path("/renew")
+	@Consumes(MediaType.MULTIPART_FORM_DATA)
+	@Securable
+	@Produces({ MediaType.APPLICATION_JSON })
+	@EnsureTransaction
+	@SuppressWarnings("unchecked")
+	public Response renewFromLicenseFile(MultipartFormDataInput mpfdi, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException, SeCurisException {
+		LicenseBean lic = new LicenseBean();
 
-        return renewFromPreviousLicense(lic, bsc);
-    }
+		lic.setAppCode(mpfdi.getFormDataPart("appCode", String.class, null));
+		lic.setActivationCode(mpfdi.getFormDataPart("activationName", String.class, null));
+		lic.setAppName(mpfdi.getFormDataPart("appName", String.class, null));
+		lic.setArch(mpfdi.getFormDataPart("arch", String.class, null));
+		lic.setCrcLogo(mpfdi.getFormDataPart("crcLogo", String.class, null));
+		lic.setPackCode(mpfdi.getFormDataPart("packCode", String.class, null));
+		lic.setLicenseTypeCode(mpfdi.getFormDataPart("licenseCode", String.class, null));
+		lic.setCustomerCode(mpfdi.getFormDataPart("customerCode", String.class, null));
+		lic.setMacAddresses(mpfdi.getFormDataPart("macAddresses", List.class, null));
+		lic.setOsName(mpfdi.getFormDataPart("osName", String.class, null));
+		lic.setExpirationDate(mpfdi.getFormDataPart("expirationDate", Date.class, null));
+		LOG.info("Lic expires at: {}", lic.getExpirationDate());
+		if (lic.getExpirationDate().after(DateUtils.addMonths(new Date(), 1))) {
+			throw new SeCurisServiceException(ErrorCodes.LICENSE_NOT_READY_FOR_RENEW, "The license is still valid, not ready for renew");
+		}
 
-    private SignedLicenseBean renewLicense(RequestBean req, EntityManager em) throws SeCurisServiceException {
-        return renewLicense(req, em);
-    }
+		return renewFromPreviousLicense(lic, bsc);
+	}
 
-    /**
-     * Creates a new signed license from request data or from previous license
-     * if It's a renew
-     * 
-     * @param req
-     * @param em
-     * @param renew
-     * @return
-     * @throws SeCurisServiceException
-     */
-    private SignedLicenseBean createLicense(RequestBean req, EntityManager em, String nameOrReference, String email) throws SeCurisServiceException {
-        License lic = null;
+	private SignedLicenseBean renewLicense(RequestBean req, EntityManager em) throws SeCurisServiceException {
+		return renewLicense(req, em);
+	}
 
-        if (req.getActivationCode() != null) {
-            lic = License.findLicenseByActivationCode(req.getActivationCode(), em);
-            if (lic == null) {
-                throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The given activation code is invalid: " + req.getActivationCode());
-            }
-            if (lic.getStatus() == LicenseStatus.ACTIVE) {
-                RequestBean initialRequest;
-                try {
-                    initialRequest = JsonUtils.json2object(lic.getRequestData(), RequestBean.class);
-                    if (!req.match(initialRequest)) {
-                        throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "There is already an active license for given activation code: "
-                                + req.getActivationCode());
-                    } else {
-                        return JsonUtils.json2object(lic.getLicenseData(), SignedLicenseBean.class);
-                    }
-                } catch (SeCurisException e) {
-                    LOG.error("Error getting existing license", e);
-                    throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Original request is wrong");
-                }
-            } else {
-                if (req.getAppCode() != null && !req.getAppCode().equals(lic.getPack().getLicenseType().getApplication().getCode())) {
-                    LOG.error("Activation code {} belongs to app: {} but was sent by: {}", req.getActivationCode(), lic.getPack().getLicenseType()
-                            .getApplication().getCode(), req.getAppCode());
-                    throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The given activation code belongs to a different application: "
-                            + req.getActivationCode());
-                }
-            }
-            // We validate if the HW is the same, otherwise an error is
-            // thrown
-        } else {
-            try {
-                lic = License.findValidLicenseByRequestData(JsonUtils.toJSON(req), em);
-            } catch (SeCurisException e1) {
-                throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Request sent is not valid");
-            }
-            if (lic != null) {
-                try {
-                    if (lic.getStatus() == LicenseStatus.ACTIVE || lic.getStatus() == LicenseStatus.PRE_ACTIVE) {
-                        return JsonUtils.json2object(lic.getLicenseData(), SignedLicenseBean.class);
-                    }
-                } catch (SeCurisException e) {
-                    throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error trying to get the license bean from license code: "
-                            + lic.getCode());
-                }
-            } else {
-                lic = new License();
-            }
-        }
+	/**
+	 * Creates a new signed license from request data or from previous license
+	 * if It's a renew
+	 * 
+	 * @param req
+	 * @param em
+	 * @param renew
+	 * @return
+	 * @throws SeCurisServiceException
+	 */
+	private SignedLicenseBean createLicense(RequestBean req, EntityManager em, String nameOrReference, String email) throws SeCurisServiceException {
+		License lic = null;
 
-        Pack pack;
-        if (lic.getActivationCode() == null) {
-            try {
-                pack = em.createNamedQuery("pack-by-code", Pack.class).setParameter("code", req.getPackCode()).getSingleResult();
-            } catch (NoResultException e) {
-                throw new SeCurisServiceException(ErrorCodes.NOT_FOUND, "No pack found for code: " + req.getPackCode());
-            }
+		if (req.getActivationCode() != null) {
+			lic = License.findLicenseByActivationCode(req.getActivationCode(), em);
+			if (lic == null) {
+				throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The given activation code is invalid: " + req.getActivationCode());
+			}
+			if (lic.getStatus() == LicenseStatus.ACTIVE) {
+				RequestBean initialRequest;
+				try {
+					initialRequest = JsonUtils.json2object(lic.getRequestData(), RequestBean.class);
+					if (!req.match(initialRequest)) {
+						throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "There is already an active license for given activation code: " + req.getActivationCode());
+					} else {
+						return JsonUtils.json2object(lic.getLicenseData(), SignedLicenseBean.class);
+					}
+				} catch (SeCurisException e) {
+					LOG.error("Error getting existing license", e);
+					throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Original request is wrong");
+				}
+			} else {
+				if (req.getAppCode() != null && !req.getAppCode().equals(lic.getPack().getLicenseType().getApplication().getCode())) {
+					LOG.error("Activation code {} belongs to app: {} but was sent by: {}", req.getActivationCode(), lic.getPack().getLicenseType().getApplication().getCode(),
+							req.getAppCode());
+					throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The given activation code belongs to a different application: " + req.getActivationCode());
+				}
+			}
+			// We validate if the HW is the same, otherwise an error is
+			// thrown
+		} else {
+			try {
+				lic = License.findValidLicenseByRequestData(JsonUtils.toJSON(req), em);
+			} catch (SeCurisException e1) {
+				throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Request sent is not valid");
+			}
+			if (lic != null) {
+				try {
+					if (lic.getStatus() == LicenseStatus.ACTIVE || lic.getStatus() == LicenseStatus.PRE_ACTIVE) {
+						return JsonUtils.json2object(lic.getLicenseData(), SignedLicenseBean.class);
+					}
+				} catch (SeCurisException e) {
+					throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error trying to get the license bean from license code: " + lic.getCode());
+				}
+			} else {
+				lic = new License();
+			}
+		}
 
-            if (pack.getNumAvailables() <= 0) {
-                throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "The current pack has no licenses availables");
-            }
-            if (lic.getStatus() == LicenseStatus.REQUESTED && !pack.isLicensePreactivation()) {
-                throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "Current pack doesn't allow license preactivation");
-            }
+		Pack pack;
+		if (lic.getActivationCode() == null) {
+			try {
+				pack = em.createNamedQuery("pack-by-code", Pack.class).setParameter("code", req.getPackCode()).getSingleResult();
+			} catch (NoResultException e) {
+				throw new SeCurisServiceException(ErrorCodes.NOT_FOUND, "No pack found for code: " + req.getPackCode());
+			}
 
-            if (!req.getCustomerCode().equals(pack.getOrganization().getCode())) {
-                throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Customer code is not valid: " + req.getCustomerCode());
-            }
+			if (pack.getNumAvailables() <= 0) {
+				throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "The current pack has no licenses availables");
+			}
+			if (lic.getStatus() == LicenseStatus.REQUESTED && !pack.isLicensePreactivation()) {
+				throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "Current pack doesn't allow license preactivation");
+			}
 
-            if (!req.getLicenseTypeCode().equals(pack.getLicenseTypeCode())) {
-                throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "License type code is not valid: "
-                        + req.getLicenseTypeCode());
-            }
-        } else {
-            pack = lic.getPack();
-        }
-        SignedLicenseBean signedLicense;
-        try {
-            String licCode;
-            if (lic.getCode() == null) {
-                licCode = LicUtils.getLicenseCode(pack.getCode(), licenseHelper.getNextCodeSuffix(pack.getId(), em));
-            } else {
-                licCode = lic.getCode();
-            }
-            Date expirationDate = licenseHelper.getExpirationDateFromPack(pack, lic.getActivationCode() == null);
+			if (!req.getCustomerCode().equals(pack.getOrganization().getCode())) {
+				throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Customer code is not valid: " + req.getCustomerCode());
+			}
 
-            LicenseBean lb = licenseGenerator.generateLicense(req, licenseHelper.extractPackMetadata(pack.getMetadata()), expirationDate, licCode,
-                    pack.getAppName());
-            signedLicense = new SignedLicenseBean(lb);
-        } catch (SeCurisException e) {
-            throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Error generating license: " + e.toString());
-        }
-        try {
-            lic.setRequestData(JsonUtils.toJSON(req));
-            if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
-                throw new SeCurisServiceException(ErrorCodes.BLOCKED_REQUEST_DATA, "Given request data is blocked and cannot be activated");
-            }
-            lic.setLicenseData(JsonUtils.toJSON(signedLicense));
-        } catch (SeCurisException e) {
-            LOG.error("Error generating license JSON", e);
-            throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generating license JSON");
-        }
+			if (!req.getLicenseTypeCode().equals(pack.getLicenseTypeCode())) {
+				throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "License type code is not valid: " + req.getLicenseTypeCode());
+			}
+		} else {
+			pack = lic.getPack();
+		}
+		SignedLicenseBean signedLicense;
+		try {
+			String licCode;
+			if (lic.getCode() == null) {
+				licCode = LicUtils.getLicenseCode(pack.getCode(), licenseHelper.getNextCodeSuffix(pack.getId(), em));
+			} else {
+				licCode = lic.getCode();
+			}
+			Date expirationDate = licenseHelper.getExpirationDateFromPack(pack, lic.getActivationCode() == null);
 
-        lic.setModificationTimestamp(new Date());
-        lic.setExpirationDate(signedLicense.getExpirationDate());
-        User user = em.find(User.class, API_CLIENT_USERNAME);
-        if (lic.getStatus() != LicenseStatus.REQUESTED) {
-            lic.setPack(pack);
-            lic.setCreatedBy(user);
-            lic.setCreationTimestamp(new Date());
-            if (lic.getActivationCode() != null) {
-                lic.setStatus(LicenseStatus.ACTIVE);
-            } else {
-                lic.setStatus(pack.isLicensePreactivation() ? LicenseStatus.PRE_ACTIVE : LicenseStatus.REQUESTED);
-            }
-            lic.setCode(signedLicense.getLicenseCode());
-            lic.setCodeSuffix(LicUtils.getLicenseCodeSuffix(signedLicense.getLicenseCode()));
-            if (lic.getEmail() == null || "".equals(lic.getEmail())) {
-                lic.setEmail(email);
-            }
-            if (lic.getFullName() == null || "".equals(lic.getFullName())) {
-                lic.setFullName(nameOrReference);
-            }
-            if (lic.getId() != null) {
-                em.merge(lic);
-            } else {
-                em.persist(lic);
-            }
-            em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.CREATE));
-            if (lic.getActivationCode() != null) {
-                em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.ACTIVATE, "Activated by code on creation"));
-            } else {
-                if (pack.isLicensePreactivation()) {
-                    em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.PRE_ACTIVATE, "Pre-activated on creation"));
-                } else {
-                    LOG.warn("License ({}) created, but the pack doesn't allow preactivation", lic.getCode());
-                    throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "Current pack doesn't allow license preactivation");
-                }
-            }
-        } else {
-            lic.setStatus(LicenseStatus.PRE_ACTIVE);
-            em.merge(lic);
-            em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.PRE_ACTIVATE, "Pre-activated after request"));
-        }
+			LicenseBean lb = licenseGenerator.generateLicense(req, licenseHelper.extractPackMetadata(pack.getMetadata()), expirationDate, licCode, pack.getAppName());
+			signedLicense = new SignedLicenseBean(lb);
+		} catch (SeCurisException e) {
+			throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Error generating license: " + e.toString());
+		}
+		try {
+			lic.setRequestData(JsonUtils.toJSON(req));
+			if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
+				throw new SeCurisServiceException(ErrorCodes.BLOCKED_REQUEST_DATA, "Given request data is blocked and cannot be activated");
+			}
+			lic.setLicenseData(JsonUtils.toJSON(signedLicense));
+		} catch (SeCurisException e) {
+			LOG.error("Error generating license JSON", e);
+			throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generating license JSON");
+		}
 
-        return signedLicense;
-    }
+		lic.setModificationTimestamp(new Date());
+		lic.setExpirationDate(signedLicense.getExpirationDate());
+		User user = em.find(User.class, API_CLIENT_USERNAME);
+		if (lic.getStatus() != LicenseStatus.REQUESTED) {
+			lic.setPack(pack);
+			lic.setCreatedBy(user);
+			lic.setCreationTimestamp(new Date());
+			if (lic.getActivationCode() != null) {
+				lic.setStatus(LicenseStatus.ACTIVE);
+			} else {
+				lic.setStatus(pack.isLicensePreactivation() ? LicenseStatus.PRE_ACTIVE : LicenseStatus.REQUESTED);
+			}
+			lic.setCode(signedLicense.getLicenseCode());
+			lic.setCodeSuffix(LicUtils.getLicenseCodeSuffix(signedLicense.getLicenseCode()));
+			if (lic.getEmail() == null || "".equals(lic.getEmail())) {
+				lic.setEmail(email);
+			}
+			if (lic.getFullName() == null || "".equals(lic.getFullName())) {
+				lic.setFullName(nameOrReference);
+			}
+			if (lic.getId() != null) {
+				em.merge(lic);
+			} else {
+				em.persist(lic);
+			}
+			em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.CREATE));
+			if (lic.getActivationCode() != null) {
+				em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.ACTIVATE, "Activated by code on creation"));
+			} else {
+				if (pack.isLicensePreactivation()) {
+					em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.PRE_ACTIVATE, "Pre-activated on creation"));
+				} else {
+					LOG.warn("License ({}) created, but the pack doesn't allow preactivation", lic.getCode());
+					throw new SeCurisServiceException(ErrorCodes.NO_AVAILABLE_LICENSES, "Current pack doesn't allow license preactivation");
+				}
+			}
+		} else {
+			lic.setStatus(LicenseStatus.PRE_ACTIVE);
+			em.merge(lic);
+			em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.PRE_ACTIVATE, "Pre-activated after request"));
+		}
 
-    /**
-     * Creates a new signed license from request data or from previous license
-     * if It's a renew
-     * 
-     * @param req
-     * @param em
-     * @param renew
-     * @return
-     * @throws SeCurisServiceException
-     */
-    private SignedLicenseBean renewLicense(LicenseBean previousLicenseBean, EntityManager em) throws SeCurisServiceException {
+		return signedLicense;
+	}
 
-        License lic = License.findLicenseByCode(previousLicenseBean.getLicenseCode(), em);
-        if (lic.getStatus() != LicenseStatus.ACTIVE && lic.getStatus() != LicenseStatus.PRE_ACTIVE) {
-            throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The current license has been cancelled");
-        }
+	/**
+	 * Creates a new signed license from request data or from previous license
+	 * if It's a renew
+	 * 
+	 * @param req
+	 * @param em
+	 * @param renew
+	 * @return
+	 * @throws SeCurisServiceException
+	 */
+	private SignedLicenseBean renewLicense(LicenseBean previousLicenseBean, EntityManager em) throws SeCurisServiceException {
 
-        Pack pack = lic.getPack();
-        SignedLicenseBean signedLicense;
-        try {
-            String licCode = lic.getCode();
-            Date expirationDate = licenseHelper.getExpirationDateFromPack(pack, false);
+		License lic = License.findLicenseByCode(previousLicenseBean.getLicenseCode(), em);
+		if (lic.getStatus() != LicenseStatus.ACTIVE && lic.getStatus() != LicenseStatus.PRE_ACTIVE) {
+			throw new SeCurisServiceException(ErrorCodes.INVALID_DATA, "The current license has been cancelled");
+		}
 
-            LicenseBean lb = licenseGenerator.generateLicense(previousLicenseBean, licenseHelper.extractPackMetadata(pack.getMetadata()),
-                    expirationDate, licCode, pack.getAppName());
-            signedLicense = new SignedLicenseBean(lb);
-        } catch (SeCurisException e) {
-            throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Error generating license: " + e.toString());
-        }
-        try {
-            lic.setRequestData(JsonUtils.toJSON(signedLicense, RequestBean.class));
-            if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
-                throw new SeCurisServiceException(ErrorCodes.BLOCKED_REQUEST_DATA, "Given request data is blocked and cannot be activated");
-            }
-            lic.setLicenseData(JsonUtils.toJSON(signedLicense));
-        } catch (SeCurisException e) {
-            LOG.error("Error generating license JSON", e);
-            throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generating license JSON");
-        }
+		Pack pack = lic.getPack();
+		SignedLicenseBean signedLicense;
+		try {
+			String licCode = lic.getCode();
+			Date expirationDate = licenseHelper.getExpirationDateFromPack(pack, false);
 
-        lic.setModificationTimestamp(new Date());
-        lic.setExpirationDate(signedLicense.getExpirationDate());
-        User user = em.find(User.class, API_CLIENT_USERNAME);
+			LicenseBean lb = licenseGenerator.generateLicense(previousLicenseBean, licenseHelper.extractPackMetadata(pack.getMetadata()), expirationDate, licCode,
+					pack.getAppName());
+			signedLicense = new SignedLicenseBean(lb);
+		} catch (SeCurisException e) {
+			throw new SeCurisServiceException(ErrorCodes.INVALID_LICENSE_REQUEST_DATA, "Error generating license: " + e.toString());
+		}
+		try {
+			lic.setRequestData(JsonUtils.toJSON(signedLicense, RequestBean.class));
+			if (BlockedRequest.isRequestBlocked(lic.getRequestData(), em)) {
+				throw new SeCurisServiceException(ErrorCodes.BLOCKED_REQUEST_DATA, "Given request data is blocked and cannot be activated");
+			}
+			lic.setLicenseData(JsonUtils.toJSON(signedLicense));
+		} catch (SeCurisException e) {
+			LOG.error("Error generating license JSON", e);
+			throw new SeCurisServiceException(ErrorCodes.INVALID_FORMAT, "Error generating license JSON");
+		}
 
-        lic.setStatus(LicenseStatus.ACTIVE);
-        em.merge(lic);
-        em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.RENEW));
+		lic.setModificationTimestamp(new Date());
+		lic.setExpirationDate(signedLicense.getExpirationDate());
+		User user = em.find(User.class, API_CLIENT_USERNAME);
 
-        return signedLicense;
-    }
+		lic.setStatus(LicenseStatus.ACTIVE);
+		em.merge(lic);
+		em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.RENEW));
+
+		return signedLicense;
+	}
 }

--
Gitblit v1.3.2