From fdbc8ca146b8e3aff0425e2faf94c0b4a6e3dd28 Mon Sep 17 00:00:00 2001
From: rsanchez <rsanchez@curisit.net>
Date: Tue, 18 Nov 2014 20:07:36 +0000
Subject: [PATCH] #396 fix - Corrected cancel action and added Settings entity
---
securis/src/main/java/net/curisit/securis/db/common/CreationTimestampEntity.java | 10
securis/src/main/java/net/curisit/securis/db/common/ModificationTimestampEntity.java | 10
securis/src/main/java/net/curisit/securis/db/License.java | 20
securis/src/main/java/net/curisit/securis/db/listeners/CreationTimestampListener.java | 23
securis/src/main/java/net/curisit/securis/db/Settings.java | 82 ++
securis/src/main/java/net/curisit/securis/db/common/SystemParams.java | 235 ++++++
securis/src/main/java/net/curisit/securis/db/listeners/ModificationTimestampListener.java | 25
securis/src/main/java/net/curisit/securis/services/LicenseResource.java | 22
securis/src/main/webapp/js/licenses.js | 1267 ++++++++++++++++++------------------
securis/src/main/java/net/curisit/securis/utils/EmailManager.java | 8
securis/src/main/java/net/curisit/securis/utils/Config.java | 303 ++++----
securis/src/main/resources/db/schema.sql | 2
12 files changed, 1,216 insertions(+), 791 deletions(-)
diff --git a/securis/src/main/java/net/curisit/securis/db/License.java b/securis/src/main/java/net/curisit/securis/db/License.java
index bd104f9..de6973b 100644
--- a/securis/src/main/java/net/curisit/securis/db/License.java
+++ b/securis/src/main/java/net/curisit/securis/db/License.java
@@ -8,6 +8,7 @@
import javax.persistence.Column;
import javax.persistence.Entity;
+import javax.persistence.EntityListeners;
import javax.persistence.EntityManager;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
@@ -23,6 +24,10 @@
import javax.persistence.TypedQuery;
import net.curisit.integrity.commons.Utils;
+import net.curisit.securis.db.common.CreationTimestampEntity;
+import net.curisit.securis.db.common.ModificationTimestampEntity;
+import net.curisit.securis.db.listeners.CreationTimestampListener;
+import net.curisit.securis.db.listeners.ModificationTimestampListener;
import net.curisit.securis.services.exception.SeCurisServiceException;
import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
@@ -33,16 +38,20 @@
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/**
* Entity implementation class for Entity: license
*
*/
@JsonAutoDetect
-@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+@JsonInclude(Include.NON_NULL)
@Entity
+@EntityListeners({
+ CreationTimestampListener.class, ModificationTimestampListener.class
+})
@Table(name = "license")
@JsonIgnoreProperties(ignoreUnknown = true)
@NamedQueries({
@@ -50,7 +59,8 @@
@NamedQuery(name = "list-licenses-by-req-data", query = "SELECT l FROM License l where l.reqDataHash = :hash"),
@NamedQuery(name = "list-active-licenses-by-req-data", query = "SELECT l FROM License l where l.reqDataHash = :hash and l.status in ('AC', 'PA')")
})
-public class License implements Serializable {
+public class License implements CreationTimestampEntity, ModificationTimestampEntity, Serializable {
+
private static final long serialVersionUID = 2700310404904877227L;
private static final Logger LOG = LogManager.getLogger(License.class);
@@ -134,10 +144,12 @@
this.code = code;
}
+ @Override
public Date getCreationTimestamp() {
return creationTimestamp;
}
+ @Override
public void setCreationTimestamp(Date creationTimestamp) {
this.creationTimestamp = creationTimestamp;
}
@@ -216,10 +228,12 @@
this.status = status;
}
+ @Override
public Date getModificationTimestamp() {
return modificationTimestamp;
}
+ @Override
public void setModificationTimestamp(Date modificationTimestamp) {
this.modificationTimestamp = modificationTimestamp;
}
diff --git a/securis/src/main/java/net/curisit/securis/db/Settings.java b/securis/src/main/java/net/curisit/securis/db/Settings.java
new file mode 100644
index 0000000..74336e1
--- /dev/null
+++ b/securis/src/main/java/net/curisit/securis/db/Settings.java
@@ -0,0 +1,82 @@
+package net.curisit.securis.db;
+
+import java.io.Serializable;
+import java.util.Date;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EntityListeners;
+import javax.persistence.Id;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
+import javax.persistence.Table;
+
+import net.curisit.securis.db.common.ModificationTimestampEntity;
+import net.curisit.securis.db.listeners.ModificationTimestampListener;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+/**
+ * Entity implementation class for Entity: settings settings is a table that has
+ * rows with 3 columns: "key", "value", "timestamp"
+ *
+ */
+@Entity()
+@EntityListeners({
+ ModificationTimestampListener.class
+})
+@Table(name = "settings")
+@NamedQueries({
+ @NamedQuery(name = "get-param", query = "SELECT p FROM Settings p where p.key = :key")
+})
+public class Settings implements ModificationTimestampEntity, Serializable {
+ @SuppressWarnings("unused")
+ private static final Logger LOG = LogManager.getLogger(Settings.class);
+
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ String key;
+
+ String value;
+
+ @Column(name = "modification_timestamp")
+ @JsonProperty("modification_timestamp")
+ private Date modificationTimestamp;
+
+ public String getKey() {
+ return key;
+ }
+
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public Date getModificationTimestamp() {
+ return modificationTimestamp;
+ }
+
+ @Override
+ public void setModificationTimestamp(Date modificationTimestamp) {
+ this.modificationTimestamp = modificationTimestamp;
+ }
+
+ @Override
+ public String toString() {
+
+ return String.format("{key: %s, value: %s, ts: %s}", key, value, modificationTimestamp);
+ }
+
+}
diff --git a/securis/src/main/java/net/curisit/securis/db/common/CreationTimestampEntity.java b/securis/src/main/java/net/curisit/securis/db/common/CreationTimestampEntity.java
new file mode 100644
index 0000000..e473ea0
--- /dev/null
+++ b/securis/src/main/java/net/curisit/securis/db/common/CreationTimestampEntity.java
@@ -0,0 +1,10 @@
+package net.curisit.securis.db.common;
+
+import java.util.Date;
+
+public interface CreationTimestampEntity {
+
+ public Date getCreationTimestamp();
+
+ public void setCreationTimestamp(Date creationTimestamp);
+}
diff --git a/securis/src/main/java/net/curisit/securis/db/common/ModificationTimestampEntity.java b/securis/src/main/java/net/curisit/securis/db/common/ModificationTimestampEntity.java
new file mode 100644
index 0000000..a59b56c
--- /dev/null
+++ b/securis/src/main/java/net/curisit/securis/db/common/ModificationTimestampEntity.java
@@ -0,0 +1,10 @@
+package net.curisit.securis.db.common;
+
+import java.util.Date;
+
+public interface ModificationTimestampEntity {
+
+ public Date getModificationTimestamp();
+
+ public void setModificationTimestamp(Date modificationTimestamp);
+}
diff --git a/securis/src/main/java/net/curisit/securis/db/common/SystemParams.java b/securis/src/main/java/net/curisit/securis/db/common/SystemParams.java
new file mode 100644
index 0000000..a3c7f69
--- /dev/null
+++ b/securis/src/main/java/net/curisit/securis/db/common/SystemParams.java
@@ -0,0 +1,235 @@
+package net.curisit.securis.db.common;
+
+import java.util.Date;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.persistence.EntityManager;
+
+import net.curisit.integrity.commons.Utils;
+import net.curisit.securis.db.Settings;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import com.google.inject.Provider;
+import com.google.inject.persist.Transactional;
+
+@Singleton
+public class SystemParams {
+
+ @SuppressWarnings("unused")
+ private static final Logger LOG = LogManager.getLogger(SystemParams.class);
+
+ @Inject
+ private Provider<EntityManager> emp;
+
+ /**
+ * Returns the system parameter value for given key
+ *
+ * @param key
+ * @return the value of the param or null if it doesn't exist
+ */
+ public String getParam(String key) {
+ return getParam(key, null);
+ }
+
+ /**
+ * Returns the system parameter as int value for given key
+ *
+ * @param key
+ * @return the value of the param or null if it doesn't exist
+ */
+ public Integer getParamAsInt(String key) {
+ String value = getParam(key, null);
+ return value == null ? null : Integer.parseInt(value);
+ }
+
+ /**
+ *
+ * @param key
+ * @param defaulValue
+ * returned if key doesn't exist in params table
+ * @return
+ */
+ public Integer getParamAsInt(String key, Integer defaulValue) {
+ String value = getParam(key, null);
+ return value == null ? defaulValue : Integer.parseInt(value);
+ }
+
+ /**
+ * Returns the system parameter as Date value for given key
+ *
+ * @param key
+ * @return the value of the param or null if it doesn't exist
+ */
+ public Date getParamAsDate(String key) {
+ String value = getParam(key, null);
+ return value == null ? null : Utils.toDateFromIso(value);
+ }
+
+ /**
+ * Returns the system parameter as boolean value for given key
+ *
+ * @param key
+ * @return the value of the param or null if it doesn't exist
+ */
+ public Boolean getParamAsBool(String key) {
+ String value = getParam(key, null);
+ return value == null ? null : Boolean.parseBoolean(value);
+ }
+
+ /**
+ *
+ * @param key
+ * @param defaulValue
+ * returned if key doesn't exist in params table
+ * @return
+ */
+ public Boolean getParamAsBool(String key, boolean defaulValue) {
+ String value = getParam(key, null);
+ return value == null ? defaulValue : Boolean.parseBoolean(value);
+ }
+
+ /**
+ * Returns the system parameter as boolean value for given key
+ *
+ * @param key
+ * @return the value of the param or null if it doesn't exist
+ */
+ public Double getParamAsDouble(String key) {
+ String value = getParam(key, null);
+ return value == null ? null : Double.parseDouble(value);
+ }
+
+ /**
+ * Returns the system parameter value for given key
+ *
+ * @param key
+ * @param defaultValue
+ * returned if key doesn't exist in params table
+ * @return
+ */
+ public String getParam(String key, String defaultValue) {
+ EntityManager em = emp.get();
+ Settings p = em.find(Settings.class, key);
+ return p == null ? defaultValue : p.getValue();
+ }
+
+ /**
+ * Returns the system parameter value passed as parameter to method
+ *
+ * @param key
+ * @param defaultValue
+ * @return
+ */
+ @Transactional
+ public void setParam(String key, String value) {
+ EntityManager em = this.emp.get();
+ Settings p = em.find(Settings.class, key);
+ if (p == null) {
+ p = new Settings();
+ p.setKey(key);
+ p.setValue(value);
+ em.persist(p);
+ } else {
+ p.setValue(value);
+ em.merge(p);
+ }
+ em.flush();
+ }
+
+ /**
+ * Save a parameter as a Date
+ *
+ * @param key
+ * @param value
+ */
+ public void setParam(String key, Date value) {
+ setParam(key, Utils.toIsoFormat(value));
+ }
+
+ /**
+ * Save a parameter as a integer
+ *
+ * @param key
+ * @param value
+ */
+ public void setParam(String key, int value) {
+ setParam(key, String.valueOf(value));
+ }
+
+ /**
+ * Save a parameter as a boolean
+ *
+ * @param key
+ * @param value
+ */
+ public void setParam(String key, boolean value) {
+ setParam(key, String.valueOf(value));
+ }
+
+ /**
+ * Save a parameter as a double
+ *
+ * @param key
+ * @param value
+ */
+ public void setParam(String key, double value) {
+ setParam(key, String.valueOf(value));
+ }
+
+ /**
+ * Remove a parameter from params table
+ *
+ * @param key
+ * @return
+ */
+ @Transactional
+ public void removeParam(String key) {
+ EntityManager em = this.emp.get();
+ Settings p = em.find(Settings.class, key);
+ if (p != null) {
+ em.remove(p);
+ }
+ }
+
+ public static class Keys {
+ // Keys used in basic app
+ public static final String CONFIG_CLIENT_HOST = "config.client.host";
+ public static final String CONFIG_CLIENT_PORT = "config.client.port";
+ public static final String CONFIG_CLIENT_LAST_UPDATE = "config.client.last_update";
+ public static final String CONFIG_CLIENT_LICENSE = "config.client.license";
+ public static final String CONFIG_CLIENT_MAC = "config.client.mac";
+ public static final String CONFIG_CLIENT_MACS = "config.client.macs";
+ public static final String CONFIG_CLIENT_CPU_NAME = "config.client.cpu_name";
+ public static final String CONFIG_CLIENT_HOURES_AUTO_SYNC = "config.client.houres_auto_sync";
+ public static final String CONFIG_CLIENT_HOURES_RETRY_AUTO_SYNC = "config.client.houres_retry_auto_sync";
+ public static final String CONFIG_CLIENT_GS_HOST = "config.client.gs_host";
+ public static final String CONFIG_CLIENT_GS_PORT = "config.client.gs_port";
+
+ // Keys used in both app
+ public static final String CONFIG_COMMON_CUSTOMER_CODE = "config.common.customer_code"; // BP
+ public static final String CONFIG_COMMON_CS_CODE = "config.common.cs_code"; // 0000
+ public static final String CONFIG_COMMON_USERS_VERSION = "config.common.user_version";
+ public static final String CONFIG_COMMON_SETTINGS_VERSION = "config.common.settings_version";
+ public static final String CONFIG_COMMON_DATASET_VERSION = "config.common.dataset_version";
+ public static final String CONFIG_COMMON_SYNC_TIME_THRESHOLD = "config.common.sync.time_threshols";
+ public static final String CONFIG_COMMON_TIMEOUT_SESSION_BA = "config.common.timeout_session_ba";
+ public static final String CONFIG_COMMON_TIMEOUT_SESSION_CS = "config.common.timeout_session_cs";
+
+ // Keys used in server app
+ public static final String CONFIG_SERVER_LICENSE_EXPIRATION = "config.server.license.expiation";
+ public static final String CONFIG_SERVER_MAX_INSTANCES = "config.server.max_instances";
+ public static final String CONFIG_SERVER_MAX_USERS = "config.server.max_users";
+ public static final String CONFIG_SERVER_LICENSE_MAX_INSTANCES = "config.server.license.max_instances";
+ public static final String CONFIG_SERVER_LICENSE_MAX_USERS = "config.server.license.max_users";
+ public static final String CONFIG_SERVER_LICENSE_MAX_TIME_THRESHOLD = "config.server.license.max_time_threshols";
+ public static final String CONFIG_SERVER_LICENSE_EXTENDED_MODE = "config.server.license.extended_mode";
+ public static final String CONFIG_SERVER_LICENSE_MAX_EVENTS = "config.server.license.max_events";
+ public static final String CONFIG_SERVER_LICENSE_MAX_WELL_LIFE_LINES = "config.server.license.max_well_life_lines";
+ public static final String CONFIG_SERVER_CREATE_DATASET = "config.server.create_dataset_in_next_startup";
+ public static final String CONFIG_SERVER_PORT = "config.server.port";
+ }
+
+}
diff --git a/securis/src/main/java/net/curisit/securis/db/listeners/CreationTimestampListener.java b/securis/src/main/java/net/curisit/securis/db/listeners/CreationTimestampListener.java
new file mode 100644
index 0000000..23fa941
--- /dev/null
+++ b/securis/src/main/java/net/curisit/securis/db/listeners/CreationTimestampListener.java
@@ -0,0 +1,23 @@
+package net.curisit.securis.db.listeners;
+
+import java.util.Date;
+
+import javax.persistence.PrePersist;
+
+import net.curisit.securis.db.common.CreationTimestampEntity;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+public class CreationTimestampListener {
+
+ @SuppressWarnings("unused")
+ private static final Logger LOG = LogManager.getLogger(CreationTimestampListener.class);
+
+ @PrePersist
+ public void updateTimestamp(CreationTimestampEntity p) {
+ LOG.info("Settings creation timestmap date");
+ p.setCreationTimestamp(new Date());
+ }
+
+}
diff --git a/securis/src/main/java/net/curisit/securis/db/listeners/ModificationTimestampListener.java b/securis/src/main/java/net/curisit/securis/db/listeners/ModificationTimestampListener.java
new file mode 100644
index 0000000..208fddb
--- /dev/null
+++ b/securis/src/main/java/net/curisit/securis/db/listeners/ModificationTimestampListener.java
@@ -0,0 +1,25 @@
+package net.curisit.securis.db.listeners;
+
+import java.util.Date;
+
+import javax.persistence.PrePersist;
+import javax.persistence.PreUpdate;
+
+import net.curisit.securis.db.common.ModificationTimestampEntity;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+public class ModificationTimestampListener {
+
+ @SuppressWarnings("unused")
+ private static final Logger LOG = LogManager.getLogger(ModificationTimestampListener.class);
+
+ @PreUpdate
+ @PrePersist
+ public void updateTimestamp(ModificationTimestampEntity p) {
+ LOG.info("Settings modification timestmap date");
+ p.setModificationTimestamp(new Date());
+ }
+
+}
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 d4a1c04..927122e 100644
--- a/securis/src/main/java/net/curisit/securis/services/LicenseResource.java
+++ b/securis/src/main/java/net/curisit/securis/services/LicenseResource.java
@@ -52,9 +52,9 @@
import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
import net.curisit.securis.services.helpers.LicenseHelper;
import net.curisit.securis.services.helpers.UserHelper;
+import net.curisit.securis.utils.Config;
import net.curisit.securis.utils.EmailManager;
import net.curisit.securis.utils.JsonUtils;
-import net.curisit.securis.utils.Params;
import net.curisit.securis.utils.TokenHelper;
import org.apache.commons.io.IOUtils;
@@ -62,6 +62,9 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.inject.persist.Transactional;
/**
@@ -256,7 +259,7 @@
User user = userHelper.getUser(bsc.getUserPrincipal().getName(), em);
try {
- String subject = MessageFormat.format(Params.get(Params.KEYS.EMAIL_LIC_DEFAULT_SUBJECT), lic.getPack().getAppName());
+ String subject = MessageFormat.format(Config.get(Config.KEYS.EMAIL_LIC_DEFAULT_SUBJECT), lic.getPack().getAppName());
String email_tpl = IOUtils.toString(this.getClass().getResourceAsStream("/lic_email.template.en"));
String body = MessageFormat.format(email_tpl, lic.getFullName(), app.getName());
licFile = licenseHelper.createTemporaryLicenseFile(lic, app.getLicenseFilename());
@@ -272,7 +275,7 @@
}
}
- lic.setModificationTimestamp(new Date());
+ // lic.setModificationTimestamp(new Date());
em.merge(lic);
em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.SEND, "Email sent to: " + lic.getEmail()));
return Response.ok(lic).build();
@@ -295,7 +298,7 @@
@Produces({
MediaType.APPLICATION_JSON
})
- public Response cancel(@PathParam("licId") Integer licId, @FormParam("reason") String reason, @Context BasicSecurityContext bsc)
+ public Response cancel(@PathParam("licId") Integer licId, CancellationLicenseActionBean actionData, @Context BasicSecurityContext bsc)
throws SeCurisServiceException {
EntityManager em = emProvider.get();
@@ -307,13 +310,13 @@
+ " can not be canceled from the current license status");
}
- if (reason == null && (lic.getStatus() == LicenseStatus.ACTIVE || lic.getStatus() == LicenseStatus.PRE_ACTIVE)) {
+ if (actionData.reason == null) {
LOG.error("To cancel an active License we need a reason, lic ID: {}, user: {}", lic.getId(), bsc.getUserPrincipal().getName());
throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "Active license with id " + licId
+ " can not be canceled without a reason");
}
- licenseHelper.cancelLicense(lic, reason, bsc, em);
+ licenseHelper.cancelLicense(lic, actionData.reason, bsc, em);
return Response.ok(lic).build();
}
@@ -605,4 +608,11 @@
f = new File(f, "config-server.lic");
LOG.info("f: {}", f);
}
+
+ @JsonAutoDetect
+ @JsonIgnoreProperties(ignoreUnknown = true)
+ static class CancellationLicenseActionBean {
+ @JsonProperty
+ private String reason;
+ }
}
diff --git a/securis/src/main/java/net/curisit/securis/utils/Config.java b/securis/src/main/java/net/curisit/securis/utils/Config.java
index bd22171..1d43249 100644
--- a/securis/src/main/java/net/curisit/securis/utils/Config.java
+++ b/securis/src/main/java/net/curisit/securis/utils/Config.java
@@ -17,182 +17,193 @@
*/
public class Config {
- private static final Logger LOG = LogManager.getLogger(Config.class);
+ private static final Logger LOG = LogManager.getLogger(Config.class);
- /**
- * Key used to store config file resource location. In a web application, can be set as initial parameter in a servlet loaded on startup
- */
- public static final String KEY_CONFIG_FILE = "/securis-server.properties";
+ /**
+ * Key used to store config file resource location. In a web application,
+ * can be set as initial parameter in a servlet loaded on startup
+ */
+ public static final String KEY_CONFIG_FILE = "/securis-server.properties";
- private static Properties params = null;
+ private static Properties params = null;
- static {
- try {
- loadParameters(KEY_CONFIG_FILE);
- } catch (IOException e) {
- LOG.error("Config file {} was not found in classpath", KEY_CONFIG_FILE);
- System.exit(-2);
- }
- }
+ static {
+ try {
+ loadParameters(KEY_CONFIG_FILE);
+ } catch (IOException e) {
+ LOG.error("Config file {} was not found in classpath", KEY_CONFIG_FILE);
+ System.exit(-2);
+ }
+ }
- /**
- * Loads application global parameters from a classpath resource
- *
- * @param resource
- * : Resource location in classpath, i.e: "/resource/cp-securis.conf"
- * @throws IOException
- */
- public static void loadParameters(String resource) throws IOException {
+ /**
+ * Loads application global parameters from a classpath resource
+ *
+ * @param resource
+ * : Resource location in classpath, i.e:
+ * "/resource/cp-securis.conf"
+ * @throws IOException
+ */
+ public static void loadParameters(String resource) throws IOException {
- LOG.debug("Loading params from " + resource);
- InputStream fileis = Params.class.getResourceAsStream(resource);
+ LOG.debug("Loading params from " + resource);
+ InputStream fileis = Params.class.getResourceAsStream(resource);
- params = new Properties();
- try {
+ params = new Properties();
+ try {
- params.load(fileis);
- LOG.debug("Params loaded OK from {}", resource);
- } catch (IOException e) {
- LOG.error("Error loading config file: " + e);
- params = null;
- throw e;
- }
+ params.load(fileis);
+ LOG.debug("Params loaded OK from {}", resource);
+ } catch (IOException e) {
+ LOG.error("Error loading config file: " + e);
+ params = null;
+ throw e;
+ }
- }
+ }
- public static String getByDomain(String domain, String paramname) {
- return getByDomain(domain, paramname, null);
- }
+ public static String getByDomain(String domain, String paramname) {
+ return getByDomain(domain, paramname, null);
+ }
- public static String getByPrefix(String prefix, String paramname) {
- return get(prefix + "." + paramname, get(paramname));
- }
+ public static String getByPrefix(String prefix, String paramname) {
+ return get(prefix + "." + paramname, get(paramname));
+ }
- public static String getByPrefix(String prefix, String paramname, String defaultVal) {
- return get(prefix + "." + paramname, get(paramname, defaultVal));
- }
+ public static String getByPrefix(String prefix, String paramname, String defaultVal) {
+ return get(prefix + "." + paramname, get(paramname, defaultVal));
+ }
- public static String getByDomain(String domain, String paramname, String defaultval) {
- return get(paramname + "." + domain, defaultval);
- }
+ public static String getByDomain(String domain, String paramname, String defaultval) {
+ return get(paramname + "." + domain, defaultval);
+ }
- public static int getIntByDomain(String domain, String paramname) {
- return getInt(paramname + "." + domain, getInt(paramname));
- }
+ public static int getIntByDomain(String domain, String paramname) {
+ return getInt(paramname + "." + domain, getInt(paramname));
+ }
- public static int getIntByDomain(String domain, String paramname, int defaultval) {
- return getInt(paramname + "." + domain, defaultval);
- }
+ public static int getIntByDomain(String domain, String paramname, int defaultval) {
+ return getInt(paramname + "." + domain, defaultval);
+ }
- /**
- * Gets a List with all values of properties that begins with <code>prefix</code> It reads sequentially. For example:
- *
- * <pre>
- * securis.sort.comparator.0: net.cp.securis.comparators.ComparePttidVsPtn
- * securis.sort.comparator.1: net.cp.securis.comparators.CompareFrequency
- * securis.sort.comparator.2: net.cp.securis.comparators.CompareOutgoingVsIncomming
- * securis.sort.comparator.3: net.cp.securis.comparators.CompareDuration
- * securis.sort.comparator.4: net.cp.securis.comparators.CompareCallVsSms
- * </pre>
- *
- * That config (for prefix: "securis.sort.comparator" ) will return a List<String> with values:
- *
- * <pre>
- * "net.cp.securis.comparators.ComparePttidVsPtn",
- * "net.cp.securis.comparators.CompareFrequency",
- * "net.cp.securis.comparators.CompareOutgoingVsIncomming",
- * "net.cp.securis.comparators.CompareDuration",
- * "net.cp.securis.comparators.CompareCallVsSms"
- * </pre>
- *
- * Note: If there is a gap between suffixes process will stop, that is, only will be returned properties found before gap.
- *
- * @param prefix
- * @return
- */
- public static List<String> getListByPrefix(String prefix) {
- List<String> list = new ArrayList<String>();
+ /**
+ * Gets a List with all values of properties that begins with
+ * <code>prefix</code> It reads sequentially. For example:
+ *
+ * <pre>
+ * securis.sort.comparator.0: net.cp.securis.comparators.ComparePttidVsPtn
+ * securis.sort.comparator.1: net.cp.securis.comparators.CompareFrequency
+ * securis.sort.comparator.2: net.cp.securis.comparators.CompareOutgoingVsIncomming
+ * securis.sort.comparator.3: net.cp.securis.comparators.CompareDuration
+ * securis.sort.comparator.4: net.cp.securis.comparators.CompareCallVsSms
+ * </pre>
+ *
+ * That config (for prefix: "securis.sort.comparator" ) will return a
+ * List<String> with values:
+ *
+ * <pre>
+ * "net.cp.securis.comparators.ComparePttidVsPtn",
+ * "net.cp.securis.comparators.CompareFrequency",
+ * "net.cp.securis.comparators.CompareOutgoingVsIncomming",
+ * "net.cp.securis.comparators.CompareDuration",
+ * "net.cp.securis.comparators.CompareCallVsSms"
+ * </pre>
+ *
+ * Note: If there is a gap between suffixes process will stop, that is, only
+ * will be returned properties found before gap.
+ *
+ * @param prefix
+ * @return
+ */
+ public static List<String> getListByPrefix(String prefix) {
+ List<String> list = new ArrayList<String>();
- String tpl = prefix + ".{0}";
+ String tpl = prefix + ".{0}";
- int i = 0;
- String value = get(MessageFormat.format(tpl, i++));
- while (value != null) {
- list.add(value);
- value = get(MessageFormat.format(tpl, i++));
- }
+ int i = 0;
+ String value = get(MessageFormat.format(tpl, i++));
+ while (value != null) {
+ list.add(value);
+ value = get(MessageFormat.format(tpl, i++));
+ }
- return list;
- }
+ return list;
+ }
- /**
- * Gets param value in config file or environment variables
- *
- * @param paramname
- * Global parameter's name
- * @return Value of paramname or null if paramname is not found neither in config file nor in environment variables
- */
- public static String get(String paramname) {
+ /**
+ * Gets param value in config file or environment variables
+ *
+ * @param paramname
+ * Global parameter's name
+ * @return Value of paramname or null if paramname is not found neither in
+ * config file nor in environment variables
+ */
+ public static String get(String paramname) {
- assert (params != null) : "Parameters have not been loaded. Call method loadParameters(resource) before use Params.";
+ assert (params != null) : "Parameters have not been loaded. Call method loadParameters(resource) before use Params.";
- String value = params.getProperty(paramname);
- if (value == null)
- value = System.getenv(paramname);
- return value;
- }
+ String value = params.getProperty(paramname);
+ if (value == null)
+ value = System.getenv(paramname);
+ return value;
+ }
- /**
- * Gets param value from config file or environment variables
- *
- * @param paramname
- * Global parameter's name
- * @param defaultval
- * @return Value of paramname or defaultval if paramname is not found
- */
- public static String get(String paramname, String defaultval) {
- String value = get(paramname);
- return (value == null ? defaultval : value);
- }
+ /**
+ * Gets param value from config file or environment variables
+ *
+ * @param paramname
+ * Global parameter's name
+ * @param defaultval
+ * @return Value of paramname or defaultval if paramname is not found
+ */
+ public static String get(String paramname, String defaultval) {
+ String value = get(paramname);
+ return (value == null ? defaultval : value);
+ }
- /**
- * Gets param value in config file or environment variables
- *
- * @param paramname
- * Global parameter's name
- * @return Integer value of paramname or -1 if paramname is not found neither in config file nor in environment variables
- */
- public static int getInt(String paramname) {
- String value = get(paramname);
- return (value == null ? -1 : Integer.parseInt(value));
- }
+ /**
+ * Gets param value in config file or environment variables
+ *
+ * @param paramname
+ * Global parameter's name
+ * @return Integer value of paramname or -1 if paramname is not found
+ * neither in config file nor in environment variables
+ */
+ public static int getInt(String paramname) {
+ String value = get(paramname);
+ return (value == null ? -1 : Integer.parseInt(value));
+ }
- /**
- * Gets param value from config file or environment variables
- *
- * @param paramname
- * Global parameter's name
- * @param defaultval
- * @return Integer value of paramname or defaultval if paramname is not found
- */
- public static int getInt(String paramname, int defaultval) {
- String value = get(paramname);
- return (value == null ? defaultval : Integer.parseInt(value));
- }
+ /**
+ * Gets param value from config file or environment variables
+ *
+ * @param paramname
+ * Global parameter's name
+ * @param defaultval
+ * @return Integer value of paramname or defaultval if paramname is not
+ * found
+ */
+ public static int getInt(String paramname, int defaultval) {
+ String value = get(paramname);
+ return (value == null ? defaultval : Integer.parseInt(value));
+ }
- public static class KEYS {
+ public static class KEYS {
+ public static final String SERVER_HOSTNAME = "license.server.hostname";
-
- public static final String SERVER_HOSTNAME = "license.server.hostname";
+ public static final String SERVER_PORT = "license.server.port";
+ public static final String SERVER_SSL_PORT = "license.server.ssl.port";
- public static final String SERVER_PORT = "license.server.port";
- public static final String SERVER_SSL_PORT = "license.server.ssl.port";
-
- public static final String KEYSTORE_PATH = "ssl.keystore.path";
+ public static final String KEYSTORE_PATH = "ssl.keystore.path";
public static final String KEYSTORE_TYPE = "ssl.keystore.type";
public static final String KEYSTORE_PASSWORD = "ssl.keystore.password";
public static final String KEYSTORE_ALIAS = "ssl.keystore.alias";
- }
+
+ public static final String MAILGUN_DOMAIN = "mailgun.domain";
+ public static final String MAILGUN_API_KEY = "mailgun.api.key";
+ public static final String EMAIL_FROM_ADDRESS = "email.from.address";
+ public static final String EMAIL_LIC_DEFAULT_SUBJECT = "email.lic.default.subject";
+ }
}
diff --git a/securis/src/main/java/net/curisit/securis/utils/EmailManager.java b/securis/src/main/java/net/curisit/securis/utils/EmailManager.java
index 8657d03..e6b686a 100644
--- a/securis/src/main/java/net/curisit/securis/utils/EmailManager.java
+++ b/securis/src/main/java/net/curisit/securis/utils/EmailManager.java
@@ -56,9 +56,9 @@
* @throws SeCurisException
*/
public EmailManager() throws SeCurisException {
- String domain = Params.get(Params.KEYS.MAILGUN_DOMAIN);
+ String domain = Config.get(Config.KEYS.MAILGUN_DOMAIN);
if (domain == null) {
- throw new SeCurisException("Please, add '" + Params.KEYS.MAILGUN_DOMAIN + "' parameter to config file");
+ throw new SeCurisException("Please, add '" + Config.KEYS.MAILGUN_DOMAIN + "' parameter to config file");
}
serverUrl = String.format("https://api.mailgun.net/v2/%s/messages", domain);
httpClient = createHttpClient();
@@ -81,7 +81,7 @@
throw new SeCurisException("Error creating SSL socket factory");
}
CredentialsProvider provider = new BasicCredentialsProvider();
- UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("api", Params.get(Params.KEYS.MAILGUN_API_KEY));
+ UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("api", Config.get(Config.KEYS.MAILGUN_API_KEY));
provider.setCredentials(AuthScope.ANY, credentials);
return HttpClientBuilder.create().setDefaultCredentialsProvider(provider).setSSLSocketFactory(sslsf).build();
@@ -105,7 +105,7 @@
builder.setCharset(Charset.forName("utf-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
- builder.addTextBody("from", Params.get(Params.KEYS.EMAIL_FROM_ADDRESS));
+ builder.addTextBody("from", Config.get(Config.KEYS.EMAIL_FROM_ADDRESS));
builder.addTextBody("to", to);
if (cc != null) {
builder.addTextBody("cc", cc);
diff --git a/securis/src/main/resources/db/schema.sql b/securis/src/main/resources/db/schema.sql
index 1eb3bb6..7c5c6a3 100644
--- a/securis/src/main/resources/db/schema.sql
+++ b/securis/src/main/resources/db/schema.sql
@@ -3,7 +3,7 @@
CREATE TABLE IF NOT EXISTS settings (
`key` VARCHAR(100) NOT NULL ,
value VARCHAR(2000) NULL ,
- creation_timestamp DATETIME NOT NULL default now(),
+ modification_timestamp DATETIME NOT NULL default now(),
PRIMARY KEY (``key``) );
drop table IF EXISTS user;
diff --git a/securis/src/main/webapp/js/licenses.js b/securis/src/main/webapp/js/licenses.js
index 31302e4..5df0f34 100644
--- a/securis/src/main/webapp/js/licenses.js
+++ b/securis/src/main/webapp/js/licenses.js
@@ -1,72 +1,72 @@
(function() {
'use strict';
-
- var HTTP_ERRORS = {
- 401: "Unathorized action",
- 418: "Application error",
- 403: "Forbidden action",
- 500: "Server error",
- 404: "Element not found"
- }
+
+ var HTTP_ERRORS = {
+ 401: "Unathorized action",
+ 418: "Application error",
+ 403: "Forbidden action",
+ 500: "Server error",
+ 404: "Element not found"
+ }
var app = angular.module('securis');
app.service('Packs', ['$L','$resource', 'toaster', function($L, $resource, toaster) {
var PACK_STATUS = {
- CREATED: 'CR',
- ACTIVE: 'AC',
- ONHOLD: 'OH',
- EXPIRED: 'EX',
- CANCELLED: 'CA'
+ CREATED: 'CR',
+ ACTIVE: 'AC',
+ ONHOLD: 'OH',
+ EXPIRED: 'EX',
+ CANCELLED: 'CA'
}
var PACK_STATUSES = {
'CR': $L.get('Created'),
- 'AC': $L.get('Active'),
- 'OH': $L.get('On Hold'),
- 'EX': $L.get('Expired'),
- 'CA': $L.get('Cancelled')
- };
+ 'AC': $L.get('Active'),
+ 'OH': $L.get('On Hold'),
+ 'EX': $L.get('Expired'),
+ 'CA': $L.get('Cancelled')
+ };
/**
* These transitions could be get from server, class Pack.Status, but we
* copy them for simplicity, this info won't change easily
*/
var PACK_ACTIONS_BY_STATUS = {
- activate: [PACK_STATUS.CREATED, PACK_STATUS.EXPIRED, PACK_STATUS.ONHOLD],
- putonhold: [PACK_STATUS.ACTIVE],
- cancel: [PACK_STATUS.EXPIRED, PACK_STATUS.ONHOLD, PACK_STATUS.ACTIVE],
- 'delete': [PACK_STATUS.CREATED, PACK_STATUS.CANCELLED]
- }
-
+ activate: [PACK_STATUS.CREATED, PACK_STATUS.EXPIRED, PACK_STATUS.ONHOLD],
+ putonhold: [PACK_STATUS.ACTIVE],
+ cancel: [PACK_STATUS.EXPIRED, PACK_STATUS.ONHOLD, PACK_STATUS.ACTIVE],
+ 'delete': [PACK_STATUS.CREATED, PACK_STATUS.CANCELLED]
+ }
+
var packResource = $resource('pack/:packId/:action',
{
- packId : '@id',
- action : '@action'
+ packId : '@id',
+ action : '@action'
},
{
- activate: {
- method: "POST",
- params: {action: "activate"}
- },
- putonhold: {
- method: "POST",
- params: {action: "putonhold"}
- },
- cancel: {
- method: "POST",
- params: {action: "cancel"}
- }
- }
- );
+ activate: {
+ method: "POST",
+ params: {action: "activate"}
+ },
+ putonhold: {
+ method: "POST",
+ params: {action: "putonhold"}
+ },
+ cancel: {
+ method: "POST",
+ params: {action: "cancel"}
+ }
+ }
+ );
this.getStatusColor = function(status) {
var COLORS_BY_STATUS = {
'CR': '#808080',
- 'AC': '#329e5a',
- 'OH': '#9047c7',
- 'EX': '#ea7824',
- 'CA': '#a21717'
- };
-
+ 'AC': '#329e5a',
+ 'OH': '#9047c7',
+ 'EX': '#ea7824',
+ 'CA': '#a21717'
+ };
+
return COLORS_BY_STATUS[status];
},
this.getStatusName = function(status) {
@@ -79,15 +79,15 @@
toaster.pop('success', 'Packs', $L.get("Pack '{0}' {1} successfully", pack.code, isNew ? $L.get("created") : $L.get("updated")));
}
var _error = function(error) {
- console.log(error);
+ console.log(error);
toaster.pop('error', 'Packs', $L.get("Error {0} pack '{1}'. Reason: {2}", isNew ? $L.get("creating") : $L.get("updating"), pack.code, $L.get(error.headers('X-SECURIS-ERROR-MSG'))));
}
packResource.save(pack, _success, _error);
}
this.isActionAvailable = function(action, pack) {
- var validStatuses = PACK_ACTIONS_BY_STATUS[action];
- return pack && validStatuses && validStatuses.indexOf(pack.status) !== -1;
+ var validStatuses = PACK_ACTIONS_BY_STATUS[action];
+ return pack && validStatuses && validStatuses.indexOf(pack.status) !== -1;
}
var _createSuccessCallback = function(actionName, message, _innerCallback) {
return function() {
@@ -97,8 +97,8 @@
}
var _createErrorCallback = function(pack, actionName, _innerCallback) {
return function(error) {
- console.log(error);
- _innerCallback && _innerCallback();
+ console.log(error);
+ _innerCallback && _innerCallback();
toaster.pop('error', actionName, $L.get("Error on action '{0}', pack '{1}'. Reason: {2}", actionName, pack.code, $L.get(error.headers('X-SECURIS-ERROR-MSG'))));
}
}
@@ -132,85 +132,86 @@
}
}]);
-
+
app.service('Licenses', ['$L', '$resource', 'toaster', function($L, $resource, toaster) {
var LIC_STATUS = {
- CREATED: 'CR',
- ACTIVE: 'AC',
- REQUESTED: 'RE',
- PREACTIVE: 'PA',
- EXPIRED: 'EX',
- CANCELLED: 'CA'
+ CREATED: 'CR',
+ ACTIVE: 'AC',
+ REQUESTED: 'RE',
+ PREACTIVE: 'PA',
+ EXPIRED: 'EX',
+ CANCELLED: 'CA'
}
-
+
var LIC_STATUSES = {
'CR': $L.get('Created'),
- 'AC': $L.get('Active'),
- 'PA': $L.get('Pre-active'),
- 'RE': $L.get('Requested'),
- 'EX': $L.get('Expired'),
- 'CA': $L.get('Cancelled')
- };
+ 'AC': $L.get('Active'),
+ 'PA': $L.get('Pre-active'),
+ 'RE': $L.get('Requested'),
+ 'EX': $L.get('Expired'),
+ 'CA': $L.get('Cancelled')
+ };
/**
* These transitions could be get from server, class License.Status, but
* we copy them for simplicity, this info won't change easily
*/
var LIC_ACTIONS_BY_STATUS = {
- activate: [LIC_STATUS.CREATED, LIC_STATUS.REQUESTED, LIC_STATUS.PREACTIVE],
- send: [LIC_STATUS.ACTIVE, LIC_STATUS.PREACTIVE],
- download: [LIC_STATUS.ACTIVE, LIC_STATUS.PREACTIVE],
- block: [LIC_STATUS.CANCELLED],
- unblock: [LIC_STATUS.CANCELLED],
- cancel: [LIC_STATUS.REQUESTED, LIC_STATUS.EXPIRED, LIC_STATUS.PREACTIVE, LIC_STATUS.ACTIVE],
- 'delete': [LIC_STATUS.CREATED, LIC_STATUS.CANCELLED]
- }
-
- var licenseResource = $resource('license/:licenseId/:action', {
- licenseId : '@id',
+ activate: [LIC_STATUS.CREATED, LIC_STATUS.REQUESTED, LIC_STATUS.PREACTIVE],
+ send: [LIC_STATUS.ACTIVE, LIC_STATUS.PREACTIVE],
+ download: [LIC_STATUS.ACTIVE, LIC_STATUS.PREACTIVE],
+ block: [LIC_STATUS.CANCELLED],
+ unblock: [LIC_STATUS.CANCELLED],
+ cancel: [LIC_STATUS.REQUESTED, LIC_STATUS.EXPIRED, LIC_STATUS.PREACTIVE, LIC_STATUS.ACTIVE],
+ 'delete': [LIC_STATUS.CREATED, LIC_STATUS.CANCELLED]
+ }
+
+ var licenseResource = $resource('license/:licenseId/:action', {
+ licenseId : '@id',
action : '@action'
},
{
- activate: {
- method: "POST",
- params: {action: "activate"}
- },
- cancel: {
- method: "POST",
- params: {action: "cancel"}
- }, // Download a file cannot be done form AJAX, We should do it manually, using $http
- download: {
- method: "GET",
- params: {action: "download"}
- },
- block: {
- method: "POST",
- params: {action: "block"}
- },
- sendEmail: {
- method: "POST",
- params: {action: "send"}
- },
- unblock: {
- method: "POST",
- params: {action: "unblock"}
- }
- });
+ activate: {
+ method: "POST",
+ params: {action: "activate"}
+ },
+ cancel: {
+ method: "POST",
+ params: {action: "cancel"}
+ }, // Download a file cannot be done form AJAX, We should do it
+ // manually, using $http
+ download: {
+ method: "GET",
+ params: {action: "download"}
+ },
+ block: {
+ method: "POST",
+ params: {action: "block"}
+ },
+ sendEmail: {
+ method: "POST",
+ params: {action: "send"}
+ },
+ unblock: {
+ method: "POST",
+ params: {action: "unblock"}
+ }
+ });
- this.isActionAvailable = function(action, lic) {
- var validStatuses = LIC_ACTIONS_BY_STATUS[action];
- return lic && validStatuses && validStatuses.indexOf(lic.status) !== -1;
- }
- this.getStatusColor = function(status) {
+ this.isActionAvailable = function(action, lic) {
+ var validStatuses = LIC_ACTIONS_BY_STATUS[action];
+ return lic && validStatuses && validStatuses.indexOf(lic.status) !== -1;
+ }
+ this.getStatusColor = function(status) {
var COLORS_BY_STATUS = {
'CR': '#808080',
- 'AC': '#329e5a',
- 'RE': '#2981d4',
- 'EX': '#ea7824',
- 'CA': '#a21717'
- };
-
+ 'AC': '#329e5a',
+ 'RE': '#2981d4',
+ 'EX': '#ea7824',
+ 'CA': '#a21717'
+ };
+
return COLORS_BY_STATUS[status];
},
this.getStatusName = function(status) {
@@ -223,7 +224,7 @@
toaster.pop('success', 'Licenses', $L.get("License '{0}' {1} successfully", license.code, isNew ? $L.get("created") : $L.get("updated")));
}
var _error = function(error) {
- console.log(error);
+ console.log(error);
toaster.pop('error', 'Licenses', $L.get("Error {0} license '{1}'. Reason: {2}", isNew ? $L.get("creating") : $L.get("updating"), license.code, $L.get(error.headers('X-SECURIS-ERROR-MSG'))));
}
licenseResource.save(license, _success, _error);
@@ -237,12 +238,12 @@
}
var _createErrorCallback = function(license, actionName, _innerCallback) {
return function(error) {
- console.log(error);
- _innerCallback && _innerCallback();
+ console.log(error);
+ _innerCallback && _innerCallback();
toaster.pop('error', actionName, $L.get("Error on action '{0}', license '{1}'. Reason: {2}", actionName, license.code, $L.get(error.headers('X-SECURIS-ERROR-MSG'))));
}
}
-
+
this.getLicensesList = function(pack, _onsuccess, _onerror) {
return licenseResource.query({packId: pack.id}, _onsuccess, _onerror);
}
@@ -274,9 +275,9 @@
console.log('Download license: ' + license.id);
var _success = _createSuccessCallback($L.get('Download'), $L.get("License '{0}' {1} successfully", license.code, $L.get("downloaded")), _onsuccess);
var _error = _createErrorCallback(license, $L.get('Download license file'), _onerror);
- //window.open(downloadPath, '_blank', '');
+ // window.open(downloadPath, '_blank', '');
var _success2 = function(data, headers) {
- //console.log(headers.get("Content-Disposition"));
+ // console.log(headers.get("Content-Disposition"));
// attachment; filename="license.lic"
var filename = JSON.parse(headers('Content-Disposition').match(/".*"$/g)[0]);
data.$promise.then(function(content) {
@@ -300,526 +301,530 @@
licenseResource.delete({licenseId: license.id}, _success, _error);
}
}]);
-
+
app.directive('fileLoader',
- function($timeout, $parse) {
- return {
- restrict : 'A', // only activate on element attribute
- require : '',
- link : function(scope, element, attrs) {
- console.log('scope.license: ' + scope.$parent.license);
- var setter = $parse(attrs.fileLoader).assign;
- element.bind('change', function(evt) {
- if (!window.FileReader) { // Browser is not
- // compatible
- BootstrapDialog.alert($L.get("Open your .req file with a text editor and copy&paste the content in the form text field?"));
- return;
- }
- console.log('File selected');
- // console.log('scope.license: ' +
- // scope.$parent.license);
- var field = $parse(attrs.fileLoader);
- // console.log('field: ' + field);
- var fileList = evt.target.files;
- if (fileList != null && fileList[0]) {
- var reader = new FileReader();
- reader.onerror = function(data) {
- setter(scope.$parent, 'ERROR');
- scope.$apply();
- }
- reader.onload = function(data) {
- setter(scope.$parent, reader.result);
- scope.$apply();
- }
-
- reader.readAsText(fileList[0]);
- } else {
- setter(scope.$parent, '');
- scope.$apply();
- }
- });
-
- }
- };
- });
+ function($timeout, $parse) {
+ return {
+ restrict : 'A', // only activate on element attribute
+ require : '',
+ link : function(scope, element, attrs) {
+ console.log('scope.license: ' + scope.$parent.license);
+ var setter = $parse(attrs.fileLoader).assign;
+ element.bind('change', function(evt) {
+ if (!window.FileReader) { // Browser is not
+ // compatible
+ BootstrapDialog.alert($L.get("Open your .req file with a text editor and copy&paste the content in the form text field?"));
+ return;
+ }
+ console.log('File selected');
+ // console.log('scope.license: ' +
+ // scope.$parent.license);
+ var field = $parse(attrs.fileLoader);
+ // console.log('field: ' + field);
+ var fileList = evt.target.files;
+ if (fileList != null && fileList[0]) {
+ var reader = new FileReader();
+ reader.onerror = function(data) {
+ setter(scope.$parent, 'ERROR');
+ scope.$apply();
+ }
+ reader.onload = function(data) {
+ setter(scope.$parent, reader.result);
+ scope.$apply();
+ }
+
+ reader.readAsText(fileList[0]);
+ } else {
+ setter(scope.$parent, '');
+ scope.$apply();
+ }
+ });
+
+ }
+ };
+ });
app.controller('PackAndLicensesCtrl', [
- '$scope',
- '$http',
- 'toaster',
- '$store',
- '$L',
- function($scope, $http, toaster, $store, $L) {
- $store.set('location', '/licenses');
-
- $scope.maxLengthErrorMsg = function(displayname, fieldMaxlength) {
- return $L.get("{0} length is too long (max: {1}).", $L.get(displayname), fieldMaxlength);
- }
- $scope.mandatoryFieldErrorMsg = function(displayname) {
- return $L.get("'{0}' is required.", $L.get(displayname));
- }
- $scope.field1ShouldBeGreaterThanField2 = function(field1, field2) {
- return $L.get("{0} should be greater than {1}", $L.get(field1), $L.get(field2));
- }
- $scope.ellipsis = function(txt, len) {
- if (!txt || txt.length <= len) return txt;
- return txt.substring(0, len) + '...';
- }
- $scope.currentPack = $store.get('currentPack');
+ '$scope',
+ '$http',
+ 'toaster',
+ '$store',
+ '$L',
+ function($scope, $http, toaster, $store, $L) {
+ $store.set('location', '/licenses');
- }]);
-
- app.controller('PacksCtrl', [
- '$scope',
- '$http',
- '$resource',
- 'toaster',
- 'Catalogs',
- 'Packs',
- '$store',
- '$L',
- function($scope, $http, $resource, toaster, Catalogs, Packs, $store, $L) {
- $scope.Packs = Packs;
-
-
- $scope.mandatory = {
- code: true,
- num_licenses: true,
- init_valid_date: true,
- end_valid_date: true,
- status: true,
- organization_id: true,
- license_type_id: true
- }
- $scope.maxlength = {
- code: 50,
- comments: 1024
- }
- $scope.refs = {};
- Catalogs.init().then(function() {
- var refFields = [{resource: 'organization', name: 'organization_id'},{resource: 'licensetype', name: 'license_type_id'}];
- Catalogs.loadRefs(function(refs) {
- $scope.refs = refs;
- }, refFields);
- });
-
- // Used to create the form with the appropriate data
- $scope.isNew = undefined;
-
- // Selected pack from listing
- // pack is the edited pack, in creation contains the data for
- // the new pack
- $scope.pack = null;
-
- $scope.packs = Packs.getPacksList();
-
- $scope.save = function() {
- Packs.savePackData($scope.pack, $scope.isNew, function() {
- if (!$scope.isNew) {
- $scope.showForm = false;
- } else {
- $scope.newPack();
- }
- $scope.packs = Packs.getPacksList();
- });
- }
-
- /**
- * Execute an action over the pack, activation, onhold,
- * cancellation
- */
- $scope.execute = function(action, pack) {
- var _execute = function(extra_data) {
- if (extra_data) {
- Packs[action](pack || $scope.pack, extra_data, function() {
- if (!$scope.isNew) $scope.showForm = false;
- $scope.packs = Packs.getPacksList();
- });
- } else {
- Packs[action](pack || $scope.pack, function() {
- if (!$scope.isNew) $scope.showForm = false;
- $scope.packs = Packs.getPacksList();
- });
- }
- }
- if (action === 'delete') {
- BootstrapDialog.confirm($L.get("The pack '{0}' will be deleted, are you sure ?", pack.code), function(answer) {
- if (answer) {
- _execute();
- }
- });
- } else {
- if (action === 'cancel') {
- BootstrapDialog.show({
- title: $L.get("Pack cancellation"),
- type: BootstrapDialog.TYPE_DANGER,
- message: function(dialog) {
- var $content = $('<div></div>');
- var $message = $('<div></div>');
- $message.append($('<label/>').text($L.get("The pack '{0}' and all its licenses will be cancelled, this action cannot be undone", pack.code)));
- $content.append($message);
-
- var $message = $('<div style="margin-top:10pt;"/>');
- var pageToLoad = dialog.getData('pageToLoad');
- $message.append($('<label style="margin-right:5pt;"/>').text($L.get("Cancellation reason:") + " "));
- $message.append($('<input type="text" style="width:100%;" maxlength="512" id="_pack_cancellation_reason"/>'));
- $content.append($message);
- return $content;
- },
- closable: true,
- buttons: [{
- id: 'btn-cancel',
- label: $L.get('Close'),
- cssClass: 'btn-default',
- action: function(dialogRef) {
- dialogRef.close();
- }
- }, {
- id: 'btn-ok',
- label: $L.get('Cancel pack'),
- cssClass: 'btn-primary',
- action: function(dialogRef){
- var reason = $('#_pack_cancellation_reason').val();
- console.log('Ready to cancel pack, by reason: ' + reason);
- if (!reason) {
- $('#_pack_cancellation_reason').focus();
- } else {
- _execute({reason: reason});
- dialogRef.close();
- }
- }
- }]
- });
- } else {
- _execute();
- }
- }
- }
-
-
- $scope.newPack = function() {
- $scope.isNew = true;
- $scope.showForm = true;
- $scope.pack = {
- license_preactivation: true,
- status: 'CR',
- num_licenses: 1,
- init_valid_date: new Date(),
- default_valid_period: 30,
- license_type_id: null,
- organization_id: null // !$scope.refs.organization_id
- // ||
- // !$scope.refs.organization_id.length
- // ? null :
- // $scope.refs.organization_id[0].id
- }
- setTimeout(function() {
- $('#code').focus();
- }, 0);
- }
-
- $scope.editPack = function(selectedPack) {
- $scope.isNew = false;
- $scope.showForm = true;
- if (!(selectedPack.init_valid_date instanceof Date)) {
- selectedPack.init_valid_date = new Date(selectedPack.init_valid_date);
- }
- if (!(selectedPack.end_valid_date instanceof Date)) {
- selectedPack.end_valid_date = new Date(selectedPack.end_valid_date);
- }
-
- $scope.pack = selectedPack;
-
- // $scope.pack.organization_name =
- // $scope.getLabelFromId('organization_id',
- // $scope.pack.organization_id);
- $scope.pack.license_type_name = $scope.getLabelFromId('license_type_id', $scope.pack.license_type_id);
- $scope.pack.status_name = Packs.getStatusName($scope.pack.status);
-
- setTimeout(function() {
- $('#code').focus();
- }, 0);
- }
-
- $scope.deletePack = function(selectedPack) {
- $scope.showForm = false;
- BootstrapDialog.confirm($L.get("The pack '{0}' will be deleted, are you sure?", selectedPack.code), function(result){
- if(result) {
- var promise = packResource.remove({}, {id: selectedPack.id}).$promise;
- promise.then(function(data) {
- $scope.selectPack(null);
- $scope.packs = packResource.query();
- toaster.pop('success', Catalogs.getName(), $L.get("Pack '{0}' deleted successfully", selectedPack.code));
- },function(error) {
- console.log(error);
- toaster.pop('error', Catalogs.getName(), $L.get("Error deleting pack, reason: {0}. Details: {1}", $L.get(HTTP_ERRORS[error.status]), error.headers('X-SECURIS-ERROR-MSG')), 10000);
- });
- }
- });
- $scope.isNew = false;
- }
-
-
- $scope.cancel = function() {
- $scope.showForm = false;
- }
-
- $scope.selectPack = function(pack) {
- $scope.$parent.currentPack = pack;
- $store.put('currentPack', pack);
- $scope.$parent.$broadcast('pack_changed', pack);
- }
-
- $scope.getLabelFromId = function(field, myid) {
- var label = null;
- $scope.refs[field].forEach(function (elem) {
- if (elem.id === myid) {
- label = elem.label;
- }
- });
- return label;
- }
-
- $scope.createMetadataRow = function() {
- if (!$scope.formu.metadata) {
- $scope.formu.metadata = [];
- }
- $scope.formu.metadata.push({key: '', value: '', mandatory: true});
- }
- $scope.removeMetadataKey = function(row_md) {
- $scope.formu.metadata.splice( $scope.formu.metadata.indexOf(row_md), 1 );
- }
- $scope.updateMetadata = function() {
- // Called when Application ID change in current field
- var newLTId = $scope.pack['license_type_id'];
- if (newLTId) {
- // Only if there is a "valid" value selected we should
- // update the metadata
- Catalogs.getResource('licensetype').get({licenseTypeId: newLTId}).$promise.then(function(lt) {
- $scope.pack.metadata = [];
- lt.metadata.forEach(function(md) {
- $scope.pack.metadata.push({
- key: md.key,
- value: md.value,
- readonly: !!md.value,
- mandatory: md.mandatory
- });
- });
- });
- }
- }
- } ]);
-
- app.controller('LicensesCtrl', [
- '$scope',
- '$http',
- '$resource',
- 'toaster',
- 'Licenses',
- '$store',
- '$L',
- function($scope, $http, $resource, toaster, Licenses, $store, $L) {
- $scope.Licenses = Licenses;
- $scope.$on('pack_changed', function(evt, message) {
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
- $scope.creationAvailable = $scope.currentPack.status == 'AC';
- if ($scope.showForm) {
- if ($scope.isNew) {
- $scope.license.pack_id = $scope.currentPack.id
- } else {
- $scope.showForm = false;
- }
- }
- })
-
- $scope.mandatory = {
- code: true,
- email: true
- }
- $scope.maxlength = {
- code: 50,
- request_data: 500,
- comments: 1024
- }
- $scope.refs = {};
-
- // Used to create the form with the
- // appropriate data
- $scope.isNew = undefined;
-
- // Selected license from listing
- // license is the edited license, in
- // creation contains the data for
- // the new license
- $scope.license = null;
- if ($scope.currentPack) {
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
- }
-
- $scope.save = function() {
- Licenses.saveLicenseData($scope.license, $scope.isNew, function() {
- if (!$scope.isNew) {
- $scope.showForm = false;
- } else {
- $scope.newLicense();
- }
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
- });
- }
-
- $scope.newLicense = function() {
- if (!$scope.currentPack) {
- BootstrapDialog.show({
- title: $L.get('New license'),
- type: BootstrapDialog.TYPE_WARNING,
- message: $L.get('Please, select a pack before to create a new license'),
- buttons: [{
- label: 'OK',
- action: function(dialog) {
- dialog.close();
- }
- }]
- });
- return;
- }
- if (!$scope.creationAvailable) {
- BootstrapDialog.show({
- title: $L.get('Pack not active'),
- type: BootstrapDialog.TYPE_WARNING,
- message: $L.get('Current pack is not active, so licenses cannot be created'),
- buttons: [{
- label: 'OK',
- action: function(dialog) {
- dialog.close();
- }
- }]
- });
- return;
- }
-
- $scope.isNew = true;
- $scope.showForm = true;
- $scope.license = {
- pack_id: $scope.currentPack.id
- }
- setTimeout(function() {
- $('#licenseForm * #code').focus();
- }, 0);
- }
-
- $scope.editLicense = function(selectedlicense) {
- $scope.isNew = false;
- $scope.showForm = true;
- $scope.license = selectedlicense;
- $scope.license.status_name = Licenses.getStatusName($scope.license.status);
-
- setTimeout(function() {
- $('#licenseForm * #code').focus();
- }, 0);
- }
-
- $scope.deletelicense = function(selectedlicense) {
- $scope.showForm = false;
- BootstrapDialog.confirm($L.get("The license '{0}' will be deleted, are you sure?", selectedlicense.code), function(result){
- if(result) {
- var promise = licenseResource.remove({}, {id: selectedlicense.id}).$promise;
- promise.then(function(data) {
- $scope.selectlicense(null);
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
- toaster.pop('success', Catalogs.getName(), $L.get("License '{0}' deleted successfully", selectedlicense.code));
- },function(error) {
- console.log(error);
- toaster.pop('error', Catalogs.getName(), $L.get("Error deleting license, reason: {0}. Details: {1}", $L.get(HTTP_ERRORS[error.status]), error.headers('X-SECURIS-ERROR-MSG')), 10000);
- });
- }
- });
- $scope.isNew = false;
- }
-
- $scope.execute = function(action, license) {
- if (!license) {
- license = $scope.license;
+ $scope.maxLengthErrorMsg = function(displayname, fieldMaxlength) {
+ return $L.get("{0} length is too long (max: {1}).", $L.get(displayname), fieldMaxlength);
}
- var _execute = function(extra_data) {
- if (extra_data) {
- Licenses[action](license, extra_data, function() {
- if (!$scope.isNew) $scope.showForm = false;
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
- });
- } else {
- Licenses[action](license, function() {
- if (!$scope.isNew) $scope.showForm = false;
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
- });
- }
- }
- if (action === 'delete') {
- BootstrapDialog.confirm($L.get("The license '{0}' will be deleted, are you sure?", license.code), function(result){
- if(result) {
- _execute();
- }
- });
- } else {
- if (action === 'cancel') {
- BootstrapDialog.show({
- title: $L.get("License cancellation"),
- type: BootstrapDialog.TYPE_DANGER,
- message: function(dialog) {
- var $content = $('<div></div>');
- var $message = $('<div></div>');
- var pageToLoad = dialog.getData('pageToLoad');
- $message.append($('<label/>').text($L.get("This action cannot be undone.", $scope.pack.code)));
- $content.append($message);
+ $scope.mandatoryFieldErrorMsg = function(displayname) {
+ return $L.get("'{0}' is required.", $L.get(displayname));
+ }
+ $scope.field1ShouldBeGreaterThanField2 = function(field1, field2) {
+ return $L.get("{0} should be greater than {1}", $L.get(field1), $L.get(field2));
+ }
+ $scope.ellipsis = function(txt, len) {
+ if (!txt || txt.length <= len) return txt;
+ return txt.substring(0, len) + '...';
+ }
+ $scope.currentPack = $store.get('currentPack');
- var $message = $('<div style="margin-top:10pt;"/>');
- $message.append($('<label style="margin-right:5pt;"/>').text($L.get("Cancellation reason:") + " "));
- $message.append($('<input type="text" style="width:100%;" maxlength="512" id="_lic_cancellation_reason"/>'));
- $content.append($message);
- return $content;
- },
- closable: true,
- buttons: [{
- id: 'btn-cancel',
- label: $L.get('Close'),
- cssClass: 'btn-default',
- action: function(dialogRef) {
- dialogRef.close();
- }
- }, {
- id: 'btn-ok',
- label: $L.get('Cancel license'),
- cssClass: 'btn-primary',
- action: function(dialogRef){
- var reason = $('#_lic_cancellation_reason').val();
- console.log('Ready to cancel license, by reason: ' + reason);
- if (!reason) {
- $('#_lic_cancellation_reason').focus();
- } else {
- _execute({reason: reason});
- dialogRef.close();
- }
- }
- }]
- });
- } else {
- _execute();
- }
- }
- }
-
+ }]);
- $scope.cancel = function() {
- $scope.showForm = false;
- }
-
- $scope.showStatus = function(lic) {
-
- }
- $scope.showStatusLong = function(license) {
-
- }
-
- } ]);
+ app.controller('PacksCtrl', [
+ '$scope',
+ '$http',
+ '$resource',
+ 'toaster',
+ 'Catalogs',
+ 'Packs',
+ '$store',
+ '$L',
+ function($scope, $http, $resource, toaster, Catalogs, Packs, $store, $L) {
+ $scope.Packs = Packs;
+
+
+ $scope.mandatory = {
+ code: true,
+ num_licenses: true,
+ init_valid_date: true,
+ end_valid_date: true,
+ status: true,
+ organization_id: true,
+ license_type_id: true
+ }
+ $scope.maxlength = {
+ code: 50,
+ comments: 1024
+ }
+ $scope.refs = {};
+ Catalogs.init().then(function() {
+ var refFields = [{resource: 'organization', name: 'organization_id'},{resource: 'licensetype', name: 'license_type_id'}];
+ Catalogs.loadRefs(function(refs) {
+ $scope.refs = refs;
+ }, refFields);
+ });
+
+ // Used to create the form with the
+ // appropriate data
+ $scope.isNew = undefined;
+
+ // Selected pack from listing
+ // pack is the edited pack, in creation
+ // contains the data for
+ // the new pack
+ $scope.pack = null;
+
+ $scope.packs = Packs.getPacksList();
+
+ $scope.save = function() {
+ Packs.savePackData($scope.pack, $scope.isNew, function() {
+ if (!$scope.isNew) {
+ $scope.showForm = false;
+ } else {
+ $scope.newPack();
+ }
+ $scope.packs = Packs.getPacksList();
+ });
+ }
+
+ /**
+ * Execute an action over the pack,
+ * activation, onhold, cancellation
+ */
+ $scope.execute = function(action, pack) {
+ var _execute = function(extra_data) {
+ if (extra_data) {
+ Packs[action](pack || $scope.pack, extra_data, function() {
+ if (!$scope.isNew) $scope.showForm = false;
+ $scope.packs = Packs.getPacksList();
+ });
+ } else {
+ Packs[action](pack || $scope.pack, function() {
+ if (!$scope.isNew) $scope.showForm = false;
+ $scope.packs = Packs.getPacksList();
+ });
+ }
+ }
+ if (action === 'delete') {
+ BootstrapDialog.confirm($L.get("The pack '{0}' will be deleted, are you sure ?", pack.code), function(answer) {
+ if (answer) {
+ _execute();
+ }
+ });
+ } else {
+ if (action === 'cancel') {
+ BootstrapDialog.show({
+ title: $L.get("Pack cancellation"),
+ type: BootstrapDialog.TYPE_DANGER,
+ message: function(dialog) {
+ var $content = $('<div></div>');
+ var $message = $('<div></div>');
+ $message.append($('<label/>').text($L.get("The pack '{0}' and all its licenses will be cancelled, this action cannot be undone", pack.code)));
+ $content.append($message);
+
+ var $message = $('<div style="margin-top:10pt;"/>');
+ var pageToLoad = dialog.getData('pageToLoad');
+ $message.append($('<label style="margin-right:5pt;"/>').text($L.get("Cancellation reason:") + " "));
+ $message.append($('<input type="text" style="width:100%;" maxlength="512" id="_pack_cancellation_reason"/>'));
+ $content.append($message);
+ return $content;
+ },
+ closable: true,
+ buttons: [{
+ id: 'btn-cancel',
+ label: $L.get('Close'),
+ cssClass: 'btn-default',
+ action: function(dialogRef) {
+ dialogRef.close();
+ }
+ }, {
+ id: 'btn-ok',
+ label: $L.get('Cancel pack'),
+ cssClass: 'btn-primary',
+ action: function(dialogRef){
+ var reason = $('#_pack_cancellation_reason').val();
+ console.log('Ready to cancel pack, by reason: ' + reason);
+ if (!reason) {
+ $('#_pack_cancellation_reason').focus();
+ } else {
+ _execute({reason: reason});
+ dialogRef.close();
+ }
+ }
+ }]
+ });
+ } else {
+ _execute();
+ }
+ }
+ }
+
+
+ $scope.newPack = function() {
+ $scope.isNew = true;
+ $scope.showForm = true;
+ $scope.pack = {
+ license_preactivation: true,
+ status: 'CR',
+ num_licenses: 1,
+ init_valid_date: new Date(),
+ default_valid_period: 30,
+ license_type_id: null,
+ organization_id: null // !$scope.refs.organization_id
+ // ||
+ // !$scope.refs.organization_id.length
+ // ? null :
+ // $scope.refs.organization_id[0].id
+ }
+ setTimeout(function() {
+ $('#code').focus();
+ }, 0);
+ }
+
+ $scope.editPack = function(selectedPack) {
+ $scope.isNew = false;
+ $scope.showForm = true;
+ if (!(selectedPack.init_valid_date instanceof Date)) {
+ selectedPack.init_valid_date = new Date(selectedPack.init_valid_date);
+ }
+ if (!(selectedPack.end_valid_date instanceof Date)) {
+ selectedPack.end_valid_date = new Date(selectedPack.end_valid_date);
+ }
+
+ $scope.pack = selectedPack;
+
+ // $scope.pack.organization_name =
+ // $scope.getLabelFromId('organization_id',
+ // $scope.pack.organization_id);
+ $scope.pack.license_type_name = $scope.getLabelFromId('license_type_id', $scope.pack.license_type_id);
+ $scope.pack.status_name = Packs.getStatusName($scope.pack.status);
+
+ setTimeout(function() {
+ $('#code').focus();
+ }, 0);
+ }
+
+ $scope.deletePack = function(selectedPack) {
+ $scope.showForm = false;
+ BootstrapDialog.confirm($L.get("The pack '{0}' will be deleted, are you sure?", selectedPack.code), function(result){
+ if(result) {
+ var promise = packResource.remove({}, {id: selectedPack.id}).$promise;
+ promise.then(function(data) {
+ $scope.selectPack(null);
+ $scope.packs = packResource.query();
+ toaster.pop('success', Catalogs.getName(), $L.get("Pack '{0}' deleted successfully", selectedPack.code));
+ },function(error) {
+ console.log(error);
+ toaster.pop('error', Catalogs.getName(), $L.get("Error deleting pack, reason: {0}. Details: {1}", $L.get(HTTP_ERRORS[error.status]), error.headers('X-SECURIS-ERROR-MSG')), 10000);
+ });
+ }
+ });
+ $scope.isNew = false;
+ }
+
+
+ $scope.cancel = function() {
+ $scope.showForm = false;
+ }
+
+ $scope.selectPack = function(pack) {
+ $scope.$parent.currentPack = pack;
+ $store.put('currentPack', pack);
+ $scope.$parent.$broadcast('pack_changed', pack);
+ }
+
+ $scope.getLabelFromId = function(field, myid) {
+ var label = null;
+ $scope.refs[field].forEach(function (elem) {
+ if (elem.id === myid) {
+ label = elem.label;
+ }
+ });
+ return label;
+ }
+
+ $scope.createMetadataRow = function() {
+ if (!$scope.formu.metadata) {
+ $scope.formu.metadata = [];
+ }
+ $scope.formu.metadata.push({key: '', value: '', mandatory: true});
+ }
+ $scope.removeMetadataKey = function(row_md) {
+ $scope.formu.metadata.splice( $scope.formu.metadata.indexOf(row_md), 1 );
+ }
+ $scope.updateMetadata = function() {
+ // Called when Application ID change
+ // in current field
+ var newLTId = $scope.pack['license_type_id'];
+ if (newLTId) {
+ // Only if there is a "valid"
+ // value selected we should
+ // update the metadata
+ Catalogs.getResource('licensetype').get({licenseTypeId: newLTId}).$promise.then(function(lt) {
+ $scope.pack.metadata = [];
+ lt.metadata.forEach(function(md) {
+ $scope.pack.metadata.push({
+ key: md.key,
+ value: md.value,
+ readonly: !!md.value,
+ mandatory: md.mandatory
+ });
+ });
+ });
+ }
+ }
+ } ]);
+
+ app.controller('LicensesCtrl', [
+ '$scope',
+ '$http',
+ '$resource',
+ 'toaster',
+ 'Licenses',
+ '$store',
+ '$L',
+ function($scope, $http, $resource, toaster, Licenses, $store, $L) {
+ $scope.Licenses = Licenses;
+ $scope.$on('pack_changed', function(evt, message) {
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
+ $scope.creationAvailable = $scope.currentPack.status == 'AC';
+ if ($scope.showForm) {
+ if ($scope.isNew) {
+ $scope.license.pack_id = $scope.currentPack.id
+ } else {
+ $scope.showForm = false;
+ }
+ }
+ })
+
+ $scope.mandatory = {
+ code: true,
+ email: true
+ }
+ $scope.maxlength = {
+ code: 50,
+ request_data: 500,
+ comments: 1024
+ }
+ $scope.refs = {};
+
+ // Used to create the form with the
+ // appropriate data
+ $scope.isNew = undefined;
+
+ // Selected license from listing
+ // license is the edited license, in
+ // creation contains the data for
+ // the new license
+ $scope.license = null;
+ if ($scope.currentPack) {
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
+ }
+
+ $scope.save = function() {
+ Licenses.saveLicenseData($scope.license, $scope.isNew, function() {
+ if (!$scope.isNew) {
+ $scope.showForm = false;
+ } else {
+ $scope.newLicense();
+ }
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
+ });
+ }
+
+ $scope.newLicense = function() {
+ if (!$scope.currentPack) {
+ BootstrapDialog.show({
+ title: $L.get('New license'),
+ type: BootstrapDialog.TYPE_WARNING,
+ message: $L.get('Please, select a pack before to create a new license'),
+ buttons: [{
+ label: 'OK',
+ action: function(dialog) {
+ dialog.close();
+ }
+ }]
+ });
+ return;
+ }
+ if (!$scope.creationAvailable) {
+ BootstrapDialog.show({
+ title: $L.get('Pack not active'),
+ type: BootstrapDialog.TYPE_WARNING,
+ message: $L.get('Current pack is not active, so licenses cannot be created'),
+ buttons: [{
+ label: 'OK',
+ action: function(dialog) {
+ dialog.close();
+ }
+ }]
+ });
+ return;
+ }
+
+ $scope.isNew = true;
+ $scope.showForm = true;
+ $scope.license = {
+ pack_id: $scope.currentPack.id
+ }
+ setTimeout(function() {
+ $('#licenseForm * #code').focus();
+ }, 0);
+ }
+
+ $scope.editLicense = function(selectedlicense) {
+ $scope.isNew = false;
+ $scope.showForm = true;
+ $scope.license = selectedlicense;
+ $scope.license.status_name = Licenses.getStatusName($scope.license.status);
+
+ setTimeout(function() {
+ $('#licenseForm * #code').focus();
+ }, 0);
+ }
+
+ $scope.deletelicense = function(selectedlicense) {
+ $scope.showForm = false;
+ BootstrapDialog.confirm($L.get("The license '{0}' will be deleted, are you sure?", selectedlicense.code), function(result){
+ if(result) {
+ var promise = licenseResource.remove({}, {id: selectedlicense.id}).$promise;
+ promise.then(function(data) {
+ $scope.selectlicense(null);
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
+ toaster.pop('success', Catalogs.getName(), $L.get("License '{0}' deleted successfully", selectedlicense.code));
+ },function(error) {
+ console.log(error);
+ toaster.pop('error', Catalogs.getName(), $L.get("Error deleting license, reason: {0}. Details: {1}", $L.get(HTTP_ERRORS[error.status]), error.headers('X-SECURIS-ERROR-MSG')), 10000);
+ });
+ }
+ });
+ $scope.isNew = false;
+ }
+
+ $scope.execute = function(action, license) {
+ if (!license) {
+ license = $scope.license;
+ }
+ var _execute = function(extra_data) {
+ if (extra_data) {
+ Licenses[action](license, extra_data, function() {
+ if (!$scope.isNew) $scope.showForm = false;
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
+ });
+ } else {
+ Licenses[action](license, function() {
+ if (!$scope.isNew) $scope.showForm = false;
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
+ });
+ }
+ }
+ if (action === 'delete') {
+ BootstrapDialog.confirm($L.get("The license '{0}' will be deleted, are you sure?", license.code), function(result){
+ if(result) {
+ _execute();
+ }
+ });
+ } else {
+ if (action === 'cancel') {
+ BootstrapDialog.show({
+ title: $L.get("License cancellation"),
+ type: BootstrapDialog.TYPE_DANGER,
+ message: function(dialog) {
+ var $content = $('<div></div>');
+ var $message = $('<div></div>');
+ var pageToLoad = dialog.getData('pageToLoad');
+ $message.append($('<label/>').text($L.get("This action cannot be undone.", license.code)));
+ $content.append($message);
+
+ var $message = $('<div style="margin-top:10pt;"/>');
+ $message.append($('<label style="margin-right:5pt;"/>').text($L.get("Cancellation reason:") + " "));
+ $message.append($('<input type="text" style="width:100%;" maxlength="512" id="_lic_cancellation_reason"/>'));
+ $content.append($message);
+ return $content;
+ },
+ closable: true,
+ buttons: [{
+ id: 'btn-cancel',
+ label: $L.get('Close'),
+ cssClass: 'btn-default',
+ action: function(dialogRef) {
+ dialogRef.close();
+ }
+ }, {
+ id: 'btn-ok',
+ label: $L.get('Cancel license'),
+ cssClass: 'btn-primary',
+ action: function(dialogRef){
+ var reason = $('#_lic_cancellation_reason').val();
+ console.log('Ready to cancel license, by reason: ' + reason);
+ if (!reason) {
+ $('#_lic_cancellation_reason').focus();
+ } else {
+ _execute({reason: reason});
+ dialogRef.close();
+ }
+ }
+ }]
+ });
+ } else {
+ _execute();
+ }
+ }
+ }
+
+
+ $scope.cancel = function() {
+ $scope.showForm = false;
+ }
+
+ $scope.showStatus = function(lic) {
+
+ }
+ $scope.showStatusLong = function(license) {
+
+ }
+
+ } ]);
})();
--
Gitblit v1.3.2