rsanchez
2014-11-18 fdbc8ca146b8e3aff0425e2faf94c0b4a6e3dd28
#396 fix - Corrected cancel action and added Settings entity
6 files added
6 files modified
changed files
securis/src/main/java/net/curisit/securis/db/License.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/Settings.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/common/CreationTimestampEntity.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/common/ModificationTimestampEntity.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/common/SystemParams.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/listeners/CreationTimestampListener.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/listeners/ModificationTimestampListener.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/LicenseResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/utils/Config.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/utils/EmailManager.java patch | view | blame | history
securis/src/main/resources/db/schema.sql patch | view | blame | history
securis/src/main/webapp/js/licenses.js patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/License.java
....@@ -8,6 +8,7 @@
88
99 import javax.persistence.Column;
1010 import javax.persistence.Entity;
11
+import javax.persistence.EntityListeners;
1112 import javax.persistence.EntityManager;
1213 import javax.persistence.FetchType;
1314 import javax.persistence.GeneratedValue;
....@@ -23,6 +24,10 @@
2324 import javax.persistence.TypedQuery;
2425
2526 import net.curisit.integrity.commons.Utils;
27
+import net.curisit.securis.db.common.CreationTimestampEntity;
28
+import net.curisit.securis.db.common.ModificationTimestampEntity;
29
+import net.curisit.securis.db.listeners.CreationTimestampListener;
30
+import net.curisit.securis.db.listeners.ModificationTimestampListener;
2631 import net.curisit.securis.services.exception.SeCurisServiceException;
2732 import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
2833
....@@ -33,16 +38,20 @@
3338 import com.fasterxml.jackson.annotation.JsonAutoDetect;
3439 import com.fasterxml.jackson.annotation.JsonIgnore;
3540 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
41
+import com.fasterxml.jackson.annotation.JsonInclude;
42
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
3643 import com.fasterxml.jackson.annotation.JsonProperty;
37
-import com.fasterxml.jackson.databind.annotation.JsonSerialize;
3844
3945 /**
4046 * Entity implementation class for Entity: license
4147 *
4248 */
4349 @JsonAutoDetect
44
-@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
50
+@JsonInclude(Include.NON_NULL)
4551 @Entity
52
+@EntityListeners({
53
+ CreationTimestampListener.class, ModificationTimestampListener.class
54
+})
4655 @Table(name = "license")
4756 @JsonIgnoreProperties(ignoreUnknown = true)
4857 @NamedQueries({
....@@ -50,7 +59,8 @@
5059 @NamedQuery(name = "list-licenses-by-req-data", query = "SELECT l FROM License l where l.reqDataHash = :hash"),
5160 @NamedQuery(name = "list-active-licenses-by-req-data", query = "SELECT l FROM License l where l.reqDataHash = :hash and l.status in ('AC', 'PA')")
5261 })
53
-public class License implements Serializable {
62
+public class License implements CreationTimestampEntity, ModificationTimestampEntity, Serializable {
63
+
5464 private static final long serialVersionUID = 2700310404904877227L;
5565
5666 private static final Logger LOG = LogManager.getLogger(License.class);
....@@ -134,10 +144,12 @@
134144 this.code = code;
135145 }
136146
147
+ @Override
137148 public Date getCreationTimestamp() {
138149 return creationTimestamp;
139150 }
140151
152
+ @Override
141153 public void setCreationTimestamp(Date creationTimestamp) {
142154 this.creationTimestamp = creationTimestamp;
143155 }
....@@ -216,10 +228,12 @@
216228 this.status = status;
217229 }
218230
231
+ @Override
219232 public Date getModificationTimestamp() {
220233 return modificationTimestamp;
221234 }
222235
236
+ @Override
223237 public void setModificationTimestamp(Date modificationTimestamp) {
224238 this.modificationTimestamp = modificationTimestamp;
225239 }
securis/src/main/java/net/curisit/securis/db/Settings.java
....@@ -0,0 +1,82 @@
1
+package net.curisit.securis.db;
2
+
3
+import java.io.Serializable;
4
+import java.util.Date;
5
+
6
+import javax.persistence.Column;
7
+import javax.persistence.Entity;
8
+import javax.persistence.EntityListeners;
9
+import javax.persistence.Id;
10
+import javax.persistence.NamedQueries;
11
+import javax.persistence.NamedQuery;
12
+import javax.persistence.Table;
13
+
14
+import net.curisit.securis.db.common.ModificationTimestampEntity;
15
+import net.curisit.securis.db.listeners.ModificationTimestampListener;
16
+
17
+import org.apache.logging.log4j.LogManager;
18
+import org.apache.logging.log4j.Logger;
19
+
20
+import com.fasterxml.jackson.annotation.JsonProperty;
21
+
22
+/**
23
+ * Entity implementation class for Entity: settings settings is a table that has
24
+ * rows with 3 columns: "key", "value", "timestamp"
25
+ *
26
+ */
27
+@Entity()
28
+@EntityListeners({
29
+ ModificationTimestampListener.class
30
+})
31
+@Table(name = "settings")
32
+@NamedQueries({
33
+ @NamedQuery(name = "get-param", query = "SELECT p FROM Settings p where p.key = :key")
34
+})
35
+public class Settings implements ModificationTimestampEntity, Serializable {
36
+ @SuppressWarnings("unused")
37
+ private static final Logger LOG = LogManager.getLogger(Settings.class);
38
+
39
+ private static final long serialVersionUID = 1L;
40
+
41
+ @Id
42
+ String key;
43
+
44
+ String value;
45
+
46
+ @Column(name = "modification_timestamp")
47
+ @JsonProperty("modification_timestamp")
48
+ private Date modificationTimestamp;
49
+
50
+ public String getKey() {
51
+ return key;
52
+ }
53
+
54
+ public void setKey(String key) {
55
+ this.key = key;
56
+ }
57
+
58
+ public String getValue() {
59
+ return value;
60
+ }
61
+
62
+ public void setValue(String value) {
63
+ this.value = value;
64
+ }
65
+
66
+ @Override
67
+ public Date getModificationTimestamp() {
68
+ return modificationTimestamp;
69
+ }
70
+
71
+ @Override
72
+ public void setModificationTimestamp(Date modificationTimestamp) {
73
+ this.modificationTimestamp = modificationTimestamp;
74
+ }
75
+
76
+ @Override
77
+ public String toString() {
78
+
79
+ return String.format("{key: %s, value: %s, ts: %s}", key, value, modificationTimestamp);
80
+ }
81
+
82
+}
securis/src/main/java/net/curisit/securis/db/common/CreationTimestampEntity.java
....@@ -0,0 +1,10 @@
1
+package net.curisit.securis.db.common;
2
+
3
+import java.util.Date;
4
+
5
+public interface CreationTimestampEntity {
6
+
7
+ public Date getCreationTimestamp();
8
+
9
+ public void setCreationTimestamp(Date creationTimestamp);
10
+}
securis/src/main/java/net/curisit/securis/db/common/ModificationTimestampEntity.java
....@@ -0,0 +1,10 @@
1
+package net.curisit.securis.db.common;
2
+
3
+import java.util.Date;
4
+
5
+public interface ModificationTimestampEntity {
6
+
7
+ public Date getModificationTimestamp();
8
+
9
+ public void setModificationTimestamp(Date modificationTimestamp);
10
+}
securis/src/main/java/net/curisit/securis/db/common/SystemParams.java
....@@ -0,0 +1,235 @@
1
+package net.curisit.securis.db.common;
2
+
3
+import java.util.Date;
4
+
5
+import javax.inject.Inject;
6
+import javax.inject.Singleton;
7
+import javax.persistence.EntityManager;
8
+
9
+import net.curisit.integrity.commons.Utils;
10
+import net.curisit.securis.db.Settings;
11
+
12
+import org.apache.logging.log4j.LogManager;
13
+import org.apache.logging.log4j.Logger;
14
+
15
+import com.google.inject.Provider;
16
+import com.google.inject.persist.Transactional;
17
+
18
+@Singleton
19
+public class SystemParams {
20
+
21
+ @SuppressWarnings("unused")
22
+ private static final Logger LOG = LogManager.getLogger(SystemParams.class);
23
+
24
+ @Inject
25
+ private Provider<EntityManager> emp;
26
+
27
+ /**
28
+ * Returns the system parameter value for given key
29
+ *
30
+ * @param key
31
+ * @return the value of the param or null if it doesn't exist
32
+ */
33
+ public String getParam(String key) {
34
+ return getParam(key, null);
35
+ }
36
+
37
+ /**
38
+ * Returns the system parameter as int value for given key
39
+ *
40
+ * @param key
41
+ * @return the value of the param or null if it doesn't exist
42
+ */
43
+ public Integer getParamAsInt(String key) {
44
+ String value = getParam(key, null);
45
+ return value == null ? null : Integer.parseInt(value);
46
+ }
47
+
48
+ /**
49
+ *
50
+ * @param key
51
+ * @param defaulValue
52
+ * returned if key doesn't exist in params table
53
+ * @return
54
+ */
55
+ public Integer getParamAsInt(String key, Integer defaulValue) {
56
+ String value = getParam(key, null);
57
+ return value == null ? defaulValue : Integer.parseInt(value);
58
+ }
59
+
60
+ /**
61
+ * Returns the system parameter as Date value for given key
62
+ *
63
+ * @param key
64
+ * @return the value of the param or null if it doesn't exist
65
+ */
66
+ public Date getParamAsDate(String key) {
67
+ String value = getParam(key, null);
68
+ return value == null ? null : Utils.toDateFromIso(value);
69
+ }
70
+
71
+ /**
72
+ * Returns the system parameter as boolean value for given key
73
+ *
74
+ * @param key
75
+ * @return the value of the param or null if it doesn't exist
76
+ */
77
+ public Boolean getParamAsBool(String key) {
78
+ String value = getParam(key, null);
79
+ return value == null ? null : Boolean.parseBoolean(value);
80
+ }
81
+
82
+ /**
83
+ *
84
+ * @param key
85
+ * @param defaulValue
86
+ * returned if key doesn't exist in params table
87
+ * @return
88
+ */
89
+ public Boolean getParamAsBool(String key, boolean defaulValue) {
90
+ String value = getParam(key, null);
91
+ return value == null ? defaulValue : Boolean.parseBoolean(value);
92
+ }
93
+
94
+ /**
95
+ * Returns the system parameter as boolean value for given key
96
+ *
97
+ * @param key
98
+ * @return the value of the param or null if it doesn't exist
99
+ */
100
+ public Double getParamAsDouble(String key) {
101
+ String value = getParam(key, null);
102
+ return value == null ? null : Double.parseDouble(value);
103
+ }
104
+
105
+ /**
106
+ * Returns the system parameter value for given key
107
+ *
108
+ * @param key
109
+ * @param defaultValue
110
+ * returned if key doesn't exist in params table
111
+ * @return
112
+ */
113
+ public String getParam(String key, String defaultValue) {
114
+ EntityManager em = emp.get();
115
+ Settings p = em.find(Settings.class, key);
116
+ return p == null ? defaultValue : p.getValue();
117
+ }
118
+
119
+ /**
120
+ * Returns the system parameter value passed as parameter to method
121
+ *
122
+ * @param key
123
+ * @param defaultValue
124
+ * @return
125
+ */
126
+ @Transactional
127
+ public void setParam(String key, String value) {
128
+ EntityManager em = this.emp.get();
129
+ Settings p = em.find(Settings.class, key);
130
+ if (p == null) {
131
+ p = new Settings();
132
+ p.setKey(key);
133
+ p.setValue(value);
134
+ em.persist(p);
135
+ } else {
136
+ p.setValue(value);
137
+ em.merge(p);
138
+ }
139
+ em.flush();
140
+ }
141
+
142
+ /**
143
+ * Save a parameter as a Date
144
+ *
145
+ * @param key
146
+ * @param value
147
+ */
148
+ public void setParam(String key, Date value) {
149
+ setParam(key, Utils.toIsoFormat(value));
150
+ }
151
+
152
+ /**
153
+ * Save a parameter as a integer
154
+ *
155
+ * @param key
156
+ * @param value
157
+ */
158
+ public void setParam(String key, int value) {
159
+ setParam(key, String.valueOf(value));
160
+ }
161
+
162
+ /**
163
+ * Save a parameter as a boolean
164
+ *
165
+ * @param key
166
+ * @param value
167
+ */
168
+ public void setParam(String key, boolean value) {
169
+ setParam(key, String.valueOf(value));
170
+ }
171
+
172
+ /**
173
+ * Save a parameter as a double
174
+ *
175
+ * @param key
176
+ * @param value
177
+ */
178
+ public void setParam(String key, double value) {
179
+ setParam(key, String.valueOf(value));
180
+ }
181
+
182
+ /**
183
+ * Remove a parameter from params table
184
+ *
185
+ * @param key
186
+ * @return
187
+ */
188
+ @Transactional
189
+ public void removeParam(String key) {
190
+ EntityManager em = this.emp.get();
191
+ Settings p = em.find(Settings.class, key);
192
+ if (p != null) {
193
+ em.remove(p);
194
+ }
195
+ }
196
+
197
+ public static class Keys {
198
+ // Keys used in basic app
199
+ public static final String CONFIG_CLIENT_HOST = "config.client.host";
200
+ public static final String CONFIG_CLIENT_PORT = "config.client.port";
201
+ public static final String CONFIG_CLIENT_LAST_UPDATE = "config.client.last_update";
202
+ public static final String CONFIG_CLIENT_LICENSE = "config.client.license";
203
+ public static final String CONFIG_CLIENT_MAC = "config.client.mac";
204
+ public static final String CONFIG_CLIENT_MACS = "config.client.macs";
205
+ public static final String CONFIG_CLIENT_CPU_NAME = "config.client.cpu_name";
206
+ public static final String CONFIG_CLIENT_HOURES_AUTO_SYNC = "config.client.houres_auto_sync";
207
+ public static final String CONFIG_CLIENT_HOURES_RETRY_AUTO_SYNC = "config.client.houres_retry_auto_sync";
208
+ public static final String CONFIG_CLIENT_GS_HOST = "config.client.gs_host";
209
+ public static final String CONFIG_CLIENT_GS_PORT = "config.client.gs_port";
210
+
211
+ // Keys used in both app
212
+ public static final String CONFIG_COMMON_CUSTOMER_CODE = "config.common.customer_code"; // BP
213
+ public static final String CONFIG_COMMON_CS_CODE = "config.common.cs_code"; // 0000
214
+ public static final String CONFIG_COMMON_USERS_VERSION = "config.common.user_version";
215
+ public static final String CONFIG_COMMON_SETTINGS_VERSION = "config.common.settings_version";
216
+ public static final String CONFIG_COMMON_DATASET_VERSION = "config.common.dataset_version";
217
+ public static final String CONFIG_COMMON_SYNC_TIME_THRESHOLD = "config.common.sync.time_threshols";
218
+ public static final String CONFIG_COMMON_TIMEOUT_SESSION_BA = "config.common.timeout_session_ba";
219
+ public static final String CONFIG_COMMON_TIMEOUT_SESSION_CS = "config.common.timeout_session_cs";
220
+
221
+ // Keys used in server app
222
+ public static final String CONFIG_SERVER_LICENSE_EXPIRATION = "config.server.license.expiation";
223
+ public static final String CONFIG_SERVER_MAX_INSTANCES = "config.server.max_instances";
224
+ public static final String CONFIG_SERVER_MAX_USERS = "config.server.max_users";
225
+ public static final String CONFIG_SERVER_LICENSE_MAX_INSTANCES = "config.server.license.max_instances";
226
+ public static final String CONFIG_SERVER_LICENSE_MAX_USERS = "config.server.license.max_users";
227
+ public static final String CONFIG_SERVER_LICENSE_MAX_TIME_THRESHOLD = "config.server.license.max_time_threshols";
228
+ public static final String CONFIG_SERVER_LICENSE_EXTENDED_MODE = "config.server.license.extended_mode";
229
+ public static final String CONFIG_SERVER_LICENSE_MAX_EVENTS = "config.server.license.max_events";
230
+ public static final String CONFIG_SERVER_LICENSE_MAX_WELL_LIFE_LINES = "config.server.license.max_well_life_lines";
231
+ public static final String CONFIG_SERVER_CREATE_DATASET = "config.server.create_dataset_in_next_startup";
232
+ public static final String CONFIG_SERVER_PORT = "config.server.port";
233
+ }
234
+
235
+}
securis/src/main/java/net/curisit/securis/db/listeners/CreationTimestampListener.java
....@@ -0,0 +1,23 @@
1
+package net.curisit.securis.db.listeners;
2
+
3
+import java.util.Date;
4
+
5
+import javax.persistence.PrePersist;
6
+
7
+import net.curisit.securis.db.common.CreationTimestampEntity;
8
+
9
+import org.apache.logging.log4j.LogManager;
10
+import org.apache.logging.log4j.Logger;
11
+
12
+public class CreationTimestampListener {
13
+
14
+ @SuppressWarnings("unused")
15
+ private static final Logger LOG = LogManager.getLogger(CreationTimestampListener.class);
16
+
17
+ @PrePersist
18
+ public void updateTimestamp(CreationTimestampEntity p) {
19
+ LOG.info("Settings creation timestmap date");
20
+ p.setCreationTimestamp(new Date());
21
+ }
22
+
23
+}
securis/src/main/java/net/curisit/securis/db/listeners/ModificationTimestampListener.java
....@@ -0,0 +1,25 @@
1
+package net.curisit.securis.db.listeners;
2
+
3
+import java.util.Date;
4
+
5
+import javax.persistence.PrePersist;
6
+import javax.persistence.PreUpdate;
7
+
8
+import net.curisit.securis.db.common.ModificationTimestampEntity;
9
+
10
+import org.apache.logging.log4j.LogManager;
11
+import org.apache.logging.log4j.Logger;
12
+
13
+public class ModificationTimestampListener {
14
+
15
+ @SuppressWarnings("unused")
16
+ private static final Logger LOG = LogManager.getLogger(ModificationTimestampListener.class);
17
+
18
+ @PreUpdate
19
+ @PrePersist
20
+ public void updateTimestamp(ModificationTimestampEntity p) {
21
+ LOG.info("Settings modification timestmap date");
22
+ p.setModificationTimestamp(new Date());
23
+ }
24
+
25
+}
securis/src/main/java/net/curisit/securis/services/LicenseResource.java
....@@ -52,9 +52,9 @@
5252 import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
5353 import net.curisit.securis.services.helpers.LicenseHelper;
5454 import net.curisit.securis.services.helpers.UserHelper;
55
+import net.curisit.securis.utils.Config;
5556 import net.curisit.securis.utils.EmailManager;
5657 import net.curisit.securis.utils.JsonUtils;
57
-import net.curisit.securis.utils.Params;
5858 import net.curisit.securis.utils.TokenHelper;
5959
6060 import org.apache.commons.io.IOUtils;
....@@ -62,6 +62,9 @@
6262 import org.apache.logging.log4j.LogManager;
6363 import org.apache.logging.log4j.Logger;
6464
65
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
66
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
67
+import com.fasterxml.jackson.annotation.JsonProperty;
6568 import com.google.inject.persist.Transactional;
6669
6770 /**
....@@ -256,7 +259,7 @@
256259
257260 User user = userHelper.getUser(bsc.getUserPrincipal().getName(), em);
258261 try {
259
- String subject = MessageFormat.format(Params.get(Params.KEYS.EMAIL_LIC_DEFAULT_SUBJECT), lic.getPack().getAppName());
262
+ String subject = MessageFormat.format(Config.get(Config.KEYS.EMAIL_LIC_DEFAULT_SUBJECT), lic.getPack().getAppName());
260263 String email_tpl = IOUtils.toString(this.getClass().getResourceAsStream("/lic_email.template.en"));
261264 String body = MessageFormat.format(email_tpl, lic.getFullName(), app.getName());
262265 licFile = licenseHelper.createTemporaryLicenseFile(lic, app.getLicenseFilename());
....@@ -272,7 +275,7 @@
272275 }
273276 }
274277
275
- lic.setModificationTimestamp(new Date());
278
+ // lic.setModificationTimestamp(new Date());
276279 em.merge(lic);
277280 em.persist(licenseHelper.createLicenseHistoryAction(lic, user, LicenseHistory.Actions.SEND, "Email sent to: " + lic.getEmail()));
278281 return Response.ok(lic).build();
....@@ -295,7 +298,7 @@
295298 @Produces({
296299 MediaType.APPLICATION_JSON
297300 })
298
- public Response cancel(@PathParam("licId") Integer licId, @FormParam("reason") String reason, @Context BasicSecurityContext bsc)
301
+ public Response cancel(@PathParam("licId") Integer licId, CancellationLicenseActionBean actionData, @Context BasicSecurityContext bsc)
299302 throws SeCurisServiceException {
300303
301304 EntityManager em = emProvider.get();
....@@ -307,13 +310,13 @@
307310 + " can not be canceled from the current license status");
308311 }
309312
310
- if (reason == null && (lic.getStatus() == LicenseStatus.ACTIVE || lic.getStatus() == LicenseStatus.PRE_ACTIVE)) {
313
+ if (actionData.reason == null) {
311314 LOG.error("To cancel an active License we need a reason, lic ID: {}, user: {}", lic.getId(), bsc.getUserPrincipal().getName());
312315 throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "Active license with id " + licId
313316 + " can not be canceled without a reason");
314317 }
315318
316
- licenseHelper.cancelLicense(lic, reason, bsc, em);
319
+ licenseHelper.cancelLicense(lic, actionData.reason, bsc, em);
317320 return Response.ok(lic).build();
318321 }
319322
....@@ -605,4 +608,11 @@
605608 f = new File(f, "config-server.lic");
606609 LOG.info("f: {}", f);
607610 }
611
+
612
+ @JsonAutoDetect
613
+ @JsonIgnoreProperties(ignoreUnknown = true)
614
+ static class CancellationLicenseActionBean {
615
+ @JsonProperty
616
+ private String reason;
617
+ }
608618 }
securis/src/main/java/net/curisit/securis/utils/Config.java
....@@ -17,182 +17,193 @@
1717 */
1818 public class Config {
1919
20
- private static final Logger LOG = LogManager.getLogger(Config.class);
20
+ private static final Logger LOG = LogManager.getLogger(Config.class);
2121
22
- /**
23
- * Key used to store config file resource location. In a web application, can be set as initial parameter in a servlet loaded on startup
24
- */
25
- public static final String KEY_CONFIG_FILE = "/securis-server.properties";
22
+ /**
23
+ * Key used to store config file resource location. In a web application,
24
+ * can be set as initial parameter in a servlet loaded on startup
25
+ */
26
+ public static final String KEY_CONFIG_FILE = "/securis-server.properties";
2627
27
- private static Properties params = null;
28
+ private static Properties params = null;
2829
29
- static {
30
- try {
31
- loadParameters(KEY_CONFIG_FILE);
32
- } catch (IOException e) {
33
- LOG.error("Config file {} was not found in classpath", KEY_CONFIG_FILE);
34
- System.exit(-2);
35
- }
36
- }
30
+ static {
31
+ try {
32
+ loadParameters(KEY_CONFIG_FILE);
33
+ } catch (IOException e) {
34
+ LOG.error("Config file {} was not found in classpath", KEY_CONFIG_FILE);
35
+ System.exit(-2);
36
+ }
37
+ }
3738
38
- /**
39
- * Loads application global parameters from a classpath resource
40
- *
41
- * @param resource
42
- * : Resource location in classpath, i.e: "/resource/cp-securis.conf"
43
- * @throws IOException
44
- */
45
- public static void loadParameters(String resource) throws IOException {
39
+ /**
40
+ * Loads application global parameters from a classpath resource
41
+ *
42
+ * @param resource
43
+ * : Resource location in classpath, i.e:
44
+ * "/resource/cp-securis.conf"
45
+ * @throws IOException
46
+ */
47
+ public static void loadParameters(String resource) throws IOException {
4648
47
- LOG.debug("Loading params from " + resource);
48
- InputStream fileis = Params.class.getResourceAsStream(resource);
49
+ LOG.debug("Loading params from " + resource);
50
+ InputStream fileis = Params.class.getResourceAsStream(resource);
4951
50
- params = new Properties();
51
- try {
52
+ params = new Properties();
53
+ try {
5254
53
- params.load(fileis);
54
- LOG.debug("Params loaded OK from {}", resource);
55
- } catch (IOException e) {
56
- LOG.error("Error loading config file: " + e);
57
- params = null;
58
- throw e;
59
- }
55
+ params.load(fileis);
56
+ LOG.debug("Params loaded OK from {}", resource);
57
+ } catch (IOException e) {
58
+ LOG.error("Error loading config file: " + e);
59
+ params = null;
60
+ throw e;
61
+ }
6062
61
- }
63
+ }
6264
63
- public static String getByDomain(String domain, String paramname) {
64
- return getByDomain(domain, paramname, null);
65
- }
65
+ public static String getByDomain(String domain, String paramname) {
66
+ return getByDomain(domain, paramname, null);
67
+ }
6668
67
- public static String getByPrefix(String prefix, String paramname) {
68
- return get(prefix + "." + paramname, get(paramname));
69
- }
69
+ public static String getByPrefix(String prefix, String paramname) {
70
+ return get(prefix + "." + paramname, get(paramname));
71
+ }
7072
71
- public static String getByPrefix(String prefix, String paramname, String defaultVal) {
72
- return get(prefix + "." + paramname, get(paramname, defaultVal));
73
- }
73
+ public static String getByPrefix(String prefix, String paramname, String defaultVal) {
74
+ return get(prefix + "." + paramname, get(paramname, defaultVal));
75
+ }
7476
75
- public static String getByDomain(String domain, String paramname, String defaultval) {
76
- return get(paramname + "." + domain, defaultval);
77
- }
77
+ public static String getByDomain(String domain, String paramname, String defaultval) {
78
+ return get(paramname + "." + domain, defaultval);
79
+ }
7880
79
- public static int getIntByDomain(String domain, String paramname) {
80
- return getInt(paramname + "." + domain, getInt(paramname));
81
- }
81
+ public static int getIntByDomain(String domain, String paramname) {
82
+ return getInt(paramname + "." + domain, getInt(paramname));
83
+ }
8284
83
- public static int getIntByDomain(String domain, String paramname, int defaultval) {
84
- return getInt(paramname + "." + domain, defaultval);
85
- }
85
+ public static int getIntByDomain(String domain, String paramname, int defaultval) {
86
+ return getInt(paramname + "." + domain, defaultval);
87
+ }
8688
87
- /**
88
- * Gets a List with all values of properties that begins with <code>prefix</code> It reads sequentially. For example:
89
- *
90
- * <pre>
91
- * securis.sort.comparator.0: net.cp.securis.comparators.ComparePttidVsPtn
92
- * securis.sort.comparator.1: net.cp.securis.comparators.CompareFrequency
93
- * securis.sort.comparator.2: net.cp.securis.comparators.CompareOutgoingVsIncomming
94
- * securis.sort.comparator.3: net.cp.securis.comparators.CompareDuration
95
- * securis.sort.comparator.4: net.cp.securis.comparators.CompareCallVsSms
96
- * </pre>
97
- *
98
- * That config (for prefix: "securis.sort.comparator" ) will return a List<String> with values:
99
- *
100
- * <pre>
101
- * "net.cp.securis.comparators.ComparePttidVsPtn",
102
- * "net.cp.securis.comparators.CompareFrequency",
103
- * "net.cp.securis.comparators.CompareOutgoingVsIncomming",
104
- * "net.cp.securis.comparators.CompareDuration",
105
- * "net.cp.securis.comparators.CompareCallVsSms"
106
- * </pre>
107
- *
108
- * Note: If there is a gap between suffixes process will stop, that is, only will be returned properties found before gap.
109
- *
110
- * @param prefix
111
- * @return
112
- */
113
- public static List<String> getListByPrefix(String prefix) {
114
- List<String> list = new ArrayList<String>();
89
+ /**
90
+ * Gets a List with all values of properties that begins with
91
+ * <code>prefix</code> It reads sequentially. For example:
92
+ *
93
+ * <pre>
94
+ * securis.sort.comparator.0: net.cp.securis.comparators.ComparePttidVsPtn
95
+ * securis.sort.comparator.1: net.cp.securis.comparators.CompareFrequency
96
+ * securis.sort.comparator.2: net.cp.securis.comparators.CompareOutgoingVsIncomming
97
+ * securis.sort.comparator.3: net.cp.securis.comparators.CompareDuration
98
+ * securis.sort.comparator.4: net.cp.securis.comparators.CompareCallVsSms
99
+ * </pre>
100
+ *
101
+ * That config (for prefix: "securis.sort.comparator" ) will return a
102
+ * List<String> with values:
103
+ *
104
+ * <pre>
105
+ * "net.cp.securis.comparators.ComparePttidVsPtn",
106
+ * "net.cp.securis.comparators.CompareFrequency",
107
+ * "net.cp.securis.comparators.CompareOutgoingVsIncomming",
108
+ * "net.cp.securis.comparators.CompareDuration",
109
+ * "net.cp.securis.comparators.CompareCallVsSms"
110
+ * </pre>
111
+ *
112
+ * Note: If there is a gap between suffixes process will stop, that is, only
113
+ * will be returned properties found before gap.
114
+ *
115
+ * @param prefix
116
+ * @return
117
+ */
118
+ public static List<String> getListByPrefix(String prefix) {
119
+ List<String> list = new ArrayList<String>();
115120
116
- String tpl = prefix + ".{0}";
121
+ String tpl = prefix + ".{0}";
117122
118
- int i = 0;
119
- String value = get(MessageFormat.format(tpl, i++));
120
- while (value != null) {
121
- list.add(value);
122
- value = get(MessageFormat.format(tpl, i++));
123
- }
123
+ int i = 0;
124
+ String value = get(MessageFormat.format(tpl, i++));
125
+ while (value != null) {
126
+ list.add(value);
127
+ value = get(MessageFormat.format(tpl, i++));
128
+ }
124129
125
- return list;
126
- }
130
+ return list;
131
+ }
127132
128
- /**
129
- * Gets param value in config file or environment variables
130
- *
131
- * @param paramname
132
- * Global parameter's name
133
- * @return Value of paramname or null if paramname is not found neither in config file nor in environment variables
134
- */
135
- public static String get(String paramname) {
133
+ /**
134
+ * Gets param value in config file or environment variables
135
+ *
136
+ * @param paramname
137
+ * Global parameter's name
138
+ * @return Value of paramname or null if paramname is not found neither in
139
+ * config file nor in environment variables
140
+ */
141
+ public static String get(String paramname) {
136142
137
- assert (params != null) : "Parameters have not been loaded. Call method loadParameters(resource) before use Params.";
143
+ assert (params != null) : "Parameters have not been loaded. Call method loadParameters(resource) before use Params.";
138144
139
- String value = params.getProperty(paramname);
140
- if (value == null)
141
- value = System.getenv(paramname);
142
- return value;
143
- }
145
+ String value = params.getProperty(paramname);
146
+ if (value == null)
147
+ value = System.getenv(paramname);
148
+ return value;
149
+ }
144150
145
- /**
146
- * Gets param value from config file or environment variables
147
- *
148
- * @param paramname
149
- * Global parameter's name
150
- * @param defaultval
151
- * @return Value of paramname or defaultval if paramname is not found
152
- */
153
- public static String get(String paramname, String defaultval) {
154
- String value = get(paramname);
155
- return (value == null ? defaultval : value);
156
- }
151
+ /**
152
+ * Gets param value from config file or environment variables
153
+ *
154
+ * @param paramname
155
+ * Global parameter's name
156
+ * @param defaultval
157
+ * @return Value of paramname or defaultval if paramname is not found
158
+ */
159
+ public static String get(String paramname, String defaultval) {
160
+ String value = get(paramname);
161
+ return (value == null ? defaultval : value);
162
+ }
157163
158
- /**
159
- * Gets param value in config file or environment variables
160
- *
161
- * @param paramname
162
- * Global parameter's name
163
- * @return Integer value of paramname or -1 if paramname is not found neither in config file nor in environment variables
164
- */
165
- public static int getInt(String paramname) {
166
- String value = get(paramname);
167
- return (value == null ? -1 : Integer.parseInt(value));
168
- }
164
+ /**
165
+ * Gets param value in config file or environment variables
166
+ *
167
+ * @param paramname
168
+ * Global parameter's name
169
+ * @return Integer value of paramname or -1 if paramname is not found
170
+ * neither in config file nor in environment variables
171
+ */
172
+ public static int getInt(String paramname) {
173
+ String value = get(paramname);
174
+ return (value == null ? -1 : Integer.parseInt(value));
175
+ }
169176
170
- /**
171
- * Gets param value from config file or environment variables
172
- *
173
- * @param paramname
174
- * Global parameter's name
175
- * @param defaultval
176
- * @return Integer value of paramname or defaultval if paramname is not found
177
- */
178
- public static int getInt(String paramname, int defaultval) {
179
- String value = get(paramname);
180
- return (value == null ? defaultval : Integer.parseInt(value));
181
- }
177
+ /**
178
+ * Gets param value from config file or environment variables
179
+ *
180
+ * @param paramname
181
+ * Global parameter's name
182
+ * @param defaultval
183
+ * @return Integer value of paramname or defaultval if paramname is not
184
+ * found
185
+ */
186
+ public static int getInt(String paramname, int defaultval) {
187
+ String value = get(paramname);
188
+ return (value == null ? defaultval : Integer.parseInt(value));
189
+ }
182190
183
- public static class KEYS {
191
+ public static class KEYS {
184192
193
+ public static final String SERVER_HOSTNAME = "license.server.hostname";
185194
186
-
187
- public static final String SERVER_HOSTNAME = "license.server.hostname";
195
+ public static final String SERVER_PORT = "license.server.port";
196
+ public static final String SERVER_SSL_PORT = "license.server.ssl.port";
188197
189
- public static final String SERVER_PORT = "license.server.port";
190
- public static final String SERVER_SSL_PORT = "license.server.ssl.port";
191
-
192
- public static final String KEYSTORE_PATH = "ssl.keystore.path";
198
+ public static final String KEYSTORE_PATH = "ssl.keystore.path";
193199 public static final String KEYSTORE_TYPE = "ssl.keystore.type";
194200 public static final String KEYSTORE_PASSWORD = "ssl.keystore.password";
195201 public static final String KEYSTORE_ALIAS = "ssl.keystore.alias";
196
- }
202
+
203
+ public static final String MAILGUN_DOMAIN = "mailgun.domain";
204
+ public static final String MAILGUN_API_KEY = "mailgun.api.key";
205
+ public static final String EMAIL_FROM_ADDRESS = "email.from.address";
206
+ public static final String EMAIL_LIC_DEFAULT_SUBJECT = "email.lic.default.subject";
207
+ }
197208
198209 }
securis/src/main/java/net/curisit/securis/utils/EmailManager.java
....@@ -56,9 +56,9 @@
5656 * @throws SeCurisException
5757 */
5858 public EmailManager() throws SeCurisException {
59
- String domain = Params.get(Params.KEYS.MAILGUN_DOMAIN);
59
+ String domain = Config.get(Config.KEYS.MAILGUN_DOMAIN);
6060 if (domain == null) {
61
- throw new SeCurisException("Please, add '" + Params.KEYS.MAILGUN_DOMAIN + "' parameter to config file");
61
+ throw new SeCurisException("Please, add '" + Config.KEYS.MAILGUN_DOMAIN + "' parameter to config file");
6262 }
6363 serverUrl = String.format("https://api.mailgun.net/v2/%s/messages", domain);
6464 httpClient = createHttpClient();
....@@ -81,7 +81,7 @@
8181 throw new SeCurisException("Error creating SSL socket factory");
8282 }
8383 CredentialsProvider provider = new BasicCredentialsProvider();
84
- UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("api", Params.get(Params.KEYS.MAILGUN_API_KEY));
84
+ UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("api", Config.get(Config.KEYS.MAILGUN_API_KEY));
8585 provider.setCredentials(AuthScope.ANY, credentials);
8686
8787 return HttpClientBuilder.create().setDefaultCredentialsProvider(provider).setSSLSocketFactory(sslsf).build();
....@@ -105,7 +105,7 @@
105105
106106 builder.setCharset(Charset.forName("utf-8"));
107107 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
108
- builder.addTextBody("from", Params.get(Params.KEYS.EMAIL_FROM_ADDRESS));
108
+ builder.addTextBody("from", Config.get(Config.KEYS.EMAIL_FROM_ADDRESS));
109109 builder.addTextBody("to", to);
110110 if (cc != null) {
111111 builder.addTextBody("cc", cc);
securis/src/main/resources/db/schema.sql
....@@ -3,7 +3,7 @@
33 CREATE TABLE IF NOT EXISTS settings (
44 `key` VARCHAR(100) NOT NULL ,
55 value VARCHAR(2000) NULL ,
6
- creation_timestamp DATETIME NOT NULL default now(),
6
+ modification_timestamp DATETIME NOT NULL default now(),
77 PRIMARY KEY (``key``) );
88
99 drop table IF EXISTS user;
securis/src/main/webapp/js/licenses.js
....@@ -1,72 +1,72 @@
11 (function() {
22 'use strict';
3
-
43
54
6
- var HTTP_ERRORS = {
7
- 401: "Unathorized action",
8
- 418: "Application error",
9
- 403: "Forbidden action",
10
- 500: "Server error",
11
- 404: "Element not found"
12
- }
5
+
6
+ var HTTP_ERRORS = {
7
+ 401: "Unathorized action",
8
+ 418: "Application error",
9
+ 403: "Forbidden action",
10
+ 500: "Server error",
11
+ 404: "Element not found"
12
+ }
1313
1414 var app = angular.module('securis');
1515 app.service('Packs', ['$L','$resource', 'toaster', function($L, $resource, toaster) {
1616 var PACK_STATUS = {
17
- CREATED: 'CR',
18
- ACTIVE: 'AC',
19
- ONHOLD: 'OH',
20
- EXPIRED: 'EX',
21
- CANCELLED: 'CA'
17
+ CREATED: 'CR',
18
+ ACTIVE: 'AC',
19
+ ONHOLD: 'OH',
20
+ EXPIRED: 'EX',
21
+ CANCELLED: 'CA'
2222 }
2323 var PACK_STATUSES = {
2424 'CR': $L.get('Created'),
25
- 'AC': $L.get('Active'),
26
- 'OH': $L.get('On Hold'),
27
- 'EX': $L.get('Expired'),
28
- 'CA': $L.get('Cancelled')
29
- };
25
+ 'AC': $L.get('Active'),
26
+ 'OH': $L.get('On Hold'),
27
+ 'EX': $L.get('Expired'),
28
+ 'CA': $L.get('Cancelled')
29
+ };
3030 /**
3131 * These transitions could be get from server, class Pack.Status, but we
3232 * copy them for simplicity, this info won't change easily
3333 */
3434 var PACK_ACTIONS_BY_STATUS = {
35
- activate: [PACK_STATUS.CREATED, PACK_STATUS.EXPIRED, PACK_STATUS.ONHOLD],
36
- putonhold: [PACK_STATUS.ACTIVE],
37
- cancel: [PACK_STATUS.EXPIRED, PACK_STATUS.ONHOLD, PACK_STATUS.ACTIVE],
38
- 'delete': [PACK_STATUS.CREATED, PACK_STATUS.CANCELLED]
39
- }
40
-
35
+ activate: [PACK_STATUS.CREATED, PACK_STATUS.EXPIRED, PACK_STATUS.ONHOLD],
36
+ putonhold: [PACK_STATUS.ACTIVE],
37
+ cancel: [PACK_STATUS.EXPIRED, PACK_STATUS.ONHOLD, PACK_STATUS.ACTIVE],
38
+ 'delete': [PACK_STATUS.CREATED, PACK_STATUS.CANCELLED]
39
+ }
40
+
4141 var packResource = $resource('pack/:packId/:action',
4242 {
43
- packId : '@id',
44
- action : '@action'
43
+ packId : '@id',
44
+ action : '@action'
4545 },
4646 {
47
- activate: {
48
- method: "POST",
49
- params: {action: "activate"}
50
- },
51
- putonhold: {
52
- method: "POST",
53
- params: {action: "putonhold"}
54
- },
55
- cancel: {
56
- method: "POST",
57
- params: {action: "cancel"}
58
- }
59
- }
60
- );
47
+ activate: {
48
+ method: "POST",
49
+ params: {action: "activate"}
50
+ },
51
+ putonhold: {
52
+ method: "POST",
53
+ params: {action: "putonhold"}
54
+ },
55
+ cancel: {
56
+ method: "POST",
57
+ params: {action: "cancel"}
58
+ }
59
+ }
60
+ );
6161 this.getStatusColor = function(status) {
6262 var COLORS_BY_STATUS = {
6363 'CR': '#808080',
64
- 'AC': '#329e5a',
65
- 'OH': '#9047c7',
66
- 'EX': '#ea7824',
67
- 'CA': '#a21717'
68
- };
69
-
64
+ 'AC': '#329e5a',
65
+ 'OH': '#9047c7',
66
+ 'EX': '#ea7824',
67
+ 'CA': '#a21717'
68
+ };
69
+
7070 return COLORS_BY_STATUS[status];
7171 },
7272 this.getStatusName = function(status) {
....@@ -79,15 +79,15 @@
7979 toaster.pop('success', 'Packs', $L.get("Pack '{0}' {1} successfully", pack.code, isNew ? $L.get("created") : $L.get("updated")));
8080 }
8181 var _error = function(error) {
82
- console.log(error);
82
+ console.log(error);
8383 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'))));
8484 }
8585 packResource.save(pack, _success, _error);
8686 }
8787
8888 this.isActionAvailable = function(action, pack) {
89
- var validStatuses = PACK_ACTIONS_BY_STATUS[action];
90
- return pack && validStatuses && validStatuses.indexOf(pack.status) !== -1;
89
+ var validStatuses = PACK_ACTIONS_BY_STATUS[action];
90
+ return pack && validStatuses && validStatuses.indexOf(pack.status) !== -1;
9191 }
9292 var _createSuccessCallback = function(actionName, message, _innerCallback) {
9393 return function() {
....@@ -97,8 +97,8 @@
9797 }
9898 var _createErrorCallback = function(pack, actionName, _innerCallback) {
9999 return function(error) {
100
- console.log(error);
101
- _innerCallback && _innerCallback();
100
+ console.log(error);
101
+ _innerCallback && _innerCallback();
102102 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'))));
103103 }
104104 }
....@@ -132,85 +132,86 @@
132132 }
133133
134134 }]);
135
-
135
+
136136 app.service('Licenses', ['$L', '$resource', 'toaster', function($L, $resource, toaster) {
137137 var LIC_STATUS = {
138
- CREATED: 'CR',
139
- ACTIVE: 'AC',
140
- REQUESTED: 'RE',
141
- PREACTIVE: 'PA',
142
- EXPIRED: 'EX',
143
- CANCELLED: 'CA'
138
+ CREATED: 'CR',
139
+ ACTIVE: 'AC',
140
+ REQUESTED: 'RE',
141
+ PREACTIVE: 'PA',
142
+ EXPIRED: 'EX',
143
+ CANCELLED: 'CA'
144144 }
145
-
145
+
146146 var LIC_STATUSES = {
147147 'CR': $L.get('Created'),
148
- 'AC': $L.get('Active'),
149
- 'PA': $L.get('Pre-active'),
150
- 'RE': $L.get('Requested'),
151
- 'EX': $L.get('Expired'),
152
- 'CA': $L.get('Cancelled')
153
- };
148
+ 'AC': $L.get('Active'),
149
+ 'PA': $L.get('Pre-active'),
150
+ 'RE': $L.get('Requested'),
151
+ 'EX': $L.get('Expired'),
152
+ 'CA': $L.get('Cancelled')
153
+ };
154154
155155 /**
156156 * These transitions could be get from server, class License.Status, but
157157 * we copy them for simplicity, this info won't change easily
158158 */
159159 var LIC_ACTIONS_BY_STATUS = {
160
- activate: [LIC_STATUS.CREATED, LIC_STATUS.REQUESTED, LIC_STATUS.PREACTIVE],
161
- send: [LIC_STATUS.ACTIVE, LIC_STATUS.PREACTIVE],
162
- download: [LIC_STATUS.ACTIVE, LIC_STATUS.PREACTIVE],
163
- block: [LIC_STATUS.CANCELLED],
164
- unblock: [LIC_STATUS.CANCELLED],
165
- cancel: [LIC_STATUS.REQUESTED, LIC_STATUS.EXPIRED, LIC_STATUS.PREACTIVE, LIC_STATUS.ACTIVE],
166
- 'delete': [LIC_STATUS.CREATED, LIC_STATUS.CANCELLED]
167
- }
168
-
169
- var licenseResource = $resource('license/:licenseId/:action', {
170
- licenseId : '@id',
160
+ activate: [LIC_STATUS.CREATED, LIC_STATUS.REQUESTED, LIC_STATUS.PREACTIVE],
161
+ send: [LIC_STATUS.ACTIVE, LIC_STATUS.PREACTIVE],
162
+ download: [LIC_STATUS.ACTIVE, LIC_STATUS.PREACTIVE],
163
+ block: [LIC_STATUS.CANCELLED],
164
+ unblock: [LIC_STATUS.CANCELLED],
165
+ cancel: [LIC_STATUS.REQUESTED, LIC_STATUS.EXPIRED, LIC_STATUS.PREACTIVE, LIC_STATUS.ACTIVE],
166
+ 'delete': [LIC_STATUS.CREATED, LIC_STATUS.CANCELLED]
167
+ }
168
+
169
+ var licenseResource = $resource('license/:licenseId/:action', {
170
+ licenseId : '@id',
171171 action : '@action'
172172 },
173173 {
174
- activate: {
175
- method: "POST",
176
- params: {action: "activate"}
177
- },
178
- cancel: {
179
- method: "POST",
180
- params: {action: "cancel"}
181
- }, // Download a file cannot be done form AJAX, We should do it manually, using $http
182
- download: {
183
- method: "GET",
184
- params: {action: "download"}
185
- },
186
- block: {
187
- method: "POST",
188
- params: {action: "block"}
189
- },
190
- sendEmail: {
191
- method: "POST",
192
- params: {action: "send"}
193
- },
194
- unblock: {
195
- method: "POST",
196
- params: {action: "unblock"}
197
- }
198
- });
174
+ activate: {
175
+ method: "POST",
176
+ params: {action: "activate"}
177
+ },
178
+ cancel: {
179
+ method: "POST",
180
+ params: {action: "cancel"}
181
+ }, // Download a file cannot be done form AJAX, We should do it
182
+ // manually, using $http
183
+ download: {
184
+ method: "GET",
185
+ params: {action: "download"}
186
+ },
187
+ block: {
188
+ method: "POST",
189
+ params: {action: "block"}
190
+ },
191
+ sendEmail: {
192
+ method: "POST",
193
+ params: {action: "send"}
194
+ },
195
+ unblock: {
196
+ method: "POST",
197
+ params: {action: "unblock"}
198
+ }
199
+ });
199200
200201
201
- this.isActionAvailable = function(action, lic) {
202
- var validStatuses = LIC_ACTIONS_BY_STATUS[action];
203
- return lic && validStatuses && validStatuses.indexOf(lic.status) !== -1;
204
- }
205
- this.getStatusColor = function(status) {
202
+ this.isActionAvailable = function(action, lic) {
203
+ var validStatuses = LIC_ACTIONS_BY_STATUS[action];
204
+ return lic && validStatuses && validStatuses.indexOf(lic.status) !== -1;
205
+ }
206
+ this.getStatusColor = function(status) {
206207 var COLORS_BY_STATUS = {
207208 'CR': '#808080',
208
- 'AC': '#329e5a',
209
- 'RE': '#2981d4',
210
- 'EX': '#ea7824',
211
- 'CA': '#a21717'
212
- };
213
-
209
+ 'AC': '#329e5a',
210
+ 'RE': '#2981d4',
211
+ 'EX': '#ea7824',
212
+ 'CA': '#a21717'
213
+ };
214
+
214215 return COLORS_BY_STATUS[status];
215216 },
216217 this.getStatusName = function(status) {
....@@ -223,7 +224,7 @@
223224 toaster.pop('success', 'Licenses', $L.get("License '{0}' {1} successfully", license.code, isNew ? $L.get("created") : $L.get("updated")));
224225 }
225226 var _error = function(error) {
226
- console.log(error);
227
+ console.log(error);
227228 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'))));
228229 }
229230 licenseResource.save(license, _success, _error);
....@@ -237,12 +238,12 @@
237238 }
238239 var _createErrorCallback = function(license, actionName, _innerCallback) {
239240 return function(error) {
240
- console.log(error);
241
- _innerCallback && _innerCallback();
241
+ console.log(error);
242
+ _innerCallback && _innerCallback();
242243 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'))));
243244 }
244245 }
245
-
246
+
246247 this.getLicensesList = function(pack, _onsuccess, _onerror) {
247248 return licenseResource.query({packId: pack.id}, _onsuccess, _onerror);
248249 }
....@@ -274,9 +275,9 @@
274275 console.log('Download license: ' + license.id);
275276 var _success = _createSuccessCallback($L.get('Download'), $L.get("License '{0}' {1} successfully", license.code, $L.get("downloaded")), _onsuccess);
276277 var _error = _createErrorCallback(license, $L.get('Download license file'), _onerror);
277
- //window.open(downloadPath, '_blank', '');
278
+ // window.open(downloadPath, '_blank', '');
278279 var _success2 = function(data, headers) {
279
- //console.log(headers.get("Content-Disposition"));
280
+ // console.log(headers.get("Content-Disposition"));
280281 // attachment; filename="license.lic"
281282 var filename = JSON.parse(headers('Content-Disposition').match(/".*"$/g)[0]);
282283 data.$promise.then(function(content) {
....@@ -300,526 +301,530 @@
300301 licenseResource.delete({licenseId: license.id}, _success, _error);
301302 }
302303 }]);
303
-
304
+
304305 app.directive('fileLoader',
305
- function($timeout, $parse) {
306
- return {
307
- restrict : 'A', // only activate on element attribute
308
- require : '',
309
- link : function(scope, element, attrs) {
310
- console.log('scope.license: ' + scope.$parent.license);
311
- var setter = $parse(attrs.fileLoader).assign;
312
- element.bind('change', function(evt) {
313
- if (!window.FileReader) { // Browser is not
314
- // compatible
315
- BootstrapDialog.alert($L.get("Open your .req file with a text editor and copy&paste the content in the form text field?"));
316
- return;
317
- }
318
- console.log('File selected');
319
- // console.log('scope.license: ' +
320
- // scope.$parent.license);
321
- var field = $parse(attrs.fileLoader);
322
- // console.log('field: ' + field);
323
- var fileList = evt.target.files;
324
- if (fileList != null && fileList[0]) {
325
- var reader = new FileReader();
326
- reader.onerror = function(data) {
327
- setter(scope.$parent, 'ERROR');
328
- scope.$apply();
329
- }
330
- reader.onload = function(data) {
331
- setter(scope.$parent, reader.result);
332
- scope.$apply();
333
- }
334
-
335
- reader.readAsText(fileList[0]);
336
- } else {
337
- setter(scope.$parent, '');
338
- scope.$apply();
339
- }
340
- });
341
-
342
- }
343
- };
344
- });
306
+ function($timeout, $parse) {
307
+ return {
308
+ restrict : 'A', // only activate on element attribute
309
+ require : '',
310
+ link : function(scope, element, attrs) {
311
+ console.log('scope.license: ' + scope.$parent.license);
312
+ var setter = $parse(attrs.fileLoader).assign;
313
+ element.bind('change', function(evt) {
314
+ if (!window.FileReader) { // Browser is not
315
+ // compatible
316
+ BootstrapDialog.alert($L.get("Open your .req file with a text editor and copy&paste the content in the form text field?"));
317
+ return;
318
+ }
319
+ console.log('File selected');
320
+ // console.log('scope.license: ' +
321
+ // scope.$parent.license);
322
+ var field = $parse(attrs.fileLoader);
323
+ // console.log('field: ' + field);
324
+ var fileList = evt.target.files;
325
+ if (fileList != null && fileList[0]) {
326
+ var reader = new FileReader();
327
+ reader.onerror = function(data) {
328
+ setter(scope.$parent, 'ERROR');
329
+ scope.$apply();
330
+ }
331
+ reader.onload = function(data) {
332
+ setter(scope.$parent, reader.result);
333
+ scope.$apply();
334
+ }
335
+
336
+ reader.readAsText(fileList[0]);
337
+ } else {
338
+ setter(scope.$parent, '');
339
+ scope.$apply();
340
+ }
341
+ });
342
+
343
+ }
344
+ };
345
+ });
345346
346347
347348 app.controller('PackAndLicensesCtrl', [
348
- '$scope',
349
- '$http',
350
- 'toaster',
351
- '$store',
352
- '$L',
353
- function($scope, $http, toaster, $store, $L) {
354
- $store.set('location', '/licenses');
355
-
356
- $scope.maxLengthErrorMsg = function(displayname, fieldMaxlength) {
357
- return $L.get("{0} length is too long (max: {1}).", $L.get(displayname), fieldMaxlength);
358
- }
359
- $scope.mandatoryFieldErrorMsg = function(displayname) {
360
- return $L.get("'{0}' is required.", $L.get(displayname));
361
- }
362
- $scope.field1ShouldBeGreaterThanField2 = function(field1, field2) {
363
- return $L.get("{0} should be greater than {1}", $L.get(field1), $L.get(field2));
364
- }
365
- $scope.ellipsis = function(txt, len) {
366
- if (!txt || txt.length <= len) return txt;
367
- return txt.substring(0, len) + '...';
368
- }
369
- $scope.currentPack = $store.get('currentPack');
349
+ '$scope',
350
+ '$http',
351
+ 'toaster',
352
+ '$store',
353
+ '$L',
354
+ function($scope, $http, toaster, $store, $L) {
355
+ $store.set('location', '/licenses');
370356
371
- }]);
372
-
373
- app.controller('PacksCtrl', [
374
- '$scope',
375
- '$http',
376
- '$resource',
377
- 'toaster',
378
- 'Catalogs',
379
- 'Packs',
380
- '$store',
381
- '$L',
382
- function($scope, $http, $resource, toaster, Catalogs, Packs, $store, $L) {
383
- $scope.Packs = Packs;
384
-
385
-
386
- $scope.mandatory = {
387
- code: true,
388
- num_licenses: true,
389
- init_valid_date: true,
390
- end_valid_date: true,
391
- status: true,
392
- organization_id: true,
393
- license_type_id: true
394
- }
395
- $scope.maxlength = {
396
- code: 50,
397
- comments: 1024
398
- }
399
- $scope.refs = {};
400
- Catalogs.init().then(function() {
401
- var refFields = [{resource: 'organization', name: 'organization_id'},{resource: 'licensetype', name: 'license_type_id'}];
402
- Catalogs.loadRefs(function(refs) {
403
- $scope.refs = refs;
404
- }, refFields);
405
- });
406
-
407
- // Used to create the form with the appropriate data
408
- $scope.isNew = undefined;
409
-
410
- // Selected pack from listing
411
- // pack is the edited pack, in creation contains the data for
412
- // the new pack
413
- $scope.pack = null;
414
-
415
- $scope.packs = Packs.getPacksList();
416
-
417
- $scope.save = function() {
418
- Packs.savePackData($scope.pack, $scope.isNew, function() {
419
- if (!$scope.isNew) {
420
- $scope.showForm = false;
421
- } else {
422
- $scope.newPack();
423
- }
424
- $scope.packs = Packs.getPacksList();
425
- });
426
- }
427
-
428
- /**
429
- * Execute an action over the pack, activation, onhold,
430
- * cancellation
431
- */
432
- $scope.execute = function(action, pack) {
433
- var _execute = function(extra_data) {
434
- if (extra_data) {
435
- Packs[action](pack || $scope.pack, extra_data, function() {
436
- if (!$scope.isNew) $scope.showForm = false;
437
- $scope.packs = Packs.getPacksList();
438
- });
439
- } else {
440
- Packs[action](pack || $scope.pack, function() {
441
- if (!$scope.isNew) $scope.showForm = false;
442
- $scope.packs = Packs.getPacksList();
443
- });
444
- }
445
- }
446
- if (action === 'delete') {
447
- BootstrapDialog.confirm($L.get("The pack '{0}' will be deleted, are you sure ?", pack.code), function(answer) {
448
- if (answer) {
449
- _execute();
450
- }
451
- });
452
- } else {
453
- if (action === 'cancel') {
454
- BootstrapDialog.show({
455
- title: $L.get("Pack cancellation"),
456
- type: BootstrapDialog.TYPE_DANGER,
457
- message: function(dialog) {
458
- var $content = $('<div></div>');
459
- var $message = $('<div></div>');
460
- $message.append($('<label/>').text($L.get("The pack '{0}' and all its licenses will be cancelled, this action cannot be undone", pack.code)));
461
- $content.append($message);
462
-
463
- var $message = $('<div style="margin-top:10pt;"/>');
464
- var pageToLoad = dialog.getData('pageToLoad');
465
- $message.append($('<label style="margin-right:5pt;"/>').text($L.get("Cancellation reason:") + " "));
466
- $message.append($('<input type="text" style="width:100%;" maxlength="512" id="_pack_cancellation_reason"/>'));
467
- $content.append($message);
468
- return $content;
469
- },
470
- closable: true,
471
- buttons: [{
472
- id: 'btn-cancel',
473
- label: $L.get('Close'),
474
- cssClass: 'btn-default',
475
- action: function(dialogRef) {
476
- dialogRef.close();
477
- }
478
- }, {
479
- id: 'btn-ok',
480
- label: $L.get('Cancel pack'),
481
- cssClass: 'btn-primary',
482
- action: function(dialogRef){
483
- var reason = $('#_pack_cancellation_reason').val();
484
- console.log('Ready to cancel pack, by reason: ' + reason);
485
- if (!reason) {
486
- $('#_pack_cancellation_reason').focus();
487
- } else {
488
- _execute({reason: reason});
489
- dialogRef.close();
490
- }
491
- }
492
- }]
493
- });
494
- } else {
495
- _execute();
496
- }
497
- }
498
- }
499
-
500
-
501
- $scope.newPack = function() {
502
- $scope.isNew = true;
503
- $scope.showForm = true;
504
- $scope.pack = {
505
- license_preactivation: true,
506
- status: 'CR',
507
- num_licenses: 1,
508
- init_valid_date: new Date(),
509
- default_valid_period: 30,
510
- license_type_id: null,
511
- organization_id: null // !$scope.refs.organization_id
512
- // ||
513
- // !$scope.refs.organization_id.length
514
- // ? null :
515
- // $scope.refs.organization_id[0].id
516
- }
517
- setTimeout(function() {
518
- $('#code').focus();
519
- }, 0);
520
- }
521
-
522
- $scope.editPack = function(selectedPack) {
523
- $scope.isNew = false;
524
- $scope.showForm = true;
525
- if (!(selectedPack.init_valid_date instanceof Date)) {
526
- selectedPack.init_valid_date = new Date(selectedPack.init_valid_date);
527
- }
528
- if (!(selectedPack.end_valid_date instanceof Date)) {
529
- selectedPack.end_valid_date = new Date(selectedPack.end_valid_date);
530
- }
531
-
532
- $scope.pack = selectedPack;
533
-
534
- // $scope.pack.organization_name =
535
- // $scope.getLabelFromId('organization_id',
536
- // $scope.pack.organization_id);
537
- $scope.pack.license_type_name = $scope.getLabelFromId('license_type_id', $scope.pack.license_type_id);
538
- $scope.pack.status_name = Packs.getStatusName($scope.pack.status);
539
-
540
- setTimeout(function() {
541
- $('#code').focus();
542
- }, 0);
543
- }
544
-
545
- $scope.deletePack = function(selectedPack) {
546
- $scope.showForm = false;
547
- BootstrapDialog.confirm($L.get("The pack '{0}' will be deleted, are you sure?", selectedPack.code), function(result){
548
- if(result) {
549
- var promise = packResource.remove({}, {id: selectedPack.id}).$promise;
550
- promise.then(function(data) {
551
- $scope.selectPack(null);
552
- $scope.packs = packResource.query();
553
- toaster.pop('success', Catalogs.getName(), $L.get("Pack '{0}' deleted successfully", selectedPack.code));
554
- },function(error) {
555
- console.log(error);
556
- 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);
557
- });
558
- }
559
- });
560
- $scope.isNew = false;
561
- }
562
-
563
-
564
- $scope.cancel = function() {
565
- $scope.showForm = false;
566
- }
567
-
568
- $scope.selectPack = function(pack) {
569
- $scope.$parent.currentPack = pack;
570
- $store.put('currentPack', pack);
571
- $scope.$parent.$broadcast('pack_changed', pack);
572
- }
573
-
574
- $scope.getLabelFromId = function(field, myid) {
575
- var label = null;
576
- $scope.refs[field].forEach(function (elem) {
577
- if (elem.id === myid) {
578
- label = elem.label;
579
- }
580
- });
581
- return label;
582
- }
583
-
584
- $scope.createMetadataRow = function() {
585
- if (!$scope.formu.metadata) {
586
- $scope.formu.metadata = [];
587
- }
588
- $scope.formu.metadata.push({key: '', value: '', mandatory: true});
589
- }
590
- $scope.removeMetadataKey = function(row_md) {
591
- $scope.formu.metadata.splice( $scope.formu.metadata.indexOf(row_md), 1 );
592
- }
593
- $scope.updateMetadata = function() {
594
- // Called when Application ID change in current field
595
- var newLTId = $scope.pack['license_type_id'];
596
- if (newLTId) {
597
- // Only if there is a "valid" value selected we should
598
- // update the metadata
599
- Catalogs.getResource('licensetype').get({licenseTypeId: newLTId}).$promise.then(function(lt) {
600
- $scope.pack.metadata = [];
601
- lt.metadata.forEach(function(md) {
602
- $scope.pack.metadata.push({
603
- key: md.key,
604
- value: md.value,
605
- readonly: !!md.value,
606
- mandatory: md.mandatory
607
- });
608
- });
609
- });
610
- }
611
- }
612
- } ]);
613
-
614
- app.controller('LicensesCtrl', [
615
- '$scope',
616
- '$http',
617
- '$resource',
618
- 'toaster',
619
- 'Licenses',
620
- '$store',
621
- '$L',
622
- function($scope, $http, $resource, toaster, Licenses, $store, $L) {
623
- $scope.Licenses = Licenses;
624
- $scope.$on('pack_changed', function(evt, message) {
625
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
626
- $scope.creationAvailable = $scope.currentPack.status == 'AC';
627
- if ($scope.showForm) {
628
- if ($scope.isNew) {
629
- $scope.license.pack_id = $scope.currentPack.id
630
- } else {
631
- $scope.showForm = false;
632
- }
633
- }
634
- })
635
-
636
- $scope.mandatory = {
637
- code: true,
638
- email: true
639
- }
640
- $scope.maxlength = {
641
- code: 50,
642
- request_data: 500,
643
- comments: 1024
644
- }
645
- $scope.refs = {};
646
-
647
- // Used to create the form with the
648
- // appropriate data
649
- $scope.isNew = undefined;
650
-
651
- // Selected license from listing
652
- // license is the edited license, in
653
- // creation contains the data for
654
- // the new license
655
- $scope.license = null;
656
- if ($scope.currentPack) {
657
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
658
- }
659
-
660
- $scope.save = function() {
661
- Licenses.saveLicenseData($scope.license, $scope.isNew, function() {
662
- if (!$scope.isNew) {
663
- $scope.showForm = false;
664
- } else {
665
- $scope.newLicense();
666
- }
667
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
668
- });
669
- }
670
-
671
- $scope.newLicense = function() {
672
- if (!$scope.currentPack) {
673
- BootstrapDialog.show({
674
- title: $L.get('New license'),
675
- type: BootstrapDialog.TYPE_WARNING,
676
- message: $L.get('Please, select a pack before to create a new license'),
677
- buttons: [{
678
- label: 'OK',
679
- action: function(dialog) {
680
- dialog.close();
681
- }
682
- }]
683
- });
684
- return;
685
- }
686
- if (!$scope.creationAvailable) {
687
- BootstrapDialog.show({
688
- title: $L.get('Pack not active'),
689
- type: BootstrapDialog.TYPE_WARNING,
690
- message: $L.get('Current pack is not active, so licenses cannot be created'),
691
- buttons: [{
692
- label: 'OK',
693
- action: function(dialog) {
694
- dialog.close();
695
- }
696
- }]
697
- });
698
- return;
699
- }
700
-
701
- $scope.isNew = true;
702
- $scope.showForm = true;
703
- $scope.license = {
704
- pack_id: $scope.currentPack.id
705
- }
706
- setTimeout(function() {
707
- $('#licenseForm * #code').focus();
708
- }, 0);
709
- }
710
-
711
- $scope.editLicense = function(selectedlicense) {
712
- $scope.isNew = false;
713
- $scope.showForm = true;
714
- $scope.license = selectedlicense;
715
- $scope.license.status_name = Licenses.getStatusName($scope.license.status);
716
-
717
- setTimeout(function() {
718
- $('#licenseForm * #code').focus();
719
- }, 0);
720
- }
721
-
722
- $scope.deletelicense = function(selectedlicense) {
723
- $scope.showForm = false;
724
- BootstrapDialog.confirm($L.get("The license '{0}' will be deleted, are you sure?", selectedlicense.code), function(result){
725
- if(result) {
726
- var promise = licenseResource.remove({}, {id: selectedlicense.id}).$promise;
727
- promise.then(function(data) {
728
- $scope.selectlicense(null);
729
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
730
- toaster.pop('success', Catalogs.getName(), $L.get("License '{0}' deleted successfully", selectedlicense.code));
731
- },function(error) {
732
- console.log(error);
733
- 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);
734
- });
735
- }
736
- });
737
- $scope.isNew = false;
738
- }
739
-
740
- $scope.execute = function(action, license) {
741
- if (!license) {
742
- license = $scope.license;
357
+ $scope.maxLengthErrorMsg = function(displayname, fieldMaxlength) {
358
+ return $L.get("{0} length is too long (max: {1}).", $L.get(displayname), fieldMaxlength);
743359 }
744
- var _execute = function(extra_data) {
745
- if (extra_data) {
746
- Licenses[action](license, extra_data, function() {
747
- if (!$scope.isNew) $scope.showForm = false;
748
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
749
- });
750
- } else {
751
- Licenses[action](license, function() {
752
- if (!$scope.isNew) $scope.showForm = false;
753
- $scope.licenses = Licenses.getLicensesList($scope.currentPack);
754
- });
755
- }
756
- }
757
- if (action === 'delete') {
758
- BootstrapDialog.confirm($L.get("The license '{0}' will be deleted, are you sure?", license.code), function(result){
759
- if(result) {
760
- _execute();
761
- }
762
- });
763
- } else {
764
- if (action === 'cancel') {
765
- BootstrapDialog.show({
766
- title: $L.get("License cancellation"),
767
- type: BootstrapDialog.TYPE_DANGER,
768
- message: function(dialog) {
769
- var $content = $('<div></div>');
770
- var $message = $('<div></div>');
771
- var pageToLoad = dialog.getData('pageToLoad');
772
- $message.append($('<label/>').text($L.get("This action cannot be undone.", $scope.pack.code)));
773
- $content.append($message);
360
+ $scope.mandatoryFieldErrorMsg = function(displayname) {
361
+ return $L.get("'{0}' is required.", $L.get(displayname));
362
+ }
363
+ $scope.field1ShouldBeGreaterThanField2 = function(field1, field2) {
364
+ return $L.get("{0} should be greater than {1}", $L.get(field1), $L.get(field2));
365
+ }
366
+ $scope.ellipsis = function(txt, len) {
367
+ if (!txt || txt.length <= len) return txt;
368
+ return txt.substring(0, len) + '...';
369
+ }
370
+ $scope.currentPack = $store.get('currentPack');
774371
775
- var $message = $('<div style="margin-top:10pt;"/>');
776
- $message.append($('<label style="margin-right:5pt;"/>').text($L.get("Cancellation reason:") + " "));
777
- $message.append($('<input type="text" style="width:100%;" maxlength="512" id="_lic_cancellation_reason"/>'));
778
- $content.append($message);
779
- return $content;
780
- },
781
- closable: true,
782
- buttons: [{
783
- id: 'btn-cancel',
784
- label: $L.get('Close'),
785
- cssClass: 'btn-default',
786
- action: function(dialogRef) {
787
- dialogRef.close();
788
- }
789
- }, {
790
- id: 'btn-ok',
791
- label: $L.get('Cancel license'),
792
- cssClass: 'btn-primary',
793
- action: function(dialogRef){
794
- var reason = $('#_lic_cancellation_reason').val();
795
- console.log('Ready to cancel license, by reason: ' + reason);
796
- if (!reason) {
797
- $('#_lic_cancellation_reason').focus();
798
- } else {
799
- _execute({reason: reason});
800
- dialogRef.close();
801
- }
802
- }
803
- }]
804
- });
805
- } else {
806
- _execute();
807
- }
808
- }
809
- }
810
-
372
+ }]);
811373
812
- $scope.cancel = function() {
813
- $scope.showForm = false;
814
- }
815
-
816
- $scope.showStatus = function(lic) {
817
-
818
- }
819
- $scope.showStatusLong = function(license) {
820
-
821
- }
822
-
823
- } ]);
374
+ app.controller('PacksCtrl', [
375
+ '$scope',
376
+ '$http',
377
+ '$resource',
378
+ 'toaster',
379
+ 'Catalogs',
380
+ 'Packs',
381
+ '$store',
382
+ '$L',
383
+ function($scope, $http, $resource, toaster, Catalogs, Packs, $store, $L) {
384
+ $scope.Packs = Packs;
385
+
386
+
387
+ $scope.mandatory = {
388
+ code: true,
389
+ num_licenses: true,
390
+ init_valid_date: true,
391
+ end_valid_date: true,
392
+ status: true,
393
+ organization_id: true,
394
+ license_type_id: true
395
+ }
396
+ $scope.maxlength = {
397
+ code: 50,
398
+ comments: 1024
399
+ }
400
+ $scope.refs = {};
401
+ Catalogs.init().then(function() {
402
+ var refFields = [{resource: 'organization', name: 'organization_id'},{resource: 'licensetype', name: 'license_type_id'}];
403
+ Catalogs.loadRefs(function(refs) {
404
+ $scope.refs = refs;
405
+ }, refFields);
406
+ });
407
+
408
+ // Used to create the form with the
409
+ // appropriate data
410
+ $scope.isNew = undefined;
411
+
412
+ // Selected pack from listing
413
+ // pack is the edited pack, in creation
414
+ // contains the data for
415
+ // the new pack
416
+ $scope.pack = null;
417
+
418
+ $scope.packs = Packs.getPacksList();
419
+
420
+ $scope.save = function() {
421
+ Packs.savePackData($scope.pack, $scope.isNew, function() {
422
+ if (!$scope.isNew) {
423
+ $scope.showForm = false;
424
+ } else {
425
+ $scope.newPack();
426
+ }
427
+ $scope.packs = Packs.getPacksList();
428
+ });
429
+ }
430
+
431
+ /**
432
+ * Execute an action over the pack,
433
+ * activation, onhold, cancellation
434
+ */
435
+ $scope.execute = function(action, pack) {
436
+ var _execute = function(extra_data) {
437
+ if (extra_data) {
438
+ Packs[action](pack || $scope.pack, extra_data, function() {
439
+ if (!$scope.isNew) $scope.showForm = false;
440
+ $scope.packs = Packs.getPacksList();
441
+ });
442
+ } else {
443
+ Packs[action](pack || $scope.pack, function() {
444
+ if (!$scope.isNew) $scope.showForm = false;
445
+ $scope.packs = Packs.getPacksList();
446
+ });
447
+ }
448
+ }
449
+ if (action === 'delete') {
450
+ BootstrapDialog.confirm($L.get("The pack '{0}' will be deleted, are you sure ?", pack.code), function(answer) {
451
+ if (answer) {
452
+ _execute();
453
+ }
454
+ });
455
+ } else {
456
+ if (action === 'cancel') {
457
+ BootstrapDialog.show({
458
+ title: $L.get("Pack cancellation"),
459
+ type: BootstrapDialog.TYPE_DANGER,
460
+ message: function(dialog) {
461
+ var $content = $('<div></div>');
462
+ var $message = $('<div></div>');
463
+ $message.append($('<label/>').text($L.get("The pack '{0}' and all its licenses will be cancelled, this action cannot be undone", pack.code)));
464
+ $content.append($message);
465
+
466
+ var $message = $('<div style="margin-top:10pt;"/>');
467
+ var pageToLoad = dialog.getData('pageToLoad');
468
+ $message.append($('<label style="margin-right:5pt;"/>').text($L.get("Cancellation reason:") + " "));
469
+ $message.append($('<input type="text" style="width:100%;" maxlength="512" id="_pack_cancellation_reason"/>'));
470
+ $content.append($message);
471
+ return $content;
472
+ },
473
+ closable: true,
474
+ buttons: [{
475
+ id: 'btn-cancel',
476
+ label: $L.get('Close'),
477
+ cssClass: 'btn-default',
478
+ action: function(dialogRef) {
479
+ dialogRef.close();
480
+ }
481
+ }, {
482
+ id: 'btn-ok',
483
+ label: $L.get('Cancel pack'),
484
+ cssClass: 'btn-primary',
485
+ action: function(dialogRef){
486
+ var reason = $('#_pack_cancellation_reason').val();
487
+ console.log('Ready to cancel pack, by reason: ' + reason);
488
+ if (!reason) {
489
+ $('#_pack_cancellation_reason').focus();
490
+ } else {
491
+ _execute({reason: reason});
492
+ dialogRef.close();
493
+ }
494
+ }
495
+ }]
496
+ });
497
+ } else {
498
+ _execute();
499
+ }
500
+ }
501
+ }
502
+
503
+
504
+ $scope.newPack = function() {
505
+ $scope.isNew = true;
506
+ $scope.showForm = true;
507
+ $scope.pack = {
508
+ license_preactivation: true,
509
+ status: 'CR',
510
+ num_licenses: 1,
511
+ init_valid_date: new Date(),
512
+ default_valid_period: 30,
513
+ license_type_id: null,
514
+ organization_id: null // !$scope.refs.organization_id
515
+ // ||
516
+ // !$scope.refs.organization_id.length
517
+ // ? null :
518
+ // $scope.refs.organization_id[0].id
519
+ }
520
+ setTimeout(function() {
521
+ $('#code').focus();
522
+ }, 0);
523
+ }
524
+
525
+ $scope.editPack = function(selectedPack) {
526
+ $scope.isNew = false;
527
+ $scope.showForm = true;
528
+ if (!(selectedPack.init_valid_date instanceof Date)) {
529
+ selectedPack.init_valid_date = new Date(selectedPack.init_valid_date);
530
+ }
531
+ if (!(selectedPack.end_valid_date instanceof Date)) {
532
+ selectedPack.end_valid_date = new Date(selectedPack.end_valid_date);
533
+ }
534
+
535
+ $scope.pack = selectedPack;
536
+
537
+ // $scope.pack.organization_name =
538
+ // $scope.getLabelFromId('organization_id',
539
+ // $scope.pack.organization_id);
540
+ $scope.pack.license_type_name = $scope.getLabelFromId('license_type_id', $scope.pack.license_type_id);
541
+ $scope.pack.status_name = Packs.getStatusName($scope.pack.status);
542
+
543
+ setTimeout(function() {
544
+ $('#code').focus();
545
+ }, 0);
546
+ }
547
+
548
+ $scope.deletePack = function(selectedPack) {
549
+ $scope.showForm = false;
550
+ BootstrapDialog.confirm($L.get("The pack '{0}' will be deleted, are you sure?", selectedPack.code), function(result){
551
+ if(result) {
552
+ var promise = packResource.remove({}, {id: selectedPack.id}).$promise;
553
+ promise.then(function(data) {
554
+ $scope.selectPack(null);
555
+ $scope.packs = packResource.query();
556
+ toaster.pop('success', Catalogs.getName(), $L.get("Pack '{0}' deleted successfully", selectedPack.code));
557
+ },function(error) {
558
+ console.log(error);
559
+ 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);
560
+ });
561
+ }
562
+ });
563
+ $scope.isNew = false;
564
+ }
565
+
566
+
567
+ $scope.cancel = function() {
568
+ $scope.showForm = false;
569
+ }
570
+
571
+ $scope.selectPack = function(pack) {
572
+ $scope.$parent.currentPack = pack;
573
+ $store.put('currentPack', pack);
574
+ $scope.$parent.$broadcast('pack_changed', pack);
575
+ }
576
+
577
+ $scope.getLabelFromId = function(field, myid) {
578
+ var label = null;
579
+ $scope.refs[field].forEach(function (elem) {
580
+ if (elem.id === myid) {
581
+ label = elem.label;
582
+ }
583
+ });
584
+ return label;
585
+ }
586
+
587
+ $scope.createMetadataRow = function() {
588
+ if (!$scope.formu.metadata) {
589
+ $scope.formu.metadata = [];
590
+ }
591
+ $scope.formu.metadata.push({key: '', value: '', mandatory: true});
592
+ }
593
+ $scope.removeMetadataKey = function(row_md) {
594
+ $scope.formu.metadata.splice( $scope.formu.metadata.indexOf(row_md), 1 );
595
+ }
596
+ $scope.updateMetadata = function() {
597
+ // Called when Application ID change
598
+ // in current field
599
+ var newLTId = $scope.pack['license_type_id'];
600
+ if (newLTId) {
601
+ // Only if there is a "valid"
602
+ // value selected we should
603
+ // update the metadata
604
+ Catalogs.getResource('licensetype').get({licenseTypeId: newLTId}).$promise.then(function(lt) {
605
+ $scope.pack.metadata = [];
606
+ lt.metadata.forEach(function(md) {
607
+ $scope.pack.metadata.push({
608
+ key: md.key,
609
+ value: md.value,
610
+ readonly: !!md.value,
611
+ mandatory: md.mandatory
612
+ });
613
+ });
614
+ });
615
+ }
616
+ }
617
+ } ]);
618
+
619
+ app.controller('LicensesCtrl', [
620
+ '$scope',
621
+ '$http',
622
+ '$resource',
623
+ 'toaster',
624
+ 'Licenses',
625
+ '$store',
626
+ '$L',
627
+ function($scope, $http, $resource, toaster, Licenses, $store, $L) {
628
+ $scope.Licenses = Licenses;
629
+ $scope.$on('pack_changed', function(evt, message) {
630
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
631
+ $scope.creationAvailable = $scope.currentPack.status == 'AC';
632
+ if ($scope.showForm) {
633
+ if ($scope.isNew) {
634
+ $scope.license.pack_id = $scope.currentPack.id
635
+ } else {
636
+ $scope.showForm = false;
637
+ }
638
+ }
639
+ })
640
+
641
+ $scope.mandatory = {
642
+ code: true,
643
+ email: true
644
+ }
645
+ $scope.maxlength = {
646
+ code: 50,
647
+ request_data: 500,
648
+ comments: 1024
649
+ }
650
+ $scope.refs = {};
651
+
652
+ // Used to create the form with the
653
+ // appropriate data
654
+ $scope.isNew = undefined;
655
+
656
+ // Selected license from listing
657
+ // license is the edited license, in
658
+ // creation contains the data for
659
+ // the new license
660
+ $scope.license = null;
661
+ if ($scope.currentPack) {
662
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
663
+ }
664
+
665
+ $scope.save = function() {
666
+ Licenses.saveLicenseData($scope.license, $scope.isNew, function() {
667
+ if (!$scope.isNew) {
668
+ $scope.showForm = false;
669
+ } else {
670
+ $scope.newLicense();
671
+ }
672
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
673
+ });
674
+ }
675
+
676
+ $scope.newLicense = function() {
677
+ if (!$scope.currentPack) {
678
+ BootstrapDialog.show({
679
+ title: $L.get('New license'),
680
+ type: BootstrapDialog.TYPE_WARNING,
681
+ message: $L.get('Please, select a pack before to create a new license'),
682
+ buttons: [{
683
+ label: 'OK',
684
+ action: function(dialog) {
685
+ dialog.close();
686
+ }
687
+ }]
688
+ });
689
+ return;
690
+ }
691
+ if (!$scope.creationAvailable) {
692
+ BootstrapDialog.show({
693
+ title: $L.get('Pack not active'),
694
+ type: BootstrapDialog.TYPE_WARNING,
695
+ message: $L.get('Current pack is not active, so licenses cannot be created'),
696
+ buttons: [{
697
+ label: 'OK',
698
+ action: function(dialog) {
699
+ dialog.close();
700
+ }
701
+ }]
702
+ });
703
+ return;
704
+ }
705
+
706
+ $scope.isNew = true;
707
+ $scope.showForm = true;
708
+ $scope.license = {
709
+ pack_id: $scope.currentPack.id
710
+ }
711
+ setTimeout(function() {
712
+ $('#licenseForm * #code').focus();
713
+ }, 0);
714
+ }
715
+
716
+ $scope.editLicense = function(selectedlicense) {
717
+ $scope.isNew = false;
718
+ $scope.showForm = true;
719
+ $scope.license = selectedlicense;
720
+ $scope.license.status_name = Licenses.getStatusName($scope.license.status);
721
+
722
+ setTimeout(function() {
723
+ $('#licenseForm * #code').focus();
724
+ }, 0);
725
+ }
726
+
727
+ $scope.deletelicense = function(selectedlicense) {
728
+ $scope.showForm = false;
729
+ BootstrapDialog.confirm($L.get("The license '{0}' will be deleted, are you sure?", selectedlicense.code), function(result){
730
+ if(result) {
731
+ var promise = licenseResource.remove({}, {id: selectedlicense.id}).$promise;
732
+ promise.then(function(data) {
733
+ $scope.selectlicense(null);
734
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
735
+ toaster.pop('success', Catalogs.getName(), $L.get("License '{0}' deleted successfully", selectedlicense.code));
736
+ },function(error) {
737
+ console.log(error);
738
+ 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);
739
+ });
740
+ }
741
+ });
742
+ $scope.isNew = false;
743
+ }
744
+
745
+ $scope.execute = function(action, license) {
746
+ if (!license) {
747
+ license = $scope.license;
748
+ }
749
+ var _execute = function(extra_data) {
750
+ if (extra_data) {
751
+ Licenses[action](license, extra_data, function() {
752
+ if (!$scope.isNew) $scope.showForm = false;
753
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
754
+ });
755
+ } else {
756
+ Licenses[action](license, function() {
757
+ if (!$scope.isNew) $scope.showForm = false;
758
+ $scope.licenses = Licenses.getLicensesList($scope.currentPack);
759
+ });
760
+ }
761
+ }
762
+ if (action === 'delete') {
763
+ BootstrapDialog.confirm($L.get("The license '{0}' will be deleted, are you sure?", license.code), function(result){
764
+ if(result) {
765
+ _execute();
766
+ }
767
+ });
768
+ } else {
769
+ if (action === 'cancel') {
770
+ BootstrapDialog.show({
771
+ title: $L.get("License cancellation"),
772
+ type: BootstrapDialog.TYPE_DANGER,
773
+ message: function(dialog) {
774
+ var $content = $('<div></div>');
775
+ var $message = $('<div></div>');
776
+ var pageToLoad = dialog.getData('pageToLoad');
777
+ $message.append($('<label/>').text($L.get("This action cannot be undone.", license.code)));
778
+ $content.append($message);
779
+
780
+ var $message = $('<div style="margin-top:10pt;"/>');
781
+ $message.append($('<label style="margin-right:5pt;"/>').text($L.get("Cancellation reason:") + " "));
782
+ $message.append($('<input type="text" style="width:100%;" maxlength="512" id="_lic_cancellation_reason"/>'));
783
+ $content.append($message);
784
+ return $content;
785
+ },
786
+ closable: true,
787
+ buttons: [{
788
+ id: 'btn-cancel',
789
+ label: $L.get('Close'),
790
+ cssClass: 'btn-default',
791
+ action: function(dialogRef) {
792
+ dialogRef.close();
793
+ }
794
+ }, {
795
+ id: 'btn-ok',
796
+ label: $L.get('Cancel license'),
797
+ cssClass: 'btn-primary',
798
+ action: function(dialogRef){
799
+ var reason = $('#_lic_cancellation_reason').val();
800
+ console.log('Ready to cancel license, by reason: ' + reason);
801
+ if (!reason) {
802
+ $('#_lic_cancellation_reason').focus();
803
+ } else {
804
+ _execute({reason: reason});
805
+ dialogRef.close();
806
+ }
807
+ }
808
+ }]
809
+ });
810
+ } else {
811
+ _execute();
812
+ }
813
+ }
814
+ }
815
+
816
+
817
+ $scope.cancel = function() {
818
+ $scope.showForm = false;
819
+ }
820
+
821
+ $scope.showStatus = function(lic) {
822
+
823
+ }
824
+ $scope.showStatusLong = function(license) {
825
+
826
+ }
827
+
828
+ } ]);
824829
825830 })();