Roberto Sánchez
2014-01-27 3a4f598d47254e07c62776324e775f39d595ff5f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package net.curisit.securis.services;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import net.curisit.integrity.commons.JsonUtils;
import net.curisit.integrity.commons.Utils;
import net.curisit.integrity.exception.CurisException;
import net.curisit.securis.DefaultExceptionHandler;
import net.curisit.securis.db.License;
import net.curisit.securis.db.LicenseHistory;
import net.curisit.securis.db.Pack;
import net.curisit.securis.db.User;
import net.curisit.securis.security.BasicSecurityContext;
import net.curisit.securis.security.Securable;
import net.curisit.securis.utils.TokenHelper;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.persist.Transactional;
/**
 * License resource, this service will provide methods to create, modify and delete licenses
 * 
 * @author roberto <roberto.sanchez@curisit.net>
 */
@Path("/license")
public class LicenseResource {
   private static final Logger log = LoggerFactory.getLogger(LicenseResource.class);
   @Inject
   TokenHelper tokenHelper;
   @Inject
   Provider<EntityManager> emProvider;
   public LicenseResource() {
   }
   /**
    * 
    * @return the server version in format majorVersion.minorVersion
    */
   @GET
   @Path("/")
   @Securable
   @Produces(
       { MediaType.APPLICATION_JSON })
   public Response index(@QueryParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
       log.info("Getting licenses list ");
       EntityManager em = emProvider.get();
       if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
           Pack pack = em.find(Pack.class, packId);
           if (pack == null)
               return Response.ok().build();
           if (!bsc.getOrganizationsIds().contains(pack.getOrganization().getId())) {
               log.error("Pack with id {} not accesible by user {}", pack, bsc.getUserPrincipal());
               return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack licenses").build();
           }
       }
       TypedQuery<License> q = em.createNamedQuery("list-licenses-by-pack", License.class);
       q.setParameter("packId", packId);
       List<License> list = q.getResultList();
       return Response.ok(list).build();
   }
   /**
    * 
    * @return the server version in format majorVersion.minorVersion
    */
   @GET
   @Path("/{licId}")
   @Securable
   @Produces(
       { MediaType.APPLICATION_JSON })
   public Response get(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) {
       log.info("Getting organization data for id: {}: ", licId);
       if (licId == null || licId.equals("")) {
           log.error("License ID is mandatory");
           return Response.status(Status.NOT_FOUND).build();
       }
       EntityManager em = emProvider.get();
       License lic = em.find(License.class, licId);
       if (lic == null) {
           log.error("License with id {} not found in DB", licId);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License not found for ID: " + licId).build();
       }
       if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
           if (!bsc.getOrganizationsIds().contains(lic.getPack().getOrganization().getId())) {
               log.error("License with id {} is not accesible by user {}", licId, bsc.getUserPrincipal());
               return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to license data").build();
           }
       }
       return Response.ok(lic).build();
   }
   /**
    * 
    * @return The license file, only of license is active
    */
   @GET
   @Path("/{licId}/download")
   @Securable
   @Produces(
       { MediaType.APPLICATION_OCTET_STREAM })
   public Response download(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) {
       log.info("Getting license data for id: {}: ", licId);
       if (licId == null || licId.equals("")) {
           log.error("License ID is mandatory");
           return Response.status(Status.NOT_FOUND).build();
       }
       EntityManager em = emProvider.get();
       License lic = em.find(License.class, licId);
       if (lic == null) {
           log.error("License with id {} not found in DB", licId);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License not found for ID: " + licId).build();
       }
       if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
           if (!bsc.getOrganizationsIds().contains(lic.getPack().getOrganization().getId())) {
               log.error("License with id {} is not accesible by user {}", licId, bsc.getUserPrincipal());
               return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to license data").build();
           }
       }
       if (lic.getLicenseData() == null) {
           log.error("License with id {} has not license file generated", licId, bsc.getUserPrincipal());
           return Response.status(Status.FORBIDDEN).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License has not contain data to generate license file").build();
       }
       if (lic.getStatus() != License.Status.ACTIVE) {
           log.error("License with id {} is not active, so It can not downloaded", licId, bsc.getUserPrincipal());
           return Response.status(Status.FORBIDDEN).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License is not active, so It can not be downloaded").build();
       }
       return Response.ok(lic.getLicenseData()).build();
   }
   @PUT
   @POST
   @Path("/{licId}/activate")
   @Securable
   @Transactional
   @Consumes(MediaType.APPLICATION_JSON)
   @Produces(
       { MediaType.APPLICATION_JSON })
   public Response activate(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) {
       log.info("Getting license data for id: {}: ", licId);
       if (licId == null || licId.equals("")) {
           log.error("License ID is mandatory");
           return Response.status(Status.NOT_FOUND).build();
       }
       EntityManager em = emProvider.get();
       License lic = em.find(License.class, licId);
       if (lic == null) {
           log.error("License with id {} not found in DB", licId);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License not found for ID: " + licId).build();
       }
       if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
           if (!bsc.getOrganizationsIds().contains(lic.getPack().getOrganization().getId())) {
               log.error("License with id {} is not accesible by user {}", licId, bsc.getUserPrincipal());
               return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to license data").build();
           }
       }
       User user = null;
       try {
           user = getUser(bsc.getUserPrincipal().getName(), em);
       } catch (CurisException ex) {
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Current user not found in DB: " + bsc.getUserPrincipal()).build();
       }
       lic.setStatus(License.Status.ACTIVE);
       lic.setModificationTimestamp(new Date());
       em.persist(lic);
       LicenseHistory lh = new LicenseHistory();
       lh.setLicense(lic);
       lh.setUser(user);
       lh.setTimestamp(new Date());
       lh.setAction(LicenseHistory.Actions.ACTIVATE);
       em.persist(lh);
       return Response.ok(lic).build();
   }
   @POST
   @Path("/")
   @Consumes(MediaType.APPLICATION_JSON)
   @Securable
   @Produces(
       { MediaType.APPLICATION_JSON })
   @Transactional
   public Response create(License lic, @Context BasicSecurityContext bsc) {
       log.info("Creating new license from create()");
       EntityManager em = emProvider.get();
       Pack pack = null;
       if (lic.getPackId() != null) {
           pack = em.find(Pack.class, lic.getPackId());
           if (pack == null) {
               log.error("License pack with id {} not found in DB", lic.getPackId());
               return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's pack not found with ID: " + lic.getPackId()).build();
           } else {
               if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
                   if (!bsc.getOrganizationsIds().contains(pack.getOrganization().getId())) {
                       log.error("License for pack with id {} can not be created by user {}", pack.getId(), bsc.getUserPrincipal());
                       return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized action on pack license").build();
                   }
               }
           }
       }
       User createdBy = null;
       try {
           createdBy = getUser(bsc.getUserPrincipal().getName(), em);
       } catch (CurisException ex) {
           String createdByUsername = lic.getCreatedById();
           log.error("License created by user with id {} not found in DB", createdByUsername);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's created by user not found with ID: " + createdByUsername).build();
       }
       // ODO: Manage status if request data is set
       lic.setCreatedBy(createdBy);
       lic.setStatus(License.Status.CREATED);
       lic.setCreationTimestamp(new Date());
       lic.setModificationTimestamp(lic.getCreationTimestamp());
       em.persist(lic);
       LicenseHistory lh = new LicenseHistory();
       lh.setLicense(lic);
       lh.setUser(createdBy);
       lh.setTimestamp(new Date());
       lh.setAction(LicenseHistory.Actions.CREATE);
       em.persist(lh);
       return Response.ok(lic).build();
   }
   @POST
   @Path("/")
   @Consumes(MediaType.MULTIPART_FORM_DATA)
   @Securable
   @Produces(
       { MediaType.APPLICATION_JSON })
   @Transactional
   public Response createWithFile(MultipartFormDataInput mpfdi, @Context BasicSecurityContext bsc) throws IOException {
       License lic = new License();
       lic.setCode(mpfdi.getFormDataPart("code", String.class, null));
       lic.setRequestData(mpfdi.getFormDataPart("request_data", String.class, null));
       lic.setPackId(mpfdi.getFormDataPart("pack_id", Integer.class, null));
       lic.setFullName(mpfdi.getFormDataPart("full_name", String.class, null));
       lic.setEmail(mpfdi.getFormDataPart("email", String.class, null));
       lic.setComments(mpfdi.getFormDataPart("comments", String.class, null));
       try {
           log.info("File content: {}", lic.getRequestData());
           log.info("License read from multipart: {}", JsonUtils.toJSON(lic));
       } catch (CurisException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       return create(lic, bsc);
   }
   private User getUser(String username, EntityManager em) throws CurisException {
       User user = null;
       if (username != null) {
           user = em.find(User.class, username);
           if (user == null) {
               throw new CurisException("User not found");
           }
       }
       return user;
   }
   @PUT
   @POST
   @Path("/{licId}")
   @Securable
   @Transactional
   @Consumes(MediaType.APPLICATION_JSON)
   @Produces(
       { MediaType.APPLICATION_JSON })
   public Response modify(License lic, @PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) {
       log.info("Modifying organization with id: {}", licId);
       EntityManager em = emProvider.get();
       // Pack pack = null;
       // if (lic.getPackId() != null) {
       // pack = em.find(Pack.class, lic.getPackId());
       // if (pack == null) {
       // log.error("License pack with id {} not found in DB", lic.getPackId());
       // return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's pack not found with ID: " + lic.getPackId()).build();
       // } else {
       // if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
       // if (!bsc.getOrganizationsIds().contains(pack.getOrganization().getId())) {
       // log.error("License for pack with id {} can not be modified by user {}", pack.getId(), bsc.getUserPrincipal());
       // return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized action on pack license").build();
       // }
       // }
       // }
       // }
       User createdBy = null;
       try {
           createdBy = getUser(lic.getCreatedById(), em);
       } catch (CurisException ex) {
           String createdByUsername = lic.getCreatedById();
           log.error("License created by user with id {} not found in DB", createdByUsername);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's created by user not found with ID: " + createdByUsername).build();
       }
       User canceledBy = null;
       try {
           canceledBy = getUser(lic.getCanceledById(), em);
       } catch (CurisException ex) {
           String canceledByUsername = lic.getCreatedById();
           log.error("License canceled by user with id {} not found in DB", canceledByUsername);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's canceled by user not found with ID: " + canceledByUsername).build();
       }
       License currentLicense = em.find(License.class, lic.getId());
       if (currentLicense == null) {
           log.error("License with id {} not found in DB", licId);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License not found for ID: " + licId).build();
       }
       if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
           if (!bsc.getOrganizationsIds().contains(lic.getPack().getOrganization().getId())) {
               log.error("License with id {} is not accesible by user {}", licId, bsc.getUserPrincipal());
               return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to license data").build();
           }
       }
       // TODO: set status based in current one and dates ? use custom actions ?
       currentLicense.setCreatedBy(createdBy);
       currentLicense.setCanceledBy(canceledBy);
       // currentLicense.setPack(pack);
       currentLicense.setCode(lic.getCode());
       currentLicense.setFullName(lic.getFullName());
       currentLicense.setEmail(lic.getEmail());
       currentLicense.setRequestData(lic.getRequestData());
       currentLicense.setModificationTimestamp(new Date());
       em.persist(currentLicense);
       return Response.ok(currentLicense).build();
   }
   @DELETE
   @Path("/{licId}")
   @Transactional
   @Securable
   @Produces(
       { MediaType.APPLICATION_JSON })
   public Response delete(@PathParam("licId") String licId, @Context BasicSecurityContext bsc) {
       log.info("Deleting license with id: {}", licId);
       EntityManager em = emProvider.get();
       License lic = em.find(License.class, Integer.parseInt(licId));
       if (lic == null) {
           log.error("License with id {} can not be deleted, It was not found in DB", licId);
           return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License was not found, ID: " + licId).build();
       }
       if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
           if (!bsc.getOrganizationsIds().contains(lic.getPack().getOrganization().getId())) {
               log.error("License with id {} is not accesible by user {}", licId, bsc.getUserPrincipal());
               return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to license data").build();
           }
       }
       if (lic.getStatus() != License.Status.CANCELED || lic.getStatus() != License.Status.CREATED) {
           log.error("License {} can not be deleted with status {}", lic.getCode(), lic.getStatus());
           return Response.status(Status.FORBIDDEN).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License can not be deleted in current status").build();
       }
       em.remove(lic);
       return Response.ok(Utils.createMap("success", true, "id", licId)).build();
   }
}