From f1702d6537568b1677254e27d772d6aa6d658e2c Mon Sep 17 00:00:00 2001
From: rsanchez <rsanchez@curisit.net>
Date: Tue, 30 Sep 2014 11:08:45 +0000
Subject: [PATCH] #2021 fix - Added renew command in client

---
 src/main/java/net/curisit/securis/ConnectionManager.java |   44 ++++++++++----
 src/main/java/net/curisit/securis/LicenseManager.java    |   71 ++++++++++++++++-------
 src/main/java/net/curisit/securis/License.java           |   16 ++++
 3 files changed, 94 insertions(+), 37 deletions(-)

diff --git a/src/main/java/net/curisit/securis/ConnectionManager.java b/src/main/java/net/curisit/securis/ConnectionManager.java
index 06f74f9..dde3e6f 100644
--- a/src/main/java/net/curisit/securis/ConnectionManager.java
+++ b/src/main/java/net/curisit/securis/ConnectionManager.java
@@ -1,5 +1,6 @@
 package net.curisit.securis;
 
+import java.awt.PageAttributes.MediaType;
 import java.io.IOException;
 import java.io.UnsupportedEncodingException;
 import java.security.KeyManagementException;
@@ -8,6 +9,8 @@
 import java.security.NoSuchAlgorithmException;
 import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;
+
+import javax.activation.MimeType;
 
 import net.curisit.securis.beans.RequestBean;
 import net.curisit.securis.utils.JsonUtils;
