Joaquín Reñé
2025-10-07 146a0fb8b0e90f9196e569152f649baf60d6cc8f
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
/*
 * Copyright @ 2013 CurisTEC, S.A.S. All Rights Reserved.
 */
package net.curisit.securis.services;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import jakarta.persistence.TypedQuery;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.HeaderParam;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.curisit.integrity.commons.Utils;
import net.curisit.securis.DefaultExceptionHandler;
import net.curisit.securis.db.Application;
import net.curisit.securis.db.ApplicationMetadata;
import net.curisit.securis.db.User.Rol;
import net.curisit.securis.ioc.EnsureTransaction;
import net.curisit.securis.security.BasicSecurityContext;
import net.curisit.securis.security.Securable;
import net.curisit.securis.services.exception.SeCurisServiceException;
import net.curisit.securis.services.exception.SeCurisServiceException.ErrorCodes;
import net.curisit.securis.services.helpers.MetadataHelper;
import net.curisit.securis.utils.TokenHelper;
/**
 * ApplicationResource
 * <p>
 * REST endpoints to list, fetch, create, update and delete {@link Application}s.
 * Security:
 * <ul>
 *   <li>Listing filters by user's accessible application IDs unless ADMIN.</li>
 *   <li>Create/Modify/Delete restricted to ADMIN.</li>
 * </ul>
 * Side-effects:
 * <ul>
 *   <li>Manages {@link ApplicationMetadata} lifecycle on create/update.</li>
 *   <li>Propagates metadata changes via {@link MetadataHelper}.</li>
 * </ul>
 *
 * Author: roberto &lt;roberto.sanchez@curisit.net&gt;<br>
 * Last reviewed by JRA on Oct 5, 2025.
 */
