rsanchez
2014-10-23 bc2cedc83f6353259ea1364f98ce60bf11d7ecf4
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
package net.curisit.securis.services;
import java.security.Principal;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.annotation.security.RolesAllowed;
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.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.Utils;
import net.curisit.securis.DefaultExceptionHandler;
import net.curisit.securis.SeCurisException;
import net.curisit.securis.db.LicenseType;
import net.curisit.securis.db.Organization;
import net.curisit.securis.db.Pack;
import net.curisit.securis.db.PackMetadata;
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.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.google.inject.persist.Transactional;
/**
 * Pack resource, this service will provide methods to create, modify and delete
 * packs
 * 
 * @author roberto <roberto.sanchez@curisit.net>
 */
@Path("/pack")
public class PackResource {
    private static final Logger LOG = LogManager.getLogger(PackResource.class);
    @Inject
    TokenHelper tokenHelper;
    @Inject
    Provider<EntityManager> emProvider;
    public PackResource() {
    }
    /**
     * 
     * @return the server version in format majorVersion.minorVersion
     */
    @GET
    @Path("/")
    @Securable
    @Produces({
        MediaType.APPLICATION_JSON
    })
    public Response index(@Context BasicSecurityContext bsc) {
        LOG.info("Getting packs list ");
        EntityManager em = emProvider.get();
        TypedQuery<Pack> q;
        if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
            LOG.info("Getting all packs for user: " + bsc.getUserPrincipal());
            q = em.createNamedQuery("list-packs", Pack.class);
        } else {
            q = em.createNamedQuery("list-packs-by-orgs", Pack.class);
            if (bsc.getOrganizationsIds() == null) {
                Response.ok().build();
            }
            q.setParameter("list_ids", bsc.getOrganizationsIds());
        }
        List<Pack> list = q.getResultList();
        return Response.ok(list).build();
    }
    private Response generateErrorUnathorizedAccess(Pack pack, Principal user) {
        LOG.error("Pack with id {} not accesible by user {}", pack, user);
        return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack").build();
    }
    /**
     * 
     * @return the server version in format majorVersion.minorVersion
     */
    @GET
    @Path("/{packId}")
    @Securable
    @Produces({
        MediaType.APPLICATION_JSON
    })
    public Response get(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
        LOG.info("Getting pack data for id: {}: ", packId);
        if (packId == null || "".equals(packId)) {
            LOG.error("Pack ID is mandatory");
            return Response.status(Status.NOT_FOUND).build();
        }
        EntityManager em = emProvider.get();
        Pack pack = em.find(Pack.class, packId);
        if (pack == null) {
            LOG.error("Pack with id {} not found in DB", packId);
            return Response.status(Status.NOT_FOUND).build();
        }
        if (bsc.isUserInRole(BasicSecurityContext.ROL_ADVANCE)
                && (bsc.getOrganizationsIds() == null || !bsc.getOrganizationsIds().contains(pack.getOrgId()))) {
            return generateErrorUnathorizedAccess(pack, bsc.getUserPrincipal());
        }
        return Response.ok(pack).build();
    }
    @POST
    @Path("/")
    @Securable
    @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({
        MediaType.APPLICATION_JSON
    })
    @Transactional
    public Response create(Pack pack, @Context BasicSecurityContext bsc) {
        LOG.info("Creating new pack");
        EntityManager em = emProvider.get();
        try {
            setPackOrganization(pack, pack.getOrgId(), em);
        } catch (SeCurisException e) {
            return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
        }
        try {
            setPackLicenseType(pack, pack.getLicTypeId(), em);
        } catch (SeCurisException e) {
            return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
        }
        User user = em.find(User.class, bsc.getUserPrincipal().getName());
        pack.setCreatedBy(user);
        pack.setCreationTimestamp(new Date());
        em.persist(pack);
        Set<PackMetadata> newMD = pack.getMetadata(); 
        
        if (newMD != null) {
            for (PackMetadata md : newMD) {
                md.setPack(pack);
                em.persist(md);
            }
        }
        pack.setMetadata(newMD);
        return Response.ok(pack).build();
    }
    private void setPackLicenseType(Pack pack, Integer licTypeId, EntityManager em) throws SeCurisException {
        LicenseType lt = null;
        if (licTypeId != null) {
            lt = em.find(LicenseType.class, pack.getLicTypeId());
            if (lt == null) {
                LOG.error("Pack license type with id {} not found in DB", licTypeId);
                throw new SeCurisException("Pack license type not found with ID: " + licTypeId);
            }
        }
        pack.setLicenseType(lt);
    }
    @PUT
    @POST
    @Path("/{packId}")
    @Transactional
    @Securable
    @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({
        MediaType.APPLICATION_JSON
    })
    public Response modify(Pack pack, @PathParam("packId") Integer packId) {
        LOG.info("Modifying pack with id: {}", packId);
        EntityManager em = emProvider.get();
        Pack currentPack = em.find(Pack.class, packId);
        try {
            setPackOrganization(currentPack, pack.getOrgId(), em);
        } catch (SeCurisException e) {
            return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
        }
        try {
            setPackLicenseType(currentPack, pack.getLicTypeId(), em);
        } catch (SeCurisException e) {
            return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
        }
        currentPack.setLicensePreactivation(pack.isLicensePreactivation());
        currentPack.setCode(pack.getCode());
        currentPack.setComments(pack.getComments());
        currentPack.setNumLicenses(pack.getNumLicenses());
        em.persist(currentPack);
        Set<PackMetadata> newMD = pack.getMetadata(); 
        for (PackMetadata currentMd : currentPack.getMetadata()) {
            if (newMD == null || !newMD.contains(currentMd));
                em.remove(currentMd);
        }
        
        if (newMD != null) {
            for (PackMetadata md : newMD) {
                md.setPack(currentPack);
                em.persist(md);
            }
        }
        currentPack.setMetadata(newMD);
        return Response.ok(pack).build();
    }
    private void setPackOrganization(Pack currentPack, Integer orgId, EntityManager em) throws SeCurisException {
        Organization org = null;
        if (orgId != null) {
            org = em.find(Organization.class, orgId);
            if (org == null) {
                LOG.error("Organization pack with id {} not found in DB", orgId);
                throw new SeCurisException("Pack organization not found with ID: " + orgId);
            }
        }
        currentPack.setOrganization(org);
    }
    @DELETE
    @Path("/{packId}")
    @Securable
    @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
    @Transactional
    @Produces({
        MediaType.APPLICATION_JSON
    })
    public Response delete(@PathParam("packId") String packId) {
        LOG.info("Deleting pack with id: {}", packId);
        EntityManager em = emProvider.get();
        Pack org = em.find(Pack.class, Integer.parseInt(packId));
        if (org == null) {
            LOG.error("Pack with id {} can not be deleted, It was not found in DB", packId);
            return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Pack was not found, ID: " + packId)
                    .build();
        }
        em.remove(org);
        return Response.ok(Utils.createMap("success", true, "id", packId)).build();
    }
}