@@ -34,6 +37,10 @@
 public class ConnectionManager {
 
 	private static final Logger LOG = LogManager.getLogger(ConnectionManager.class);
+    private  static final int HTTP_STATUS_APP_ERRROR = 418;
+    private  static final String JSON_MEDIA_TYPE= "application/json";
+    private static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR-MSG";
+    private static final String ERROR_CODE_MESSAGE_HEADER = "X-SECURIS-ERROR-CODE";
 
 	private static ConnectionManager singleton;
 
@@ -78,8 +85,9 @@
 
 	public <T> T executePost(String command, Class<T> returnType, RequestBean req) throws SeCurisException {
         HttpPost postRequest = new HttpPost(String.format("%s/%s", serverUrl, command));
-        postRequest.addHeader("accept", "application/json");
-        postRequest.addHeader("content-type", "application/json");
+        postRequest.addHeader("accept", JSON_MEDIA_TYPE);
+        
+        postRequest.addHeader("content-type", JSON_MEDIA_TYPE);
         try {
             postRequest.setEntity(new StringEntity(JsonUtils.toJSON(req)));
         } catch (UnsupportedEncodingException | SeCurisException e1) {
@@ -88,27 +96,38 @@
         HttpResponse response;
         try {
             response = httpClient.execute(postRequest);
-            if (response.getStatusLine().getStatusCode() != 200) {
-                throw new SeCurisException("Error executing command " + command + ", status: " + response.getStatusLine().getStatusCode());
-            }
+            
+            checkErrors(command, response);
+            
             String jsonLic = IOUtils.toString(response.getEntity().getContent());
-            LOG.info("License read OK: {}", jsonLic);
+            LOG.debug("Response content read OK: {}", jsonLic);
             T responseBean = JsonUtils.json2object(jsonLic, returnType);
 
-            LOG.info("Response bean read OK: {}", responseBean);
-            LOG.info("JSON to write in file: {}", JsonUtils.toJSON(responseBean));
+            LOG.debug("Response bean read OK: {}", responseBean);
             
             return responseBean;
         } catch (IOException e) {
-            LOG.error("Error acessing SeCuris server", e);
+            LOG.error("Error accessing SeCuris server", e);
             throw new SeCurisException("Error accessing SeCuris server");
         }
  	}
 
+	private void checkErrors(String command, HttpResponse response) throws SeCurisException {
+        if (response.getStatusLine().getStatusCode() != 200) {
+            if (response.getStatusLine().getStatusCode() == HTTP_STATUS_APP_ERRROR) {
+                String errorCode = response.getFirstHeader(ERROR_CODE_MESSAGE_HEADER).getValue();
+                String errorMsg = response.getFirstHeader(ERROR_MESSAGE_HEADER).getValue();
+                throw new SeCurisException(String.format("[%s] - %s", errorCode, errorMsg));
+            }
+            LOG.error("Unexpected error executing {}, Reason: {}", command, response.getStatusLine().getReasonPhrase());
+            throw new SeCurisException("Error executing command " + command + ", status: " + response.getStatusLine().getStatusCode());
+        }
+
+	}
 
     public <T> T executeGet(String command, Class<T> returnType) throws SeCurisException {
         HttpGet getRequest = new HttpGet(String.format("%s/%s", serverUrl, command));
-        getRequest.addHeader("accept", "application/json");
+        getRequest.addHeader("accept", JSON_MEDIA_TYPE);
 
         HttpResponse response;
         try {
@@ -117,11 +136,10 @@
                 throw new SeCurisException("Error executing command " + command + ", status: " + response.getStatusLine().getStatusCode());
             }
             String jsonLic = IOUtils.toString(response.getEntity().getContent());
-            LOG.info("License read OK: {}", jsonLic);
+            LOG.debug("Response content read OK: {}", jsonLic);
             T responseBean = JsonUtils.json2object(jsonLic, returnType);
 
-            LOG.info("Response bean read OK: {}", responseBean);
-            LOG.info("JSON to write in file: {}", JsonUtils.toJSON(responseBean));
+            LOG.debug("Response bean read OK: {}", responseBean);
             
             return responseBean;
         } catch (IOException e) {
diff --git a/src/main/java/net/curisit/securis/License.java b/src/main/java/net/curisit/securis/License.java
index 2d51327..d22c4cd 100644
--- a/src/main/java/net/curisit/securis/License.java
+++ b/src/main/java/net/curisit/securis/License.java
@@ -73,6 +73,9 @@
 				if (filename == null)
 					filename = "./license.lic";
 				File file = new File(filename);
+				if (!file.exists()) {
+				    throw new SeCurisException("The license file doesn't exist: " + file.getAbsolutePath());
+				}
 				try {
 					LicenseManager.getInstance().validateLicense(file);
 					LOG.info("License file {} is valid", file.getAbsolutePath());
@@ -86,7 +89,7 @@
 
 			if (cmd.hasOption('c')) {
 				SignedLicenseBean lic = LicenseManager.getInstance().requestLicense();
-				String filename = cmd.getOptionValue("lic_file");
+				String filename = cmd.getOptionValue("c");
                 if (filename == null)
                     filename = "./license.lic";
                 File file = new File(filename);
@@ -105,7 +108,16 @@
 			if (cmd.hasOption('r')) {
 				String licFilename = cmd.getOptionValue("renew");
 				checkMandatoryParameter(licFilename, "renew");
-				LOG.warn("This command is not yet implemented");
+                File file = new File(licFilename);
+                if (!file.exists()) {
+                    throw new SeCurisException("The license file doesn't exist: " + file.getAbsolutePath());
+                }
+                SignedLicenseBean newLic = LicenseManager.getInstance().renew(file);
+                File oldLicFile = new File(file.getAbsoluteFile() + ".old");
+                file.renameTo(oldLicFile);
+                LOG.info("Old license file has been renamed to: {}", oldLicFile.getAbsolutePath());
+                LicenseManager.getInstance().save(newLic, file);
+                LOG.info("New license file saved as: {}", file.getAbsolutePath());
 				System.exit(0);
 			}
 
diff --git a/src/main/java/net/curisit/securis/LicenseManager.java b/src/main/java/net/curisit/securis/LicenseManager.java
index 69e3259..d05a2d2 100644
--- a/src/main/java/net/curisit/securis/LicenseManager.java
+++ b/src/main/java/net/curisit/securis/LicenseManager.java
@@ -6,6 +6,7 @@
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.nio.file.StandardOpenOption;
+import java.util.Date;
 
 import net.curisit.securis.ConnectionManager.Command;
 import net.curisit.securis.beans.LicenseBean;
@@ -57,29 +58,55 @@
 		return licBean;
 	}
 
-	/**
-	 * Validates the license stored in {@code licFile} and get the corresponding LicenseBean
-	 * <p>
-	 * The validation includes:
-	 * <ul>
-	 * <li>Signature</li>
-	 * <li>HW data</li>
-	 * <li>Logo CRC</li>
-	 * </ul>
-	 * </p>
-	 * 
-	 * @param licFile
-	 * @return The license bean stored in file
-	 * @throws SeCurisException
-	 */
-	public LicenseBean validateLicense(File licFile) throws SeCurisException {
-		LicenseBean licBean = load(licFile);
-		SignatureHelper.getInstance().validateSignature(licBean);
-		LicenseValidator.getInstance().validateHW(licBean, Params.get(Params.KEYS.APPLICATION_CODE), Params.get(Params.KEYS.CUSTOMER_CODE));
-		LicenseValidator.getInstance().validateLogo(licBean);
+    /**
+     * Validates the license stored in {@code licFile} and get the corresponding LicenseBean
+     * <p>
+     * The validation includes:
+     * <ul>
+     * <li>Signature</li>
+     * <li>HW data</li>
+     * <li>Logo CRC</li>
+     * </ul>
+     * </p>
+     * 
+     * @param licFile
+     * @return The license bean stored in file
+     * @throws SeCurisException
+     */
+    public LicenseBean validateLicense(File licFile) throws SeCurisException {
 
-		return licBean;
-	}
+        return validateLicense(licFile, false);
+    }
+
+    /**
+     * Validates the license stored in {@code licFile} and get the corresponding LicenseBean. The License date is not validated
+     * <p>
+     * The validation includes:
+     * <ul>
+     * <li>Signature</li>
+     * <li>HW data</li>
+     * <li>Logo CRC</li>
+     * </ul>
+     * </p>
+     * 
+     * @param licFile
+     * @return The license bean stored in file
+     * @throws SeCurisException
+     */
+    public LicenseBean validateLicense(File licFile, boolean excludeDateValidation) throws SeCurisException {
+        LicenseBean licBean = load(licFile);
+        SignatureHelper.getInstance().validateSignature(licBean);
+        LicenseValidator.getInstance().validateHW(licBean, Params.get(Params.KEYS.APPLICATION_CODE), Params.get(Params.KEYS.CUSTOMER_CODE));
+        LicenseValidator.getInstance().validateLogo(licBean);
+
+        if (!excludeDateValidation) {
+            if (new Date().after(licBean.getExpirationDate())) {
+                throw new SeCurisException("License has expired");
+            }
+        }
+
+        return licBean;
+    }
 
 	/**
 	 * Request to server for a valid license

--
Gitblit v1.3.2