Joaquín Reñé
2025-05-27 89b1c533d1b48b8b339b9c74a59c2ce73e6431af
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
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;
/**
 * Application resource, this service will provide methods to create, modify and
 * delete applications
 * 
 * @author roberto <roberto.sanchez@curisit.net>
 */
@Path("/application")
public class ApplicationResource {
   @Inject
   TokenHelper tokenHelper;
   @Inject
   MetadataHelper metadataHelper;
   @Context
   EntityManager em;
   private static final Logger LOG = LogManager.getLogger(ApplicationResource.class);
   public ApplicationResource() {
   }
   /**
    * 
    * @return the server version in format majorVersion.minorVersion
    */
   @GET
   @Path("/")
   @Produces({ MediaType.APPLICATION_JSON })
   @Securable
   public Response index(@Context BasicSecurityContext bsc) {
       LOG.info("Getting applications list ");
       // EntityManager em = emProvider.get();
       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();
   }
   /**
    * 
    * @return the server version in format majorVersion.minorVersion
    * @throws SeCurisServiceException
    */
   @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();
   }
   @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");
       // EntityManager em = emProvider.get();
       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();
   }
   @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);
       // EntityManager em = emProvider.get();
       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);
           for (ApplicationMetadata currentMd : oldMD) {
               if (newMD == null || !directNewMD.containsKey(currentMd.getKey())) {
                   em.remove(currentMd);
               }
           }
           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();
   }
   private Map<String, ApplicationMetadata> getMapMD(Set<ApplicationMetadata> amd) {
       Map<String, ApplicationMetadata> map = new HashMap<String, ApplicationMetadata>();
       if (amd != null) {
           for (ApplicationMetadata applicationMetadata : amd) {
               map.put(applicationMetadata.getKey(), applicationMetadata);
           }
       }
       return map;
   }
   @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);
       // EntityManager em = emProvider.get();
       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();
       }
       /*
        * if (app.getLicenseTypes() != null &&
        * !app.getLicenseTypes().isEmpty()) { throw new
        * SeCurisServiceException(ErrorCodes.NOT_FOUND,
        * "Application can not be deleted becasue has assigned one or more License types, ID: "
        * + appid); }
        */
       em.remove(app);
       return Response.ok(Utils.createMap("success", true, "id", appid)).build();
   }
}