Roberto Sánchez
2014-01-10 59cdd2b7ebceae94fbecdb1eeb46a969666dc88f
#394 feature - Added all catalog resources with refereced fields
2 files added
14 files modified
changed files
securis/src/main/java/net/curisit/securis/SecurisErrorHandler.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/dao/UserDao.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/Application.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/LicenseType.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/Organization.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/User.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/ioc/RequestsModule.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/ApplicationResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/LicenseTypeResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/OrganizationResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/UserResource.java patch | view | blame | history
securis/src/main/resources/db/schema.sql patch | view | blame | history
securis/src/main/resources/static/admin.html patch | view | blame | history
securis/src/main/resources/static/js/admin.js patch | view | blame | history
securis/src/main/resources/static/js/catalogs.js patch | view | blame | history
securis/src/main/resources/static/js/catalogs.json patch | view | blame | history
securis/src/main/java/net/curisit/securis/SecurisErrorHandler.java
....@@ -9,6 +9,8 @@
99
1010 public class SecurisErrorHandler extends ErrorHandler {
1111
12
+ public static String HEADER_ERROR_MESSAGE = "X-SECURIS_ERROR";
13
+
1214 @Override
1315 protected void writeErrorPageHead(HttpServletRequest request, Writer writer, int code, String message) throws IOException {
1416 // TODO Auto-generated method stub
securis/src/main/java/net/curisit/securis/dao/UserDao.java
....@@ -25,12 +25,12 @@
2525 EntityManager em = emProvider.get();
2626 User user = new User();
2727 user.setUsername(username);
28
- user.setFullName("Rob San");
28
+ user.setFirstName("Rob");
2929 user.setPassword(Utils.sha256("rob"));
3030 user.setLang("en");
3131 user.setCreationTimestamp(new Date());
3232 user.setRoles(User.Rol.ADMIN | User.Rol.ADVANCE);
33
- user.setShortName("Rob");
33
+ user.setLastName("Sánchez");
3434 em.persist(user);
3535 User u2 = em.find(User.class, username);
3636 return u2;
securis/src/main/java/net/curisit/securis/db/Application.java
....@@ -42,6 +42,10 @@
4242 return id;
4343 }
4444
45
+ public void setId(int id) {
46
+ this.id = id;
47
+ }
48
+
4549 public String getName() {
4650 return name;
4751 }
securis/src/main/java/net/curisit/securis/db/LicenseType.java
....@@ -14,7 +14,11 @@
1414 import javax.persistence.Table;
1515
1616 import org.codehaus.jackson.annotate.JsonAutoDetect;
17
+import org.codehaus.jackson.annotate.JsonIgnoreProperties;
18
+import org.codehaus.jackson.annotate.JsonProperty;
1719 import org.codehaus.jackson.map.annotate.JsonSerialize;
20
+import org.slf4j.Logger;
21
+import org.slf4j.LoggerFactory;
1822
1923 /**
2024 * Entity implementation class for Entity: license_type
....@@ -22,12 +26,14 @@
2226 */
2327 @JsonAutoDetect
2428 @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
29
+@JsonIgnoreProperties(ignoreUnknown = true)
2530 @Entity
2631 @Table(name = "license_type")
2732 @NamedQueries(
28
- { @NamedQuery(name = "list-license_types", query = "SELECT lt FROM LicenseType lt") })
33
+ { @NamedQuery(name = "list-license_types", query = "SELECT new map(lt.id as id, lt.code as code, lt.name as name, lt.description as description, lt.creationTimestamp as creationTimestamp, ap.id as application_id, ap.name as application_name) FROM LicenseType lt inner join lt.application ap") })
2934 public class LicenseType implements Serializable {
3035
36
+ private static final Logger log = LoggerFactory.getLogger(LicenseType.class);
3137 private static final long serialVersionUID = 1L;
3238
3339 @Id
....@@ -77,6 +83,19 @@
7783 return application;
7884 }
7985
86
+ @JsonProperty("application_id")
87
+ public Integer getApplicationId() {
88
+ log.info("application " + application);
89
+ return application == null ? null : application.getId();
90
+ }
91
+
92
+ @JsonProperty("application_id")
93
+ public void setApplicationId(Integer appId) {
94
+ log.info("setApplicationId(Integer appId) " + appId);
95
+ application = new Application();
96
+ application.setId(appId);
97
+ }
98
+
8099 public void setApplication(Application application) {
81100 this.application = application;
82101 }
securis/src/main/java/net/curisit/securis/db/Organization.java
....@@ -1,6 +1,7 @@
11 package net.curisit.securis.db;
22
33 import java.io.Serializable;
4
+import java.util.ArrayList;
45 import java.util.Date;
56 import java.util.List;
67
....@@ -17,7 +18,11 @@
1718 import javax.persistence.Table;
1819
1920 import org.codehaus.jackson.annotate.JsonAutoDetect;
21
+import org.codehaus.jackson.annotate.JsonIgnore;
22
+import org.codehaus.jackson.annotate.JsonProperty;
2023 import org.codehaus.jackson.map.annotate.JsonSerialize;
24
+import org.slf4j.Logger;
25
+import org.slf4j.LoggerFactory;
2126
2227 /**
2328 * Entity implementation class for Entity: organization
....@@ -30,6 +35,9 @@
3035 @NamedQueries(
3136 { @NamedQuery(name = "list-organizations", query = "SELECT o FROM Organization o") })
3237 public class Organization implements Serializable {
38
+
39
+ @SuppressWarnings("unused")
40
+ private static final Logger log = LoggerFactory.getLogger(Organization.class);
3341
3442 private static final long serialVersionUID = 1L;
3543
....@@ -44,20 +52,28 @@
4452 @Column(name = "creation_timestamp")
4553 private Date creationTimestamp;
4654
55
+ @JsonIgnore
56
+ // We don't include the users to limit the size of each row a the listing
4757 @ManyToMany
4858 @JoinTable(name = "user_organization", //
4959 joinColumns =
5060 { @JoinColumn(name = "organization_id", referencedColumnName = "id") }, //
5161 inverseJoinColumns =
52
- { @JoinColumn(name = "user_id", referencedColumnName = "username") })
62
+ { @JoinColumn(name = "username", referencedColumnName = "username") })
5363 private List<User> users;
5464
65
+ @JsonIgnore
66
+ // We don't include the users to limit the size of each row a the listing
5567 @ManyToOne
5668 @JoinColumn(name = "org_parent_id")
5769 private Organization parentOrganization;
5870
5971 public int getId() {
6072 return id;
73
+ }
74
+
75
+ public void setId(int id) {
76
+ this.id = id;
6177 }
6278
6379 public String getName() {
....@@ -108,4 +124,43 @@
108124 this.parentOrganization = parentOrganization;
109125 }
110126
127
+ // Roberto: Following methods are necessary to include in the REST list response
128
+ // information about the referenced entities.
129
+ @JsonProperty("org_parent_id")
130
+ public void setParentOrgId(Integer orgId) {
131
+ parentOrganization = new Organization();
132
+ parentOrganization.setId(orgId);
133
+ }
134
+
135
+ @JsonProperty("org_parent_id")
136
+ public Integer getParentOrgId() {
137
+ return parentOrganization == null ? null : parentOrganization.getId();
138
+ }
139
+
140
+ @JsonProperty("org_parent_name")
141
+ public String getParentOrgName() {
142
+ return parentOrganization == null ? null : parentOrganization.getName();
143
+ }
144
+
145
+ @JsonProperty("users_ids")
146
+ public void setUsersIds(List<String> usersIds) {
147
+ users = new ArrayList<>();
148
+ for (String userid : usersIds) {
149
+ User u = new User();
150
+ u.setUsername(userid);
151
+ users.add(u);
152
+ }
153
+ }
154
+
155
+ @JsonProperty("users_ids")
156
+ public List<String> getUsersIds() {
157
+ if (users == null)
158
+ return null;
159
+ List<String> ids = new ArrayList<>();
160
+ for (User user : users) {
161
+ ids.add(user.getUsername());
162
+ }
163
+ return ids;
164
+ }
165
+
111166 }
securis/src/main/java/net/curisit/securis/db/User.java
....@@ -1,6 +1,7 @@
11 package net.curisit.securis.db;
22
33 import java.io.Serializable;
4
+import java.util.ArrayList;
45 import java.util.Date;
56 import java.util.List;
67
....@@ -15,6 +16,7 @@
1516 import javax.persistence.Table;
1617
1718 import org.codehaus.jackson.annotate.JsonAutoDetect;
19
+import org.codehaus.jackson.annotate.JsonIgnore;
1820 import org.codehaus.jackson.annotate.JsonProperty;
1921 import org.codehaus.jackson.map.annotate.JsonSerialize;
2022
....@@ -37,15 +39,16 @@
3739 private String username;
3840
3941 private String password;
40
- @JsonProperty(value = "short_name")
41
- @Column(name = "short_name")
42
- private String shortName;
42
+
43
+ @JsonProperty(value = "first_name")
44
+ @Column(name = "first_name")
45
+ private String firstName;
46
+
47
+ @JsonProperty(value = "last_name")
48
+ @Column(name = "last_name")
49
+ private String lastName;
4350
4451 private int roles;
45
-
46
- @JsonProperty(value = "full_name")
47
- @Column(name = "full_name")
48
- private String fullName;
4952
5053 @JsonProperty(value = "last_login")
5154 @Column(name = "last_login")
....@@ -59,10 +62,11 @@
5962
6063 private String lang;
6164
65
+ @JsonIgnore
6266 @ManyToMany
6367 @JoinTable(name = "user_organization", //
6468 joinColumns =
65
- { @JoinColumn(name = "user_id", referencedColumnName = "username") }, //
69
+ { @JoinColumn(name = "username", referencedColumnName = "username") }, //
6670 inverseJoinColumns =
6771 { @JoinColumn(name = "organization_id", referencedColumnName = "id") } //
6872 )
....@@ -92,20 +96,20 @@
9296 this.roles = roles;
9397 }
9498
95
- public String getFullName() {
96
- return fullName;
99
+ public String getFirstName() {
100
+ return firstName;
97101 }
98102
99
- public void setFullName(String fullName) {
100
- this.fullName = fullName;
103
+ public void setFirstName(String firstName) {
104
+ this.firstName = firstName;
101105 }
102106
103
- public String getShortName() {
104
- return shortName;
107
+ public String getLastName() {
108
+ return lastName;
105109 }
106110
107
- public void setShortName(String shortName) {
108
- this.shortName = shortName;
111
+ public void setLastName(String lastName) {
112
+ this.lastName = lastName;
109113 }
110114
111115 public Date getLastLogin() {
....@@ -134,7 +138,7 @@
134138
135139 @Override
136140 public String toString() {
137
- return "{User: " + username + " Full Name: " + fullName + ", last login: " + lastLogin + "}";
141
+ return "{User: " + username + " Name: " + firstName + " " + lastName + ", last login: " + lastLogin + "}";
138142 }
139143
140144 public String getLang() {
....@@ -153,6 +157,27 @@
153157 this.organizations = organizations;
154158 }
155159
160
+ @JsonProperty("organizations_ids")
161
+ public void setOrgsIds(List<Integer> orgsIds) {
162
+ organizations = new ArrayList<>();
163
+ for (Integer orgid : orgsIds) {
164
+ Organization o = new Organization();
165
+ o.setId(orgid);
166
+ organizations.add(o);
167
+ }
168
+ }
169
+
170
+ @JsonProperty("organizations_ids")
171
+ public List<Integer> getOrgsIds() {
172
+ if (organizations == null)
173
+ return null;
174
+ List<Integer> ids = new ArrayList<>();
175
+ for (Organization org : organizations) {
176
+ ids.add(org.getId());
177
+ }
178
+ return ids;
179
+ }
180
+
156181 static public class Rol {
157182 static public final int ADVANCE = 0x01;
158183 static public final int ADMIN = 0x02;
securis/src/main/java/net/curisit/securis/ioc/RequestsModule.java
....@@ -4,6 +4,7 @@
44 import net.curisit.securis.services.BasicServices;
55 import net.curisit.securis.services.LicenseServices;
66 import net.curisit.securis.services.LicenseTypeResource;
7
+import net.curisit.securis.services.OrganizationResource;
78 import net.curisit.securis.services.SecurityInterceptor;
89 import net.curisit.securis.services.UserResource;
910
....@@ -27,6 +28,7 @@
2728
2829 bind(ApplicationResource.class);
2930 bind(LicenseTypeResource.class);
31
+ bind(OrganizationResource.class);
3032 }
3133
3234 @Provides
securis/src/main/java/net/curisit/securis/services/ApplicationResource.java
....@@ -23,6 +23,7 @@
2323 import javax.ws.rs.core.Response.Status;
2424
2525 import net.curisit.integrity.commons.Utils;
26
+import net.curisit.securis.SecurisErrorHandler;
2627 import net.curisit.securis.db.Application;
2728 import net.curisit.securis.utils.TokenHelper;
2829
....@@ -87,7 +88,7 @@
8788 Application app = em.find(Application.class, Integer.parseInt(appid));
8889 if (app == null) {
8990 log.error("Application with id {} not found in DB", appid);
90
- return Response.status(Status.NOT_FOUND).build();
91
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "Application not found with ID: " + appid).build();
9192 }
9293 return Response.ok(app).build();
9394 }
....@@ -120,7 +121,7 @@
120121 Application currentapp = em.find(Application.class, Integer.parseInt(appid));
121122 if (currentapp == null) {
122123 log.error("Application with id {} not found in DB", appid);
123
- return Response.status(Status.NOT_FOUND).build();
124
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "Application not found with ID: " + appid).build();
124125 }
125126 currentapp.setName(app.getName());
126127 currentapp.setDescription(app.getDescription());
....@@ -140,7 +141,7 @@
140141 Application app = em.find(Application.class, Integer.parseInt(appid));
141142 if (app == null) {
142143 log.error("Application with id {} can not be deleted, It was not found in DB", appid);
143
- return Response.status(Status.NOT_FOUND).build();
144
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "Application not found with ID: " + appid).build();
144145 }
145146
146147 em.remove(app);
securis/src/main/java/net/curisit/securis/services/LicenseTypeResource.java
....@@ -6,7 +6,7 @@
66 import javax.inject.Inject;
77 import javax.inject.Provider;
88 import javax.persistence.EntityManager;
9
-import javax.persistence.TypedQuery;
9
+import javax.persistence.Query;
1010 import javax.servlet.http.HttpServletRequest;
1111 import javax.ws.rs.Consumes;
1212 import javax.ws.rs.DELETE;
....@@ -23,6 +23,8 @@
2323 import javax.ws.rs.core.Response.Status;
2424
2525 import net.curisit.integrity.commons.Utils;
26
+import net.curisit.securis.SecurisErrorHandler;
27
+import net.curisit.securis.db.Application;
2628 import net.curisit.securis.db.LicenseType;
2729 import net.curisit.securis.utils.TokenHelper;
2830
....@@ -39,13 +41,13 @@
3941 @Path("/licensetype")
4042 public class LicenseTypeResource {
4143
44
+ private static final Logger log = LoggerFactory.getLogger(LicenseTypeResource.class);
45
+
4246 @Inject
4347 TokenHelper tokenHelper;
4448
4549 @Inject
4650 Provider<EntityManager> emProvider;
47
-
48
- private static final Logger log = LoggerFactory.getLogger(LicenseTypeResource.class);
4951
5052 public LicenseTypeResource() {
5153 }
....@@ -62,8 +64,9 @@
6264 log.info("Getting license types list ");
6365
6466 EntityManager em = emProvider.get();
65
- TypedQuery<LicenseType> q = em.createNamedQuery("list-license_types", LicenseType.class);
66
- List<LicenseType> list = q.getResultList();
67
+ Query q = em.createNamedQuery("list-license_types");
68
+ @SuppressWarnings("unchecked")
69
+ List<Object> list = q.getResultList();
6770
6871 return Response.ok(list).build();
6972 }
....@@ -98,13 +101,23 @@
98101 @Produces(
99102 { MediaType.APPLICATION_JSON })
100103 @Transactional
101
- public Response create(LicenseType app, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
104
+ public Response create(LicenseType lt, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
102105 log.info("Creating new license type");
103106 EntityManager em = emProvider.get();
104
- app.setCreationTimestamp(new Date());
105
- em.persist(app);
107
+ Application app = null;
108
+ if (lt.getApplicationId() != null) {
109
+ app = em.find(Application.class, lt.getApplicationId());
110
+ if (app == null) {
111
+ log.error("LicenseType application with id {} not found in DB", lt.getApplicationId());
112
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "License type's app not found with ID: " + lt.getApplicationId()).build();
113
+ }
114
+ }
106115
107
- return Response.ok(app).build();
116
+ lt.setApplication(app);
117
+ lt.setCreationTimestamp(new Date());
118
+ em.persist(lt);
119
+
120
+ return Response.ok(lt).build();
108121 }
109122
110123 @PUT
....@@ -114,16 +127,26 @@
114127 @Consumes(MediaType.APPLICATION_JSON)
115128 @Produces(
116129 { MediaType.APPLICATION_JSON })
117
- public Response modify(LicenseType app, @PathParam("ltid") String ltid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
130
+ public Response modify(LicenseType lt, @PathParam("ltid") String ltid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
118131 log.info("Modifying license type with id: {}", ltid);
119132 EntityManager em = emProvider.get();
120133 LicenseType currentlt = em.find(LicenseType.class, Integer.parseInt(ltid));
121134 if (currentlt == null) {
122135 log.error("LicenseType with id {} not found in DB", ltid);
123
- return Response.status(Status.NOT_FOUND).build();
136
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "License type not found with ID: " + ltid).build();
124137 }
125
- currentlt.setName(app.getName());
126
- currentlt.setDescription(app.getDescription());
138
+ Application app = null;
139
+ if (lt.getApplicationId() != null) {
140
+ app = em.find(Application.class, lt.getApplicationId());
141
+ if (app == null) {
142
+ log.error("LicenseType application with id {} not found in DB", lt.getApplicationId());
143
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "License type's app not found with ID: " + lt.getApplicationId()).build();
144
+ }
145
+ }
146
+ currentlt.setCode(lt.getCode());
147
+ currentlt.setName(lt.getName());
148
+ currentlt.setDescription(lt.getDescription());
149
+ currentlt.setApplication(app);
127150 em.persist(currentlt);
128151
129152 return Response.ok(currentlt).build();
securis/src/main/java/net/curisit/securis/services/OrganizationResource.java
....@@ -0,0 +1,204 @@
1
+package net.curisit.securis.services;
2
+
3
+import java.util.ArrayList;
4
+import java.util.Date;
5
+import java.util.List;
6
+
7
+import javax.inject.Inject;
8
+import javax.inject.Provider;
9
+import javax.persistence.EntityManager;
10
+import javax.persistence.TypedQuery;
11
+import javax.servlet.http.HttpServletRequest;
12
+import javax.ws.rs.Consumes;
13
+import javax.ws.rs.DELETE;
14
+import javax.ws.rs.GET;
15
+import javax.ws.rs.HeaderParam;
16
+import javax.ws.rs.POST;
17
+import javax.ws.rs.PUT;
18
+import javax.ws.rs.Path;
19
+import javax.ws.rs.PathParam;
20
+import javax.ws.rs.Produces;
21
+import javax.ws.rs.core.Context;
22
+import javax.ws.rs.core.MediaType;
23
+import javax.ws.rs.core.Response;
24
+import javax.ws.rs.core.Response.Status;
25
+
26
+import net.curisit.integrity.commons.Utils;
27
+import net.curisit.securis.SecurisErrorHandler;
28
+import net.curisit.securis.db.Organization;
29
+import net.curisit.securis.db.User;
30
+import net.curisit.securis.utils.TokenHelper;
31
+
32
+import org.slf4j.Logger;
33
+import org.slf4j.LoggerFactory;
34
+
35
+import com.google.inject.persist.Transactional;
36
+
37
+/**
38
+ * Organization resource, this service will provide methods to create, modify and delete organizations
39
+ *
40
+ * @author roberto <roberto.sanchez@curisit.net>
41
+ */
42
+@Path("/organization")
43
+public class OrganizationResource {
44
+
45
+ private static final Logger log = LoggerFactory.getLogger(OrganizationResource.class);
46
+
47
+ @Inject
48
+ TokenHelper tokenHelper;
49
+
50
+ @Inject
51
+ Provider<EntityManager> emProvider;
52
+
53
+ public OrganizationResource() {
54
+ }
55
+
56
+ /**
57
+ *
58
+ * @return the server version in format majorVersion.minorVersion
59
+ */
60
+ @GET
61
+ @Path("/")
62
+ @Produces(
63
+ { MediaType.APPLICATION_JSON })
64
+ public Response index() {
65
+ log.info("Getting organizations list ");
66
+
67
+ EntityManager em = emProvider.get();
68
+ TypedQuery<Organization> q = em.createNamedQuery("list-organizations", Organization.class);
69
+
70
+ List<Organization> list = q.getResultList();
71
+
72
+ return Response.ok(list).build();
73
+ }
74
+
75
+ /**
76
+ *
77
+ * @return the server version in format majorVersion.minorVersion
78
+ */
79
+ @GET
80
+ @Path("/{orgid}")
81
+ @Produces(
82
+ { MediaType.APPLICATION_JSON })
83
+ public Response get(@PathParam("orgid") String orgid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
84
+ log.info("Getting organization data for id: {}: ", orgid);
85
+ if (orgid == null || orgid.equals("")) {
86
+ log.error("Organization ID is mandatory");
87
+ return Response.status(Status.NOT_FOUND).build();
88
+ }
89
+
90
+ EntityManager em = emProvider.get();
91
+ Organization lt = em.find(Organization.class, Integer.parseInt(orgid));
92
+ if (lt == null) {
93
+ log.error("Organization with id {} not found in DB", orgid);
94
+ return Response.status(Status.NOT_FOUND).build();
95
+ }
96
+ return Response.ok(lt).build();
97
+ }
98
+
99
+ @POST
100
+ @Path("/")
101
+ @Consumes(MediaType.APPLICATION_JSON)
102
+ @Produces(
103
+ { MediaType.APPLICATION_JSON })
104
+ @Transactional
105
+ public Response create(Organization org, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
106
+ log.info("Creating new organization");
107
+ EntityManager em = emProvider.get();
108
+ Organization parentOrg = null;
109
+ if (org.getParentOrgId() != null) {
110
+ parentOrg = em.find(Organization.class, org.getParentOrgId());
111
+ if (parentOrg == null) {
112
+ log.error("Organization parent with id {} not found in DB", org.getParentOrgId());
113
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "Organization's parent not found with ID: " + org.getParentOrgId()).build();
114
+ }
115
+ }
116
+ List<User> users = null;
117
+ List<String> usersIds = org.getUsersIds();
118
+ if (usersIds != null && usersIds.size() > 0) {
119
+ users = new ArrayList<>();
120
+ for (String username : usersIds) {
121
+ User user = em.find(User.class, username);
122
+ if (parentOrg == null) {
123
+ log.error("Organization user with id {} not found in DB", username);
124
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "Organization's user not found with ID: " + username).build();
125
+ }
126
+ users.add(user);
127
+ }
128
+ }
129
+
130
+ org.setUsers(users);
131
+ org.setParentOrganization(parentOrg);
132
+ org.setCreationTimestamp(new Date());
133
+ em.persist(org);
134
+
135
+ return Response.ok(org).build();
136
+ }
137
+
138
+ @PUT
139
+ @POST
140
+ @Path("/{orgid}")
141
+ @Transactional
142
+ @Consumes(MediaType.APPLICATION_JSON)
143
+ @Produces(
144
+ { MediaType.APPLICATION_JSON })
145
+ public Response modify(Organization org, @PathParam("orgid") String orgid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
146
+ log.info("Modifying organization with id: {}", orgid);
147
+ EntityManager em = emProvider.get();
148
+ Organization currentOrg = em.find(Organization.class, Integer.parseInt(orgid));
149
+ if (currentOrg == null) {
150
+ log.error("Organization with id {} not found in DB", orgid);
151
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "Organization not found with ID: " + orgid).build();
152
+ }
153
+ Organization parentOrg = null;
154
+ if (org.getParentOrgId() != null) {
155
+ parentOrg = em.find(Organization.class, org.getParentOrgId());
156
+ if (parentOrg == null) {
157
+ log.error("Organization parent with id {} not found in DB", org.getParentOrgId());
158
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "Organization's parent not found with ID: " + org.getParentOrgId()).build();
159
+ }
160
+ }
161
+
162
+ List<User> users = null;
163
+ List<String> usersIds = org.getUsersIds();
164
+ if (usersIds != null && usersIds.size() > 0) {
165
+ users = new ArrayList<>();
166
+ for (String username : usersIds) {
167
+ User user = em.find(User.class, username);
168
+ if (parentOrg == null) {
169
+ log.error("Organization user with id {} not found in DB", username);
170
+ return Response.status(Status.NOT_FOUND).header(SecurisErrorHandler.HEADER_ERROR_MESSAGE, "Organization's user not found with ID: " + username).build();
171
+ }
172
+ users.add(user);
173
+ }
174
+ }
175
+
176
+ currentOrg.setUsers(users);
177
+ currentOrg.setParentOrganization(parentOrg);
178
+ currentOrg.setCode(org.getCode());
179
+ currentOrg.setName(org.getName());
180
+ currentOrg.setDescription(org.getDescription());
181
+ em.persist(currentOrg);
182
+
183
+ return Response.ok(currentOrg).build();
184
+ }
185
+
186
+ @DELETE
187
+ @Path("/{orgid}")
188
+ @Transactional
189
+ @Produces(
190
+ { MediaType.APPLICATION_JSON })
191
+ public Response delete(@PathParam("orgid") String orgid, @Context HttpServletRequest request) {
192
+ log.info("Deleting app with id: {}", orgid);
193
+ EntityManager em = emProvider.get();
194
+ Organization app = em.find(Organization.class, Integer.parseInt(orgid));
195
+ if (app == null) {
196
+ log.error("Organization with id {} can not be deleted, It was not found in DB", orgid);
197
+ return Response.status(Status.NOT_FOUND).build();
198
+ }
199
+
200
+ em.remove(app);
201
+ return Response.ok(Utils.createMap("success", true, "id", orgid)).build();
202
+ }
203
+
204
+}
securis/src/main/java/net/curisit/securis/services/UserResource.java
....@@ -1,10 +1,21 @@
11 package net.curisit.securis.services;
22
3
+import java.util.ArrayList;
4
+import java.util.Date;
5
+import java.util.List;
6
+
37 import javax.inject.Inject;
8
+import javax.inject.Provider;
9
+import javax.persistence.EntityManager;
10
+import javax.persistence.TypedQuery;
411 import javax.servlet.http.HttpServletRequest;
12
+import javax.ws.rs.Consumes;
13
+import javax.ws.rs.DELETE;
514 import javax.ws.rs.FormParam;
615 import javax.ws.rs.GET;
16
+import javax.ws.rs.HeaderParam;
717 import javax.ws.rs.POST;
18
+import javax.ws.rs.PUT;
819 import javax.ws.rs.Path;
920 import javax.ws.rs.PathParam;
1021 import javax.ws.rs.Produces;
....@@ -14,10 +25,14 @@
1425 import javax.ws.rs.core.Response.Status;
1526
1627 import net.curisit.integrity.commons.Utils;
28
+import net.curisit.securis.db.Organization;
29
+import net.curisit.securis.db.User;
1730 import net.curisit.securis.utils.TokenHelper;
1831
1932 import org.slf4j.Logger;
2033 import org.slf4j.LoggerFactory;
34
+
35
+import com.google.inject.persist.Transactional;
2136
2237 /**
2338 * User resource
....@@ -29,6 +44,9 @@
2944
3045 @Inject
3146 TokenHelper tokenHelper;
47
+
48
+ @Inject
49
+ Provider<EntityManager> emProvider;
3250
3351 // private LicenseHelper licenseHelper = InjectorFactory.getInjector().getInstance(LicenseHelper.class);
3452 private static final Logger log = LoggerFactory.getLogger(UserResource.class);
....@@ -43,9 +61,134 @@
4361 @GET
4462 @Path("/")
4563 @Produces(
46
- { MediaType.TEXT_PLAIN })
47
- public Response index(@Context HttpServletRequest request) {
48
- return Response.ok("User resource").build();
64
+ { MediaType.APPLICATION_JSON })
65
+ public Response index() {
66
+ log.info("Getting users list ");
67
+
68
+ EntityManager em = emProvider.get();
69
+ TypedQuery<User> q = em.createNamedQuery("list-users", User.class);
70
+
71
+ List<User> list = q.getResultList();
72
+
73
+ return Response.ok(list).build();
74
+ }
75
+
76
+ /**
77
+ *
78
+ * @return The user
79
+ */
80
+ @GET
81
+ @Path("/{uid}")
82
+ @Produces(
83
+ { MediaType.APPLICATION_JSON })
84
+ public Response get(@PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
85
+ log.info("Getting user data for id: {}: ", uid);
86
+ if (uid == null || uid.equals("")) {
87
+ log.error("User ID is mandatory");
88
+ return Response.status(Status.NOT_FOUND).build();
89
+ }
90
+
91
+ EntityManager em = emProvider.get();
92
+ User lt = em.find(User.class, Integer.parseInt(uid));
93
+ if (lt == null) {
94
+ log.error("User with id {} not found in DB", uid);
95
+ return Response.status(Status.NOT_FOUND).build();
96
+ }
97
+ return Response.ok(lt).build();
98
+ }
99
+
100
+ @POST
101
+ @Path("/")
102
+ @Consumes(MediaType.APPLICATION_JSON)
103
+ @Produces(
104
+ { MediaType.APPLICATION_JSON })
105
+ @Transactional
106
+ public Response create(User user, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
107
+ log.info("Creating new user");
108
+ EntityManager em = emProvider.get();
109
+ List<Organization> orgs = null;
110
+ List<Integer> orgsIds = user.getOrgsIds();
111
+ if (orgsIds != null && orgsIds.size() > 0) {
112
+ orgs = new ArrayList<>();
113
+ for (Integer orgId : orgsIds) {
114
+ Organization o = em.find(Organization.class, orgId);
115
+ if (o == null) {
116
+ log.error("User organization with id {} not found in DB", orgId);
117
+ return Response.status(Status.NOT_FOUND).header("SECURIS_ERROR", "User's organization not found with ID: " + orgId).build();
118
+ }
119
+ orgs.add(o);
120
+ }
121
+ }
122
+
123
+ user.setOrganizations(orgs);
124
+ user.setModificationTimestamp(new Date());
125
+ user.setLastLogin(null);
126
+ user.setCreationTimestamp(new Date());
127
+ em.persist(user);
128
+
129
+ return Response.ok(user).build();
130
+ }
131
+
132
+ @PUT
133
+ @POST
134
+ @Path("/{uid}")
135
+ @Transactional
136
+ @Consumes(MediaType.APPLICATION_JSON)
137
+ @Produces(
138
+ { MediaType.APPLICATION_JSON })
139
+ public Response modify(User user, @PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
140
+ log.info("Modifying user with id: {}", uid);
141
+ EntityManager em = emProvider.get();
142
+ User currentUser = em.find(User.class, Integer.parseInt(uid));
143
+ if (currentUser == null) {
144
+ log.error("User with id {} not found in DB", uid);
145
+ return Response.status(Status.NOT_FOUND).header("SECURIS_ERROR", "User not found with ID: " + uid).build();
146
+ }
147
+
148
+ List<Organization> orgs = null;
149
+ List<Integer> orgsIds = user.getOrgsIds();
150
+ if (orgsIds != null && orgsIds.size() > 0) {
151
+ orgs = new ArrayList<>();
152
+ for (Integer orgId : orgsIds) {
153
+ Organization o = em.find(Organization.class, orgId);
154
+ if (o == null) {
155
+ log.error("User organization with id {} not found in DB", orgId);
156
+ return Response.status(Status.NOT_FOUND).header("SECURIS_ERROR", "User's user not found with ID: " + orgId).build();
157
+ }
158
+ orgs.add(o);
159
+ }
160
+ }
161
+
162
+ currentUser.setOrganizations(orgs);
163
+ currentUser.setFirstName(user.getFirstName());
164
+ currentUser.setLastName(user.getLastName());
165
+ currentUser.setRoles(user.getRoles());
166
+ currentUser.setLang(user.getLang());
167
+ currentUser.setModificationTimestamp(new Date());
168
+ currentUser.setPassword(user.getPassword());
169
+ currentUser.setLastLogin(user.getLastLogin());
170
+
171
+ em.persist(currentUser);
172
+
173
+ return Response.ok(currentUser).build();
174
+ }
175
+
176
+ @DELETE
177
+ @Path("/{uid}")
178
+ @Transactional
179
+ @Produces(
180
+ { MediaType.APPLICATION_JSON })
181
+ public Response delete(@PathParam("uid") String uid, @Context HttpServletRequest request) {
182
+ log.info("Deleting app with id: {}", uid);
183
+ EntityManager em = emProvider.get();
184
+ User app = em.find(User.class, Integer.parseInt(uid));
185
+ if (app == null) {
186
+ log.error("User with id {} can not be deleted, It was not found in DB", uid);
187
+ return Response.status(Status.NOT_FOUND).build();
188
+ }
189
+
190
+ em.remove(app);
191
+ return Response.ok(Utils.createMap("success", true, "id", uid)).build();
49192 }
50193
51194 @POST
....@@ -64,18 +207,6 @@
64207 return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();
65208 }
66209
67
- /**
68
- * @return the version of the three entities that can be synchronized (Users, DataSet and Settings)
69
- */
70
- @GET
71
- @Path("/{username}")
72
- @Produces(
73
- { MediaType.APPLICATION_JSON })
74
- // @RolesAllowed("advance")
75
- public Response main(@PathParam("username") String username) {
76
- return Response.ok().entity(Utils.createMap("name", "Pepito", "username", username)).build();
77
- }
78
-
79210 @GET
80211 @Path("/logout")
81212 @Produces(
....@@ -84,45 +215,4 @@
84215 request.getSession().invalidate();
85216 return Response.ok().build();
86217 }
87
-
88
- //
89
- // private <T> ServiceResponse<T> buildErrorResponse(ServiceResponse<T> response, String msgErrorCode) {
90
- // response.setSuccess(false);
91
- // response.setErrorMessage(localManager.getString(msgErrorCode));
92
- // response.setErrorMessageCode(msgErrorCode);
93
- // return response;
94
- // }
95
- //
96
- // private Date calculateCaducation() {
97
- // Integer licenseExpiration = systemParams.getParamAsInt(SystemParams.Keys.CONFIG_SERVER_LICENSE_EXPIRATION);
98
- // if (licenseExpiration == null)
99
- // licenseExpiration = DEFAULT_LICENSE_EXPIRATION;
100
- // return Utils.addDays(new Date(), licenseExpiration);
101
- // }
102
- //
103
- // private boolean validateLicense(String license) {
104
- // BasicApplication ba = basicApplicationDao.findByLicense(license);
105
- // return (ba != null);
106
- // }
107
- //
108
- // private boolean validateVersion(int minorVersion, int majorVersion) {
109
- // return (versionManager.getMajorVersion() == majorVersion);
110
- // }
111
- //
112
- // private BasicApplication findBasicApp(String license) {
113
- // BasicApplication ba = basicApplicationDao.findByLicense(license);
114
- // return ba;
115
- // }
116
- //
117
- // private License generateLicense() {
118
- // // TODO complete all field of the license
119
- // License license = new License();
120
- // license.setCustomerCode(systemParams.getParam(SystemParams.Keys.CONFIG_COMMON_CUSTOMER_CODE));
121
- // license.setCSCode(systemParams.getParam(SystemParams.Keys.CONFIG_COMMON_CS_CODE));
122
- // license.setCRCLogo("00000000");
123
- // license.setExpirationDate(calculateCaducation());
124
- // license.setInstallCode(codeGenerator.generateInstalationNumber());
125
- // return license;
126
- // }
127
-
128218 }
securis/src/main/resources/db/schema.sql
....@@ -9,9 +9,9 @@
99 CREATE TABLE IF NOT EXISTS user (
1010 username VARCHAR(45) NOT NULL ,
1111 password VARCHAR(100) NULL ,
12
- roles INT NULL ,
13
- full_name VARCHAR(100) NULL ,
14
- short_name VARCHAR(3) NULL ,
12
+ roles INT NOT NULL default 0,
13
+ first_name VARCHAR(100) NULL ,
14
+ last_name VARCHAR(100) NULL ,
1515 last_login DATETIME NULL ,
1616 lang VARCHAR(10) NULL ,
1717 creation_timestamp DATETIME NULL ,
....@@ -49,9 +49,9 @@
4949
5050 drop table IF EXISTS user_organization;
5151 CREATE TABLE IF NOT EXISTS user_organization (
52
- user_id INT NOT NULL,
52
+ username VARCHAR(45) NOT NULL,
5353 organization_id INT NOT NULL,
54
- PRIMARY KEY (user_id, organization_id));
54
+ PRIMARY KEY (username, organization_id));
5555
5656 drop table IF EXISTS pack;
5757 CREATE TABLE IF NOT EXISTS pack (
securis/src/main/resources/static/admin.html
....@@ -89,7 +89,7 @@
8989 <div class="col-md-2">
9090
9191 <ul class="nav nav-pills nav-stacked">
92
- <li ng-repeat="catalog in catalogs.data" ng-class="{active: $index === catalogIndex}"><a ng-click="selectCatalog($index, $event)" ng-bind="catalog.name"></a></li>
92
+ <li ng-repeat="catalog in catalogsList" ng-class="{active: $index === catalogIndex}"><a ng-click="selectCatalog($index)" ng-bind="catalog.name"></a></li>
9393 </ul>
9494
9595 </div>
....@@ -123,7 +123,7 @@
123123 <div class="panel panel-default animate-show ng-hide" ng-show="showForm">
124124 <form role="form" class="form-horizontal " name="catalogForm" id="catalogForm" ng-submit="saveCatalog()" >
125125 <!-- <pre>formu: {{formu | json}}</pre>-->
126
- <div class="form-group" ng-repeat="field in catalogMetadata.fields" ng-if="!isNew || !field.readOnly">
126
+ <div class="form-group" ng-repeat="field in catalogMetadata.fields" ng-if="(!isNew || !field.readOnly) && !field.listingOnly">
127127 <label class="col-md-3 control-label" for="{{field.name}}">{{field.display}}</label>
128128 <div class="col-md-5">
129129 <div ng-switch on="inputType(field)">
....@@ -171,7 +171,7 @@
171171 </thead>
172172 <tbody>
173173 <tr ng-repeat="row in list | filter:searchText" ng-dblclick="edit(row)">
174
- <td ng-repeat="field in catalogMetadata.list_fields" ng-bind="print(field, row[field])"></td>
174
+ <td ng-repeat="field in catalogMetadata.list_fields" ng-bind="print(field, row)"></td>
175175
176176 <td><span ng-click="edit(row)"
177177 class="glyphicon glyphicon-pencil"></span>
....@@ -228,6 +228,7 @@
228228 <script type="text/javascript"
229229 src="//code.angularjs.org/1.2.7/angular-animate.js"></script>
230230 -->
231
+ <script type="text/javascript" src="js/catalogs.js"></script>
231232 <script type="text/javascript" src="js/admin.js"></script>
232233
233234 <!-- <script src="js/main.js"></script> -->
securis/src/main/resources/static/js/admin.js
....@@ -1,7 +1,7 @@
11 (function() {
22 'use strict';
33
4
- var app = angular.module('app', [ 'ngRoute', 'ngAnimate', 'ngResource', 'toaster' ]);
4
+ var app = angular.module('app', [ 'ngRoute', 'ngAnimate', 'ngResource', 'toaster', 'catalogs' ]);
55
66 app.directive(
77 'catalogField',
....@@ -22,124 +22,34 @@
2222 };
2323 });
2424
25
- app.factory('Catalogs', function($http, $resource, toaster) {
26
- var CatalogsService = {
27
- resources : {
28
- application : $resource('/application/:appId', {
29
- appId : '@id'
30
- }, {
31
- update : {
32
- method : "PUT"
33
- }
34
- }),
35
- user : $resource('/user/:userId', {
36
- userId : '@id'
37
- }, {
38
- update : {
39
- method : "PUT"
40
- }
41
- }),
42
- licensetype : $resource('/licensetype/:licenseTypeId', {
43
- licenseTypeId : '@id'
44
- }, {
45
- update : {
46
- method : "PUT"
47
- }
48
- })
49
-
50
- },
51
- list : function(initFn) {
52
- $http.get('/js/catalogs.json').success(function(data) {
53
- console.log(data);
54
- CatalogsService.data = data;
55
- initFn();
56
- })
57
- return CatalogsService;
58
- },
59
- getName : function(index) {
60
- return CatalogsService.data ? CatalogsService.data[index].name
61
- : '';
62
- },
63
- getResource : function(index) {
64
- return CatalogsService.data ? CatalogsService.data[index].resource
65
- : '';
66
- },
67
- getMetadata : function(index) {
68
- return CatalogsService.data ? CatalogsService.data[index] : {};
69
- },
70
- save: function(catalog, data) {
71
- var resource = CatalogsService.resources[catalog.toLowerCase()];
72
- function success(data) {
73
- console.log('success')
74
- console.log(data)
75
- toaster.pop('success', "Data saved sucessfully in " + catalog);
76
- }
77
- function fail(data, status) {
78
- var errorMsg = {500: 'Server error', 404: 'Item to modify was not found'}[data.status]
79
- toaster.pop('error', "Error saving data in " + catalog, errorMsg);
80
- console.log('error')
81
- console.error(data)
82
- console.error(status)
83
- }
84
- if (data.id && data.id !== '')
85
- return resource.update(data, success, fail)
86
- else
87
- return resource.save(data, success, fail)
88
- },
89
- remove: function(catalog, data) {
90
- var resource = CatalogsService.resources[catalog.toLowerCase()];
91
- function success(data) {
92
- console.log('success')
93
- console.log(data)
94
- }
95
- function fail(data, status) {
96
- console.log('error')
97
- console.error(data)
98
- console.error(status)
99
- }
100
- return resource.remove({}, data, success, fail)
101
- },
102
- query: function(catalog) {
103
- console.log('HI catalog ???? ' + catalog);
104
- var resource = CatalogsService.resources[catalog];
105
- function success(data) {
106
- console.log('success')
107
- console.log(data)
108
- }
109
- function fail(data, status) {
110
- console.log('error')
111
- console.error(data)
112
- console.error(status)
113
- }
114
- return resource.query({}, success, fail);
115
- }
116
- }
117
-
118
- return CatalogsService;
119
-
120
- });
121
-
12225 app.controller('CatalogsCtrl', [
12326 '$scope',
12427 '$http',
12528 'Catalogs',
12629 function($scope, $http, Catalogs) {
127
- $scope.showForm = true;
30
+ $scope.showForm = false;
12831 $scope.isNew = false;
12932 $scope.formu = {};
13033 $scope.catalogIndex = 0;
131
- $scope.catalogs = Catalogs.list(function() {
132
- $scope.catalogMetadata = Catalogs.getMetadata($scope.catalogIndex);
133
- $scope.list = Catalogs.query(Catalogs.getResource($scope.catalogIndex));
134
- });
135
-
13634 $scope.catalogMetadata = {};
137
- $scope.selectCatalog = function(index, $event) {
138
- $scope.catalogIndex = index;
139
- $scope.catalogMetadata = Catalogs.getMetadata($scope.catalogIndex);
140
- $scope.list = Catalogs.query(Catalogs.getResource($scope.catalogIndex));
141
- console.log($event);
35
+ $scope.catalogsList = null;
36
+ $scope.list = null;
37
+
38
+ var _changeCatalog = function(index) {
39
+ if (!$scope.catalogsList) $scope.catalogsList = Catalogs.getList(); // catalog list is also in index.data
40
+ if (typeof index === 'number') $scope.catalogIndex = index;
41
+ Catalogs.setCurrent($scope.catalogIndex);
42
+ $scope.catalogMetadata = Catalogs.getMetadata();
43
+ $scope.list = Catalogs.query();
44
+ $scope.refs = {}
45
+ Catalogs.loadRefs($scope.refs)
46
+ console.log($scope.refs)
14247 }
48
+
49
+ Catalogs.init().then(_changeCatalog);
50
+
51
+ $scope.selectCatalog = _changeCatalog;
52
+
14353 $scope.edit = function(data) {
14454 $scope.showForm = true;
14555 $scope.isNew = false;
....@@ -149,15 +59,16 @@
14959 }
15060 console.log('$scope.edit')
15161 console.log($scope.formu)
62
+ $('#'+ Catalogs.getFFF()).focus();
63
+
15264
15365 }
15466 $scope.delete = function(data) {
15567 BootstrapDialog.confirm('The record will be deleted, are you sure?', function(result){
15668 if(result) {
157
- var catalogName = Catalogs.getResource($scope.catalogIndex);
158
- var promise = Catalogs.remove(catalogName, data).$promise;
69
+ var promise = Catalogs.remove(data).$promise;
15970 promise.then(function(data) {
160
- $scope.list = Catalogs.query(catalogName);
71
+ $scope.list = Catalogs.query();
16172 });
16273 }
16374 });
....@@ -190,7 +101,7 @@
190101 }
191102
192103 $scope.editNew = function() {
193
- $('#name').focus();
104
+ $('#'+ Catalogs.getFFF()).focus();
194105 $scope.$parent.showForm = true;
195106 $scope.$parent.isNew = true;
196107 $scope.$parent.formu = {};
....@@ -203,20 +114,17 @@
203114 if ($scope.catalogForm.$invalid) {
204115 alert(JSON.stringify($scope.catalogForm))
205116 } else {
206
- var catalogName = Catalogs.getResource($scope.catalogIndex);
207
- var promise = Catalogs.save(catalogName, $scope.formu).$promise;
117
+ var promise = Catalogs.save($scope.formu).$promise;
208118 promise.then(function(data, otro) {
209119 if ($scope.isNew) {
210120 $scope.$parent.formu = {}
211
- $('#name').focus();
121
+ $('#'+ Catalogs.getFFF()).focus();
212122 } else {
213123 $scope.cancel();
214124 }
215
- $scope.$parent.list = Catalogs.query(catalogName);
216
- }, function(error, otro) {
217
- console.log('then error');
125
+ $scope.$parent.list = Catalogs.query();
126
+ }, function(error) {
218127 console.log(error);
219
- console.log(otro);
220128 });
221129
222130 }
....@@ -225,24 +133,18 @@
225133
226134 app.controller('CatalogListCtrl', [ '$scope', '$http', '$filter', 'Catalogs',
227135 function($scope, $http, $filter, Catalogs) {
228
- console.log('List: currentCatalog: ' + $scope.currentCatalog);
229
- var _indexOfField = function(name) {
230
- if (!$scope.catalogMetadata) return -1;
231
- for (var i = $scope.catalogMetadata.fields.length - 1; i >= 0 && $scope.catalogMetadata.fields[i].name !== name; i--);
232
- return i;
233
- }
234
-
235
- $scope.print = function(name, value) {
236
- var index = _indexOfField(name);
237
- if (index === -1) return value;
238
- var type = $scope.catalogMetadata.fields[index].type;
239
-
240
- return type === 'date' ? $filter('date')(value, 'yyyy-MM-dd') : value;
136
+
137
+ $scope.print = function(name, row) {
138
+ var value = row[name];
139
+ var type = Catalogs.getField(name).type;
140
+ var printedValue = type === 'date' ? $filter('date')(value, 'yyyy-MM-dd') : value;
141
+ if (printedValue !== value) // this line is a work around to allow search in formatted fields
142
+ row['_display_'+name] = printedValue;
143
+ return printedValue;
241144 }
242145
243146 $scope.display = function(name) {
244
- var index = _indexOfField(name);
245
- return index === -1 ? '' : $scope.catalogMetadata.fields[index].display;
147
+ return Catalogs.getField(name).display;
246148 }
247149
248150 } ]);
securis/src/main/resources/static/js/catalogs.js
....@@ -0,0 +1,188 @@
1
+(function() {
2
+ 'use strict';
3
+
4
+ /*
5
+ * Catalogs module
6
+ */
7
+
8
+ angular.module('catalogs', ['ngResource'])
9
+
10
+ .service('Catalogs', ['$rootScope', '$http', '$resource', '$q', function ($rootScope, $http, $resource, $q) {
11
+ var resources = {
12
+ application : $resource('/application/:appId', {
13
+ appId : '@id'
14
+ }, {
15
+ update : {
16
+ method : "PUT"
17
+ }
18
+ }),
19
+ user : $resource('/user/:userId', {
20
+ userId : '@id'
21
+ }, {
22
+ update : {
23
+ method : "PUT"
24
+ }
25
+ }),
26
+ licensetype : $resource('/licensetype/:licenseTypeId', {
27
+ licenseTypeId : '@id'
28
+ }, {
29
+ update : {
30
+ method : "PUT"
31
+ }
32
+ })
33
+ }
34
+
35
+ var _metadata = null;
36
+ var _current = null;
37
+
38
+ var _list = function() {
39
+ return $http.get('/js/catalogs.json').success(function(data) {
40
+ _metadata = data;
41
+ })
42
+ }
43
+ this.init = function() {
44
+ return _list();
45
+ }
46
+ this.getList = function() {
47
+ return _metadata;
48
+ }
49
+ this.getName = function(index) {
50
+ if (index === undefined)
51
+ return _current ? _current.name : '';
52
+ return _metadata ? _metadata[index].name : '';
53
+ }
54
+ this.getResource = function(res) {
55
+ if (res === undefined)
56
+ return _current ? resources[_current.resource] : null;
57
+ return _current ? resources[res] : null;
58
+ }
59
+ this.getPk = function(catalogMetadata) {
60
+ if (!catalogMetadata) catalogMetadata = _current;
61
+
62
+ for(var i = 0; i < catalogMetadata.fields.length; i++)
63
+ if (catalogMetadata.fields[i].pk) return catalogMetadata.fields[i].name;
64
+
65
+ return null;
66
+ }
67
+ /**
68
+ * Returns catalog metadata
69
+ * @param index: Return current catalog if undefined, if string It find the catalog by resoource name if number it find it by position
70
+ */
71
+ this.getMetadata = function(index) {
72
+ if (!_metadata) throw new Error('There is no catalog metadata info');
73
+ if (index === undefined)
74
+ return _current;
75
+ if (typeof index === 'string') {
76
+ for (var i = _metadata.length - 1; i >= 0 && _metadata[i].resource !== index; i--);
77
+ index = i;
78
+ }
79
+
80
+ return _metadata[index];
81
+ }
82
+ this.setCurrent = function(index) {
83
+ if (!_metadata) throw new Error('There is no catalog metadata info');
84
+ if (index === undefined)
85
+ _current = null;
86
+ else
87
+ _current = _metadata[index];
88
+ }
89
+ /********************************************
90
+ * Catalog fields methods *
91
+ ********************************************/
92
+
93
+ /**
94
+ * Returns the first field in form that should get the focus. We find the first field that is not read only
95
+ */
96
+ this.getFFF = this.getFirstFocusableField = function() {
97
+ if (!_current) throw new Error('There is no current catalog selected');
98
+
99
+ for(var i = i; i < _current.fields.length; i++)
100
+ if (f.readOnly) return f.name;
101
+
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * Find the field by name or position
107
+ */
108
+ this.getField = function(key) {
109
+ if (!_current) throw new Error('There is no current catalog selected');
110
+ var index = -1;
111
+ if (typeof key === 'string') {
112
+ for (var i = _current.fields.length - 1; i >= 0 && _current.fields[i].name !== key; i--);
113
+ index = i;
114
+ } else {
115
+ index = key; // In this case key === field position
116
+ }
117
+
118
+ return index === -1 ? {} : _current.fields[index];
119
+ }
120
+
121
+ /********************************************
122
+ * Catalog resource operations on server *
123
+ ********************************************/
124
+
125
+ function _success(response) {
126
+ console.log('$resource')
127
+ console.log(response)
128
+ }
129
+ function _fail(response) {
130
+ console.error('Error trying to get data, HTTP error code: ' + response.status)
131
+ }
132
+
133
+
134
+ this.save = function(data) {
135
+ if (!_current) throw new Error('There is no current catalog selected');
136
+
137
+ var resource = this.getResource();
138
+ if (data.id && data.id !== '')
139
+ return resource.update(data, _success, _fail);
140
+ else
141
+ return resource.save(data, _success, _fail);
142
+ }
143
+ this.remove = function(data) {
144
+ return this.getResource().remove({}, data, _success, _fail)
145
+ }
146
+ this.query = function() {
147
+ return this.getResource().query({}, _success, _fail);
148
+ }
149
+ this.loadRefs = function(refs) {
150
+ if (!_current) throw new Error('There is no current catalog selected');
151
+ var refsFields = [];
152
+ _current.fields.forEach(function(f) {
153
+ if (f.resource)
154
+ refsFields.push(f)
155
+ });
156
+
157
+ var that = this;
158
+ var promises = []
159
+ refsFields.forEach(function(f) {
160
+ var resource = that.getResource(f.resource);
161
+ refs[f.name] = resource.query({}, _success, _fail);
162
+ promises.push(refs[f.name].$promise);
163
+ });
164
+
165
+ console.log('promises: ' + promises.length + ' ')
166
+ console.log(promises)
167
+ $q.all(promises).then(function() {
168
+ console.log('ALL promises OK :::::::::::::::::::::::::::: ')
169
+ for (var k in refs) {
170
+ var pk = that.getPk(that.getMetadata(k))
171
+ console.log('PK for '+k+' is ' + pk);
172
+ var comboData = []
173
+ refs[k].forEach(function(row) {
174
+ comboData.push({
175
+ id: row[pk],
176
+ label: row.label || row.name || row.code
177
+ });
178
+ })
179
+ refs[k] = comboData;
180
+ }
181
+
182
+ })
183
+ return refs;
184
+ }
185
+
186
+ }])
187
+
188
+})();
securis/src/main/resources/static/js/catalogs.json
....@@ -28,6 +28,7 @@
2828 } ]
2929 }, {
3030 "name" : "License types",
31
+ "list_fields" : [ "code", "name", "application_name", "creationTimestamp" ],
3132 "resource" : "licensetype",
3233 "fields" : [ {
3334 "name" : "id",
....@@ -54,23 +55,66 @@
5455 "maxlength" : 500,
5556 "multiline" : 2
5657 }, {
57
- "name" : "application",
58
+ "name" : "application_id",
5859 "display" : "Application",
59
- "type" : "select",
60
- "readOnly" : true
60
+ "resource" : "application",
61
+ "type" : "select"
6162 }, {
6263 "name" : "creationTimestamp",
6364 "display" : "Creation date",
6465 "type" : "date",
6566 "readOnly" : true
67
+ }, {
68
+ "name" : "application_name",
69
+ "display" : "Application",
70
+ "listingOnly" : true
71
+ } ]
72
+}, {
73
+ "name" : "Organizations",
74
+ "list_fields" : [ "code", "name", "application_name", "creationTimestamp" ],
75
+ "resource" : "organization",
76
+ "fields" : [ {
77
+ "name" : "id",
78
+ "display" : "ID",
79
+ "type" : "number",
80
+ "pk" : true,
81
+ "readOnly" : true
82
+ }, {
83
+ "name" : "code",
84
+ "display" : "Code",
85
+ "type" : "string",
86
+ "maxlength" : 10,
87
+ "mandatory" : true
88
+ }, {
89
+ "name" : "name",
90
+ "display" : "Name",
91
+ "type" : "string",
92
+ "maxlength" : 45,
93
+ "mandatory" : true
94
+ }, {
95
+ "name" : "description",
96
+ "display" : "Description",
97
+ "type" : "string",
98
+ "maxlength" : 500,
99
+ "multiline" : 2
100
+ }, {
101
+ "name" : "application_id",
102
+ "display" : "Application",
103
+ "resource" : "application",
104
+ "type" : "select"
105
+ }, {
106
+ "name" : "creationTimestamp",
107
+ "display" : "Creation date",
108
+ "type" : "date",
109
+ "readOnly" : true
110
+ }, {
111
+ "name" : "application_name",
112
+ "display" : "Application",
113
+ "listingOnly" : true
66114 } ]
67115 }, {
68116 "name" : "Users",
69117 "resource" : "user",
70
- "fields" : []
71
-}, {
72
- "name" : "Organizations",
73
- "resource" : "organization",
74118 "fields" : []
75119 }, {
76120 "name" : "System params",