@Path("/application")
public class ApplicationResource {
    @Inject TokenHelper tokenHelper;
    @Inject MetadataHelper metadataHelper;
    @Context EntityManager em;
    private static final Logger LOG = LogManager.getLogger(ApplicationResource.class);
    /**
     * ApplicationResource<p>
     * Constructor
     */
    public ApplicationResource() {}
    /**
     * index<p>
     * List applications visible to the current user.
     *
     * @param bsc security context
     * @return 200 with list (possibly empty) or 200 empty if user has no app scope
     */
    @GET
    @Path("/")
    @Produces({ MediaType.APPLICATION_JSON })
    @Securable
    public Response index(@Context BasicSecurityContext bsc) {
        LOG.info("Getting applications list ");
        em.clear();
        TypedQuery<Application> q;
        if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
            q = em.createNamedQuery("list-applications", Application.class);
        } else {
            if (bsc.getApplicationsIds() == null || bsc.getApplicationsIds().isEmpty()) {
                return Response.ok().build();
            }
            q = em.createNamedQuery("list-applications-by_ids", Application.class);
            q.setParameter("list_ids", bsc.getApplicationsIds());
        }
        List<Application> list = q.getResultList();
        return Response.ok(list).build();
    }
    /**
     * get<p>
     * Fetch a single application by ID.
     *
     * @param appid string ID
     * @return 200 + entity or 404 if not found
     * @throws SeCurisServiceException when ID is invalid or not found
     */
    @GET
    @Path("/{appid}")
    @Produces({ MediaType.APPLICATION_JSON })
    @Securable
    public Response get(@PathParam("appid") String appid) throws SeCurisServiceException {
        LOG.info("Getting application data for id: {}: ", appid);
        if (appid == null || "".equals(appid)) {
            LOG.error("Application ID is mandatory");
            return Response.status(Status.NOT_FOUND).build();
        }
        em.clear();
        Application app = null;
        try {
            LOG.info("READY to GET app: {}", appid);
            app = em.find(Application.class, Integer.parseInt(appid));
        } catch (Exception e) {
            LOG.info("ERROR GETTING app: {}", e);
        }
        if (app == null) {
            LOG.error("Application with id {} not found in DB", appid);
            throw new SeCurisServiceException(ErrorCodes.NOT_FOUND, "Application not found with ID: " + appid);
        }
        return Response.ok(app).build();
    }
    /**
     * create<p>
     * Create a new application with optional metadata entries.
     *
     * @param app application payload
     * @param token auth token (audited externally)
     * @return 200 + persisted entity
     */
    @POST
    @Path("/")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({ MediaType.APPLICATION_JSON })
    @EnsureTransaction
    @Securable(roles = Rol.ADMIN)
    @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
    public Response create(Application app, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
        LOG.info("Creating new application");
        app.setCreationTimestamp(new Date());
        em.persist(app);
        if (app.getApplicationMetadata() != null) {
            for (ApplicationMetadata md : app.getApplicationMetadata()) {
                md.setApplication(app);
                md.setCreationTimestamp(new Date());
                em.persist(md);
            }
        }
        LOG.info("Creating application ({}) with date: {}", app.getId(), app.getCreationTimestamp());
        return Response.ok(app).build();
    }
    /**
     * modify<p>
     * Update core fields and reconcile metadata set:
     * <ul>
     *   <li>Removes missing keys, merges existing, persists new.</li>
     *   <li>Propagates metadata if there were changes.</li>
     * </ul>
     *
     * @param appid path ID
     * @param app   new state
     */
    @PUT
    @POST
    @Path("/{appid}")
    @EnsureTransaction
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({ MediaType.APPLICATION_JSON })
    @Securable(roles = Rol.ADMIN)
    @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
    public Response modify(Application app, @PathParam("appid") String appid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
        LOG.info("Modifying application with id: {}", appid);
        Application currentapp = em.find(Application.class, Integer.parseInt(appid));
        if (currentapp == null) {
            LOG.error("Application with id {} not found in DB", appid);
            return Response.status(Status.NOT_FOUND)
                    .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid)
                    .build();
        }
        currentapp.setCode(app.getCode());
        currentapp.setName(app.getName());
        currentapp.setLicenseFilename(app.getLicenseFilename());
        currentapp.setDescription(app.getDescription());
        Set<ApplicationMetadata> newMD = app.getApplicationMetadata();
        Set<ApplicationMetadata> oldMD = currentapp.getApplicationMetadata();
        boolean metadataChanges = !metadataHelper.match(newMD, oldMD);
        if (metadataChanges) {
            Map<String, ApplicationMetadata> directOldMD = getMapMD(oldMD);
            Map<String, ApplicationMetadata> directNewMD = getMapMD(newMD);
            // Remove deleted MD
            for (ApplicationMetadata currentMd : oldMD) {
                if (newMD == null || !directNewMD.containsKey(currentMd.getKey())) {
                    em.remove(currentMd);
                }
            }
            // Merge or persist
            if (newMD != null) {
                for (ApplicationMetadata md : newMD) {
                    if (directOldMD.containsKey(md.getKey())) {
                        em.merge(md);
                    } else {
                        md.setApplication(currentapp);
                        if (md.getCreationTimestamp() == null) {
                            md.setCreationTimestamp(app.getCreationTimestamp());
                        }
                        em.persist(md);
                    }
                }
            }
            currentapp.setApplicationMetadata(app.getApplicationMetadata());
        }
        em.merge(currentapp);
        if (metadataChanges) {
            metadataHelper.propagateMetadata(em, currentapp);
        }
        return Response.ok(currentapp).build();
    }
    /**
     * getMapMD<p> 
     * Build a map from metadata key → entity for fast reconciliation. 
     * 
     * @param applicationMetadata
     * @return mapMD
     */
    private Map<String, ApplicationMetadata> getMapMD(Set<ApplicationMetadata> amd) {
        Map<String, ApplicationMetadata> map = new HashMap<>();
        if (amd != null) {
            for (ApplicationMetadata m : amd) {
                map.put(m.getKey(), m);
            }
        }
        return map;
    }
    /**
     * delete<p>
     * Delete an application by ID.
     * <p>Note: deletion is not allowed if there are dependent entities (enforced by DB/cascade).</p>
     * 
     * @param appId
     * @param request
     */
    @DELETE
    @Path("/{appid}")
    @EnsureTransaction
    @Produces({ MediaType.APPLICATION_JSON })
    @Securable(roles = Rol.ADMIN)
    @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
    public Response delete(@PathParam("appid") String appid, @Context HttpServletRequest request) {
        LOG.info("Deleting app with id: {}", appid);
        Application app = em.find(Application.class, Integer.parseInt(appid));
        if (app == null) {
            LOG.error("Application with id {} can not be deleted, It was not found in DB", appid);
            return Response.status(Status.NOT_FOUND)
                    .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid)
                    .build();
        }
        em.remove(app);
        return Response.ok(Utils.createMap("success", true, "id", appid)).build();
    }
}