Roberto Sánchez
2014-01-10 59cdd2b7ebceae94fbecdb1eeb46a969666dc88f
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 }