Roberto Sánchez
2014-09-19 8d5386be38db25a2a41c3bf6c876adee21ca26cc
#396 fix - Fixed more SonarQube issues
30 files modified
changed files
securis/src/main/java/net/curisit/securis/AuthFilter.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/MainApp.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/RestServicesApplication.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/dao/UserDao.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/Application.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/License.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/LicenseHistory.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/LicenseType.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/Organization.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/Pack.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/db/User.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/ioc/RequestsModule.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/ioc/SecurisModule.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/security/BasicSecurityContext.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/security/Securable.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/security/SecurityInterceptor.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/ApiResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/ApplicationResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/BasicServices.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/LicenseResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/LicenseServices.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/LicenseTypeResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/OrganizationResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/PackResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/UserResource.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/services/exception/SeCurisServiceException.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/utils/CacheTTL.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/utils/TokenHelper.java patch | view | blame | history
securis/src/patch/java/net/curisit/securis/LicenseGenerator.java patch | view | blame | history
securis/src/main/java/net/curisit/securis/AuthFilter.java
....@@ -18,72 +18,69 @@
1818
1919 import org.apache.logging.log4j.LogManager;
2020
21
-
2221 @Singleton
2322 @WebFilter(urlPatterns = "/*")
2423 public class AuthFilter implements Filter {
2524
26
- private static final Logger LOG = LogManager.getLogger(AuthFilter.class);
25
+ private static final Logger LOG = LogManager.getLogger(AuthFilter.class);
2726
28
- @Override
29
- public void init(FilterConfig fc) throws ServletException {
30
- }
27
+ @Override
28
+ public void init(FilterConfig fc) throws ServletException {}
3129
32
- @Override
33
- public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException {
34
- HttpServletRequest req = (HttpServletRequest) sr;
30
+ @Override
31
+ public void doFilter(ServletRequest sr, ServletResponse sr1, FilterChain fc) throws IOException, ServletException {
32
+ HttpServletRequest req = (HttpServletRequest) sr;
3533
36
- // System.out.println("filter: " + req.getRequestURI() + " user: " + sr.getParameter("user"));
37
- if (sr.getParameter("user") != null || req.getSession().getAttribute("user") != null) {
38
- String username = sr.getParameter("user");
39
- if (username == null)
40
- username = (String) req.getSession().getAttribute("user");
41
- String role = username.equals("advance") ? "advance" : "normal";
42
- // ResteasyProviderFactory.pushContext(User.class, new User(sr.getParameter("user")));
43
- LOG.info("Role for user: {} = {}", username, role);
44
- fc.doFilter(new UserRoleRequestWrapper(role, sr.getParameter("user"), req), sr1);
45
- } else {
46
- fc.doFilter(req, sr1);
47
- }
34
+ if (sr.getParameter("user") != null || req.getSession().getAttribute("user") != null) {
35
+ String username = sr.getParameter("user");
36
+ if (username == null) {
37
+ username = (String) req.getSession().getAttribute("user");
38
+ }
39
+ // TODO: role management is temporal
40
+ String role = "advance".equals(username) ? "advance" : "normal";
41
+ LOG.info("Role for user: {} = {}", username, role);
42
+ fc.doFilter(new UserRoleRequestWrapper(role, sr.getParameter("user"), req), sr1);
43
+ } else {
44
+ fc.doFilter(req, sr1);
45
+ }
4846
49
- }
47
+ }
5048
51
- @Override
52
- public void destroy() {
53
- }
49
+ @Override
50
+ public void destroy() {}
5451
55
- private class UserRoleRequestWrapper extends HttpServletRequestWrapper {
52
+ private class UserRoleRequestWrapper extends HttpServletRequestWrapper {
5653
57
- private String role;
58
- private String user;
54
+ private String role;
55
+ private String user;
5956
60
- public UserRoleRequestWrapper(String role, String user, HttpServletRequest request) {
61
- super(request);
62
- this.role = role;
63
- this.user = user;
64
- }
57
+ public UserRoleRequestWrapper(String role, String user, HttpServletRequest request) {
58
+ super(request);
59
+ this.role = role;
60
+ this.user = user;
61
+ }
6562
66
- @Override
67
- public boolean isUserInRole(String role) {
68
- LOG.info("isUserRole METHOD: {}, {}", role, this.role);
69
- if (this.role == null) {
70
- return super.isUserInRole(role);
71
- }
72
- return this.role.equals(role);
73
- }
63
+ @Override
64
+ public boolean isUserInRole(String role) {
65
+ LOG.info("isUserRole METHOD: {}, {}", role, this.role);
66
+ if (this.role == null) {
67
+ return super.isUserInRole(role);
68
+ }
69
+ return this.role.equals(role);
70
+ }
7471
75
- @Override
76
- public Principal getUserPrincipal() {
77
- if (this.user == null) {
78
- return super.getUserPrincipal();
79
- }
72
+ @Override
73
+ public Principal getUserPrincipal() {
74
+ if (this.user == null) {
75
+ return super.getUserPrincipal();
76
+ }
8077
81
- return new Principal() {
82
- @Override
83
- public String getName() {
84
- return user;
85
- }
86
- };
87
- }
88
- }
78
+ return new Principal() {
79
+ @Override
80
+ public String getName() {
81
+ return user;
82
+ }
83
+ };
84
+ }
85
+ }
8986 }
securis/src/main/java/net/curisit/securis/DefaultExceptionHandler.java
....@@ -17,34 +17,36 @@
1717
1818 @Provider
1919 public class DefaultExceptionHandler implements ExceptionMapper<Exception> {
20
- private static final Logger LOG = LogManager.getLogger(DefaultExceptionHandler.class);
20
+ private static final Logger LOG = LogManager.getLogger(DefaultExceptionHandler.class);
2121
22
- public static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR";
22
+ public static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR";
2323
24
- public DefaultExceptionHandler() {
25
- LOG.info("Creating DefaultExceptionHandler ");
26
- }
24
+ public DefaultExceptionHandler() {
25
+ LOG.info("Creating DefaultExceptionHandler ");
26
+ }
2727
28
- @Context
29
- HttpServletRequest request;
30
- @Context
31
- SecurityContext bsc;
28
+ @Context
29
+ HttpServletRequest request;
30
+ @Context
31
+ SecurityContext bsc;
3232
33
- @Override
34
- public Response toResponse(Exception e) {
35
- if (e instanceof ForbiddenException) {
36
- LOG.warn("Unauthorized access to {}, user: {}", request.getPathInfo(), bsc.getUserPrincipal());
37
- return Response.status(Status.UNAUTHORIZED).header(ERROR_MESSAGE_HEADER, "Unathorized access to the application").type(MediaType.APPLICATION_JSON).build();
38
- }
33
+ @Override
34
+ public Response toResponse(Exception e) {
35
+ if (e instanceof ForbiddenException) {
36
+ LOG.warn("Unauthorized access to {}, user: {}", request.getPathInfo(), bsc.getUserPrincipal());
37
+ return Response.status(Status.UNAUTHORIZED).header(ERROR_MESSAGE_HEADER, "Unathorized access to the application")
38
+ .type(MediaType.APPLICATION_JSON).build();
39
+ }
3940
40
- if (e instanceof SeCurisServiceException) {
41
- LOG.warn("SeCurisServiceException accessing to {}, user: {}", request.getPathInfo(), bsc.getUserPrincipal());
42
- return Response.status(Status.fromStatusCode(((SeCurisServiceException) e).getStatus())).header(ERROR_MESSAGE_HEADER, e.getMessage()).type(MediaType.APPLICATION_JSON).build();
43
- }
41
+ if (e instanceof SeCurisServiceException) {
42
+ LOG.warn("SeCurisServiceException accessing to {}, user: {}", request.getPathInfo(), bsc.getUserPrincipal());
43
+ return Response.status(Status.fromStatusCode(((SeCurisServiceException) e).getStatus())).header(ERROR_MESSAGE_HEADER, e.getMessage())
44
+ .type(MediaType.APPLICATION_JSON).build();
45
+ }
4446
45
- LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal());
46
- LOG.error("Request sent from {}, with User-Agent: {}", request.getRemoteHost(), request.getHeader("User-Agent"));
47
- LOG.error("Request url: " + request.getRequestURL(), e);
48
- return Response.serverError().header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString()).type(MediaType.APPLICATION_JSON).build();
49
- }
47
+ LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal());
48
+ LOG.error("Request sent from {}, with User-Agent: {}", request.getRemoteHost(), request.getHeader("User-Agent"));
49
+ LOG.error("Request url: " + request.getRequestURL(), e);
50
+ return Response.serverError().header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString()).type(MediaType.APPLICATION_JSON).build();
51
+ }
5052 }
securis/src/main/java/net/curisit/securis/MainApp.java
....@@ -32,76 +32,65 @@
3232
3333 public class MainApp {
3434
35
- private static final Logger LOG = LogManager.getLogger(MainApp.class);
35
+ private static final Logger LOG = LogManager.getLogger(MainApp.class);
3636
37
- private static Server server;
38
- private static Injector injector = null;
37
+ private static Server server;
38
+ private static Injector injector = null;
3939
40
- @Inject
41
- @Named("base-uri")
42
- private URI uri;
40
+ @Inject
41
+ @Named("base-uri")
42
+ private URI uri;
4343
44
- public static void main(String[] args) throws Exception {
45
- LOG.info("SeCuris init...");
44
+ public static void main(String[] args) throws Exception {
45
+ LOG.info("SeCuris init...");
4646
47
- SecurisModule securisModule = new SecurisModule();
48
- JpaPersistModule jpaPersistModule = new JpaPersistModule("localdb");
49
- Properties props = new Properties();
50
- props.put("javax.persistence.jdbc.password", securisModule.getPassword());
51
- props.put("javax.persistence.jdbc.url", securisModule.getUrl(securisModule.getAppDir()));
52
- LOG.info("BD Url: {} {}", securisModule.getUrl(securisModule.getAppDir()), securisModule.getPassword());
53
- jpaPersistModule.properties(props);
47
+ SecurisModule securisModule = new SecurisModule();
48
+ JpaPersistModule jpaPersistModule = new JpaPersistModule("localdb");
49
+ Properties props = new Properties();
50
+ props.put("javax.persistence.jdbc.password", securisModule.getPassword());
51
+ props.put("javax.persistence.jdbc.url", securisModule.getUrl(securisModule.getAppDir()));
52
+ LOG.info("BD Url: {} {}", securisModule.getUrl(securisModule.getAppDir()), securisModule.getPassword());
53
+ jpaPersistModule.properties(props);
5454
55
- injector = Guice.createInjector(securisModule, new RequestsModule(), jpaPersistModule);
56
- // injector.getInstance(JpaInitializer.class);
55
+ injector = Guice.createInjector(securisModule, new RequestsModule(), jpaPersistModule);
5756
58
- startServer(injector.getInstance(Key.get(URI.class, Names.named("base-uri"))));
59
- while (true) {
60
- Thread.currentThread().sleep(100);
61
- }
62
- }
57
+ startServer(injector.getInstance(Key.get(URI.class, Names.named("base-uri"))));
58
+ while (true) {
59
+ Thread.currentThread().sleep(100);
60
+ }
61
+ }
6362
64
- private static void startServer(URI uri) throws Exception {
65
- System.out.println("Starting jetty...");
63
+ private static void startServer(URI uri) throws Exception {
64
+ System.out.println("Starting jetty...");
6665
67
- server = new Server(9997);
68
- ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
69
- context.setContextPath("/");
70
- context.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));
66
+ server = new Server(9997);
67
+ ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
68
+ context.setContextPath("/");
69
+ context.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));
7170
72
- context.setInitParameter("resteasy.role.based.security", "true");
73
- context.setInitParameter("resteasy.providers", DefaultExceptionHandler.class.getName());
74
- // context.addFilter(new FilterHolder(injector.getInstance(AuthFilter.class)), "/*", null);
75
- context.addFilter(new FilterHolder(injector.getInstance(PersistFilter.class)), "/*", null);
76
- ServletHolder sh = new ServletHolder(HttpServletDispatcher.class);
77
- sh.setName("resteasy");
78
- context.addServlet(sh, "/*");
71
+ context.setInitParameter("resteasy.role.based.security", "true");
72
+ context.setInitParameter("resteasy.providers", DefaultExceptionHandler.class.getName());
73
+ context.addFilter(new FilterHolder(injector.getInstance(PersistFilter.class)), "/*", null);
74
+ ServletHolder sh = new ServletHolder(HttpServletDispatcher.class);
75
+ sh.setName("resteasy");
76
+ context.addServlet(sh, "/*");
7977
80
- ResourceHandler staticResources = new ResourceHandler();
81
- staticResources.setBaseResource(Resource.newResource(MainApp.class.getResource("/static").toURI()));
82
- staticResources.setWelcomeFiles(new String[]
83
- { "/main.html" });
84
- context.setHandler(staticResources);
78
+ ResourceHandler staticResources = new ResourceHandler();
79
+ staticResources.setBaseResource(Resource.newResource(MainApp.class.getResource("/static").toURI()));
80
+ staticResources.setWelcomeFiles(new String[] { "/main.html" });
81
+ context.setHandler(staticResources);
8582
86
- ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
87
- context.setErrorHandler(errorHandler);
88
- // errorHandler.addErrorPage(HttpResponseCodes.SC_FORBIDDEN, "/login");
89
- // errorHandler.addErrorPage(HttpResponseCodes.SC_NOT_FOUND, "/");
90
- // errorHandler.addErrorPage(javax.ws.rs.NotFoundException.class, "/");
91
- // errorHandler.addErrorPage(javax.ws.rs.ForbiddenException.class, "/");
92
- // errorHandler.addErrorPage(javax.ws.rs.ForbiddenException.class.getCanonicalName(), "/");
93
- // errorHandler.addErrorPage(ErrorPageErrorHandler.GLOBAL_ERROR_PAGE, "/");
94
- LOG.info("Error Handlers: " + context.getErrorHandler());
95
- ContextHandlerCollection contexts = new ContextHandlerCollection();
83
+ ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
84
+ context.setErrorHandler(errorHandler);
85
+ LOG.info("Error Handlers: " + context.getErrorHandler());
86
+ ContextHandlerCollection contexts = new ContextHandlerCollection();
9687
97
- contexts.setHandlers(new Handler[]
98
- { staticResources, context });
99
- // server.setHandler(contexts);
88
+ contexts.setHandlers(new Handler[] { staticResources, context });
10089
101
- server.setHandler(context);
102
- server.start();
103
- server.join();
104
- LOG.info("Started server in: http://127.0.0.1:9997/");
105
- }
90
+ server.setHandler(context);
91
+ server.start();
92
+ server.join();
93
+ LOG.info("Started server in: http://127.0.0.1:9997/");
94
+ }
10695
10796 }
securis/src/main/java/net/curisit/securis/RestServicesApplication.java
....@@ -13,16 +13,16 @@
1313
1414 public class RestServicesApplication extends Application {
1515
16
- private static final Logger LOG = LogManager.getLogger(RestServicesApplication.class);
16
+ private static final Logger LOG = LogManager.getLogger(RestServicesApplication.class);
1717
18
- @Override
19
- public Set<Class<?>> getClasses() {
20
- Set<Class<?>> classes = new HashSet<>();
21
- classes.add(LicenseServices.class);
22
- classes.add(BasicServices.class);
18
+ @Override
19
+ public Set<Class<?>> getClasses() {
20
+ Set<Class<?>> classes = new HashSet<>();
21
+ classes.add(LicenseServices.class);
22
+ classes.add(BasicServices.class);
2323
24
- LOG.info("Returnes classes for services: {}", classes);
25
- return classes;
26
- }
24
+ LOG.info("Returnes classes for services: {}", classes);
25
+ return classes;
26
+ }
2727
2828 }
securis/src/main/java/net/curisit/securis/dao/UserDao.java
....@@ -14,27 +14,26 @@
1414 @Singleton
1515 public class UserDao {
1616
17
- @Inject
18
- public UserDao() {
19
- }
17
+ @Inject
18
+ public UserDao() {}
2019
21
- @Inject
22
- Provider<EntityManager> emProvider;
20
+ @Inject
21
+ Provider<EntityManager> emProvider;
2322
24
- @com.google.inject.persist.Transactional
25
- public User test(String username) {
26
- EntityManager em = emProvider.get();
27
- User user = new User();
28
- user.setUsername(username);
29
- user.setFirstName("Rob");
30
- user.setPassword(Utils.sha256("rob"));
31
- user.setLang("en");
32
- user.setCreationTimestamp(new Date());
33
- user.setRoles(Arrays.asList(User.Rol.ADMIN, User.Rol.ADVANCE));
34
- user.setLastName("Sánchez");
35
- em.persist(user);
36
- User u2 = em.find(User.class, username);
37
- return u2;
38
- }
23
+ @com.google.inject.persist.Transactional
24
+ public User test(String username) {
25
+ EntityManager em = emProvider.get();
26
+ User user = new User();
27
+ user.setUsername(username);
28
+ user.setFirstName("Rob");
29
+ user.setPassword(Utils.sha256("rob"));
30
+ user.setLang("en");
31
+ user.setCreationTimestamp(new Date());
32
+ user.setRoles(Arrays.asList(User.Rol.ADMIN, User.Rol.ADVANCE));
33
+ user.setLastName("Sánchez");
34
+ em.persist(user);
35
+ User u2 = em.find(User.class, username);
36
+ return u2;
37
+ }
3938
4039 }
securis/src/main/java/net/curisit/securis/db/Application.java
....@@ -26,65 +26,65 @@
2626 @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
2727 @Entity
2828 @Table(name = "application")
29
-@NamedQueries(
30
- { @NamedQuery(name = "list-applications", query = "SELECT a FROM Application a") })
29
+@NamedQueries({ @NamedQuery(name = "list-applications", query = "SELECT a FROM Application a") })
3130 public class Application implements Serializable {
3231
33
- private static final long serialVersionUID = 1L;
32
+ private static final long serialVersionUID = 1L;
3433
35
- @Id
36
- @GeneratedValue
37
- private int id;
34
+ @Id
35
+ @GeneratedValue
36
+ private int id;
3837
39
- private String name;
40
- private String description;
38
+ private String name;
39
+ private String description;
4140
42
- @Column(name = "creation_timestamp")
43
- private Date creationTimestamp;
41
+ @Column(name = "creation_timestamp")
42
+ private Date creationTimestamp;
4443
45
- @JsonIgnore
46
- // We don't include the referenced entities to limit the size of each row at the listing
47
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "application")
48
- private Set<LicenseType> licenseTypes;
44
+ @JsonIgnore
45
+ // We don't include the referenced entities to limit the size of each row at
46
+ // the listing
47
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "application")
48
+ private Set<LicenseType> licenseTypes;
4949
50
- public int getId() {
51
- return id;
52
- }
50
+ public int getId() {
51
+ return id;
52
+ }
5353
54
- public void setId(int id) {
55
- this.id = id;
56
- }
54
+ public void setId(int id) {
55
+ this.id = id;
56
+ }
5757
58
- public String getName() {
59
- return name;
60
- }
58
+ public String getName() {
59
+ return name;
60
+ }
6161
62
- public void setName(String name) {
63
- this.name = name;
64
- }
62
+ public void setName(String name) {
63
+ this.name = name;
64
+ }
6565
66
- public String getDescription() {
67
- return description;
68
- }
66
+ public String getDescription() {
67
+ return description;
68
+ }
6969
70
- public void setDescription(String description) {
71
- this.description = description;
72
- }
70
+ public void setDescription(String description) {
71
+ this.description = description;
72
+ }
7373
74
- public Date getCreationTimestamp() {
75
- return creationTimestamp;
76
- }
74
+ public Date getCreationTimestamp() {
75
+ return creationTimestamp;
76
+ }
7777
78
- public void setCreationTimestamp(Date creationTimestamp) {
79
- this.creationTimestamp = creationTimestamp;
80
- }
78
+ public void setCreationTimestamp(Date creationTimestamp) {
79
+ this.creationTimestamp = creationTimestamp;
80
+ }
8181
82
- public Set<LicenseType> getLicenseTypes() {
83
- return licenseTypes;
84
- }
82
+ public Set<LicenseType> getLicenseTypes() {
83
+ return licenseTypes;
84
+ }
8585
86
- public void setLicenseTypes(Set<LicenseType> licenseTypes) {
87
- this.licenseTypes = licenseTypes;
88
- }
86
+ public void setLicenseTypes(Set<LicenseType> licenseTypes) {
87
+ this.licenseTypes = licenseTypes;
88
+ }
8989
9090 }
securis/src/main/java/net/curisit/securis/db/License.java
....@@ -35,284 +35,284 @@
3535 @Entity
3636 @Table(name = "license")
3737 @JsonIgnoreProperties(ignoreUnknown = true)
38
-@NamedQueries(
39
- { @NamedQuery(name = "list-licenses-by-pack", query = "SELECT l FROM License l where l.pack.id = :packId") })
38
+@NamedQueries({ @NamedQuery(name = "list-licenses-by-pack", query = "SELECT l FROM License l where l.pack.id = :packId") })
4039 public class License implements Serializable {
4140
42
- private static final long serialVersionUID = 1L;
41
+ private static final long serialVersionUID = 1L;
4342
44
- @Id
45
- @GeneratedValue
46
- private int id;
43
+ @Id
44
+ @GeneratedValue
45
+ private int id;
4746
48
- private String code;
47
+ private String code;
4948
50
- @JsonIgnore
51
- @ManyToOne
52
- @JoinColumn(name = "pack_id")
53
- private Pack pack;
49
+ @JsonIgnore
50
+ @ManyToOne
51
+ @JoinColumn(name = "pack_id")
52
+ private Pack pack;
5453
55
- @JsonIgnore
56
- @ManyToOne
57
- @JoinColumn(name = "created_by")
58
- private User createdBy;
54
+ @JsonIgnore
55
+ @ManyToOne
56
+ @JoinColumn(name = "created_by")
57
+ private User createdBy;
5958
60
- @JsonIgnore
61
- @ManyToOne
62
- @JoinColumn(name = "canceled_by")
63
- private User canceledBy;
59
+ @JsonIgnore
60
+ @ManyToOne
61
+ @JoinColumn(name = "canceled_by")
62
+ private User canceledBy;
6463
65
- private int status;
64
+ private int status;
6665
67
- @Column(name = "full_name")
68
- @JsonProperty("full_name")
69
- private String fullName;
66
+ @Column(name = "full_name")
67
+ @JsonProperty("full_name")
68
+ private String fullName;
7069
71
- private String email;
70
+ private String email;
7271
73
- @Column(name = "request_data")
74
- @JsonProperty("request_data")
75
- private String requestData;
72
+ @Column(name = "request_data")
73
+ @JsonProperty("request_data")
74
+ private String requestData;
7675
77
- @Column(name = "license_data")
78
- @JsonProperty("license_data")
79
- private String licenseData;
76
+ @Column(name = "license_data")
77
+ @JsonProperty("license_data")
78
+ private String licenseData;
8079
81
- @Column(name = "creation_timestamp")
82
- private Date creationTimestamp;
80
+ @Column(name = "creation_timestamp")
81
+ private Date creationTimestamp;
8382
84
- @Column(name = "modification_timestamp")
85
- private Date modificationTimestamp;
83
+ @Column(name = "modification_timestamp")
84
+ private Date modificationTimestamp;
8685
87
- @Column(name = "last_access_timestamp")
88
- private Date lastAccessTimestamp;
86
+ @Column(name = "last_access_timestamp")
87
+ private Date lastAccessTimestamp;
8988
90
- @Column(name = "expiration_date")
91
- private Date expirationDate;
89
+ @Column(name = "expiration_date")
90
+ private Date expirationDate;
9291
93
- private String comments;
92
+ private String comments;
9493
95
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "license")
96
- private List<LicenseHistory> history;
94
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "license")
95
+ private List<LicenseHistory> history;
9796
98
- public int getId() {
99
- return id;
100
- }
97
+ public int getId() {
98
+ return id;
99
+ }
101100
102
- public String getCode() {
103
- return code;
104
- }
101
+ public String getCode() {
102
+ return code;
103
+ }
105104
106
- public void setCode(String code) {
107
- this.code = code;
108
- }
105
+ public void setCode(String code) {
106
+ this.code = code;
107
+ }
109108
110
- public Date getCreationTimestamp() {
111
- return creationTimestamp;
112
- }
109
+ public Date getCreationTimestamp() {
110
+ return creationTimestamp;
111
+ }
113112
114
- public void setCreationTimestamp(Date creationTimestamp) {
115
- this.creationTimestamp = creationTimestamp;
116
- }
113
+ public void setCreationTimestamp(Date creationTimestamp) {
114
+ this.creationTimestamp = creationTimestamp;
115
+ }
117116
118
- public User getCreatedBy() {
119
- return createdBy;
120
- }
117
+ public User getCreatedBy() {
118
+ return createdBy;
119
+ }
121120
122
- public void setCreatedBy(User createdBy) {
123
- this.createdBy = createdBy;
124
- }
121
+ public void setCreatedBy(User createdBy) {
122
+ this.createdBy = createdBy;
123
+ }
125124
126
- public Pack getPack() {
127
- return pack;
128
- }
125
+ public Pack getPack() {
126
+ return pack;
127
+ }
129128
130
- public void setPack(Pack pack) {
131
- this.pack = pack;
132
- }
129
+ public void setPack(Pack pack) {
130
+ this.pack = pack;
131
+ }
133132
134
- @JsonProperty("created_by_id")
135
- public String getCreatedById() {
136
- return createdBy == null ? null : createdBy.getUsername();
137
- }
133
+ @JsonProperty("created_by_id")
134
+ public String getCreatedById() {
135
+ return createdBy == null ? null : createdBy.getUsername();
136
+ }
138137
139
- @JsonProperty("created_by_id")
140
- public void setCreatedById(String username) {
141
- if (username == null) {
142
- createdBy = null;
143
- } else {
144
- createdBy = new User();
145
- createdBy.setUsername(username);
146
- }
147
- }
138
+ @JsonProperty("created_by_id")
139
+ public void setCreatedById(String username) {
140
+ if (username == null) {
141
+ createdBy = null;
142
+ } else {
143
+ createdBy = new User();
144
+ createdBy.setUsername(username);
145
+ }
146
+ }
148147
149
- @JsonProperty("canceled_by_id")
150
- public String getCanceledById() {
151
- return canceledBy == null ? null : canceledBy.getUsername();
152
- }
148
+ @JsonProperty("canceled_by_id")
149
+ public String getCanceledById() {
150
+ return canceledBy == null ? null : canceledBy.getUsername();
151
+ }
153152
154
- @JsonProperty("canceled_by_id")
155
- public void setCanceledById(String username) {
156
- if (username == null) {
157
- canceledBy = null;
158
- } else {
159
- canceledBy = new User();
160
- canceledBy.setUsername(username);
161
- }
162
- }
153
+ @JsonProperty("canceled_by_id")
154
+ public void setCanceledById(String username) {
155
+ if (username == null) {
156
+ canceledBy = null;
157
+ } else {
158
+ canceledBy = new User();
159
+ canceledBy.setUsername(username);
160
+ }
161
+ }
163162
164
- @JsonProperty("pack_code")
165
- public String getPackCode() {
166
- return pack == null ? null : pack.getCode();
167
- }
163
+ @JsonProperty("pack_code")
164
+ public String getPackCode() {
165
+ return pack == null ? null : pack.getCode();
166
+ }
168167
169
- @JsonProperty("pack_id")
170
- public Integer getPackId() {
171
- return pack == null ? null : pack.getId();
172
- }
168
+ @JsonProperty("pack_id")
169
+ public Integer getPackId() {
170
+ return pack == null ? null : pack.getId();
171
+ }
173172
174
- @JsonProperty("pack_id")
175
- public void setPackId(Integer idPack) {
176
- if (idPack == null) {
177
- pack = null;
178
- } else {
179
- pack = new Pack();
180
- pack.setId(idPack);
181
- }
182
- }
173
+ @JsonProperty("pack_id")
174
+ public void setPackId(Integer idPack) {
175
+ if (idPack == null) {
176
+ pack = null;
177
+ } else {
178
+ pack = new Pack();
179
+ pack.setId(idPack);
180
+ }
181
+ }
183182
184
- public int getStatus() {
185
- return status;
186
- }
183
+ public int getStatus() {
184
+ return status;
185
+ }
187186
188
- public void setStatus(int status) {
189
- this.status = status;
190
- }
187
+ public void setStatus(int status) {
188
+ this.status = status;
189
+ }
191190
192
- public Date getModificationTimestamp() {
193
- return modificationTimestamp;
194
- }
191
+ public Date getModificationTimestamp() {
192
+ return modificationTimestamp;
193
+ }
195194
196
- public void setModificationTimestamp(Date modificationTimestamp) {
197
- this.modificationTimestamp = modificationTimestamp;
198
- }
195
+ public void setModificationTimestamp(Date modificationTimestamp) {
196
+ this.modificationTimestamp = modificationTimestamp;
197
+ }
199198
200
- public String getFullName() {
201
- return fullName;
202
- }
199
+ public String getFullName() {
200
+ return fullName;
201
+ }
203202
204
- public void setFullName(String fullName) {
205
- this.fullName = fullName;
206
- }
203
+ public void setFullName(String fullName) {
204
+ this.fullName = fullName;
205
+ }
207206
208
- public String getEmail() {
209
- return email;
210
- }
207
+ public String getEmail() {
208
+ return email;
209
+ }
211210
212
- public void setEmail(String email) {
213
- this.email = email;
214
- }
211
+ public void setEmail(String email) {
212
+ this.email = email;
213
+ }
215214
216
- public void setId(int id) {
217
- this.id = id;
218
- }
215
+ public void setId(int id) {
216
+ this.id = id;
217
+ }
219218
220
- public User getCanceledBy() {
221
- return canceledBy;
222
- }
219
+ public User getCanceledBy() {
220
+ return canceledBy;
221
+ }
223222
224
- public void setCanceledBy(User canceledBy) {
225
- this.canceledBy = canceledBy;
226
- }
223
+ public void setCanceledBy(User canceledBy) {
224
+ this.canceledBy = canceledBy;
225
+ }
227226
228
- public Date getLastAccessTimestamp() {
229
- return lastAccessTimestamp;
230
- }
227
+ public Date getLastAccessTimestamp() {
228
+ return lastAccessTimestamp;
229
+ }
231230
232
- public void setLastAccessTimestamp(Date lastAccessTimestamp) {
233
- this.lastAccessTimestamp = lastAccessTimestamp;
234
- }
231
+ public void setLastAccessTimestamp(Date lastAccessTimestamp) {
232
+ this.lastAccessTimestamp = lastAccessTimestamp;
233
+ }
235234
236
- public String getRequestData() {
237
- return requestData;
238
- }
235
+ public String getRequestData() {
236
+ return requestData;
237
+ }
239238
240
- public void setRequestData(String requestData) {
241
- this.requestData = requestData;
242
- }
239
+ public void setRequestData(String requestData) {
240
+ this.requestData = requestData;
241
+ }
243242
244
- public String getLicenseData() {
245
- return licenseData;
246
- }
243
+ public String getLicenseData() {
244
+ return licenseData;
245
+ }
247246
248
- public void setLicenseData(String licenseData) {
249
- this.licenseData = licenseData;
250
- }
247
+ public void setLicenseData(String licenseData) {
248
+ this.licenseData = licenseData;
249
+ }
251250
252
- public String getComments() {
253
- return comments;
254
- }
251
+ public String getComments() {
252
+ return comments;
253
+ }
255254
256
- public void setComments(String comments) {
257
- this.comments = comments;
258
- }
255
+ public void setComments(String comments) {
256
+ this.comments = comments;
257
+ }
259258
260
- public List<LicenseHistory> getHistory() {
261
- return history;
262
- }
259
+ public List<LicenseHistory> getHistory() {
260
+ return history;
261
+ }
263262
264
- public void setHistory(List<LicenseHistory> history) {
265
- this.history = history;
266
- }
263
+ public void setHistory(List<LicenseHistory> history) {
264
+ this.history = history;
265
+ }
267266
268
- public Date getExpirationDate() {
269
- return expirationDate;
270
- }
267
+ public Date getExpirationDate() {
268
+ return expirationDate;
269
+ }
271270
272
- public void setExpirationDate(Date expirationDate) {
273
- this.expirationDate = expirationDate;
274
- }
271
+ public void setExpirationDate(Date expirationDate) {
272
+ this.expirationDate = expirationDate;
273
+ }
275274
276
- public static class Action {
277
- public static final int CREATE = 1;
278
- public static final int REQUEST = 2;
279
- public static final int ACTIVATION = 3;
280
- public static final int SEND = 4;
281
- public static final int DOWNLOAD = 5;
282
- public static final int CANCEL = 6;
283
- public static final int DELETE = 7;
284
- }
275
+ public static class Action {
276
+ public static final int CREATE = 1;
277
+ public static final int REQUEST = 2;
278
+ public static final int ACTIVATION = 3;
279
+ public static final int SEND = 4;
280
+ public static final int DOWNLOAD = 5;
281
+ public static final int CANCEL = 6;
282
+ public static final int DELETE = 7;
283
+ }
285284
286
- public static class Status {
287
- public static final int CREATED = 1;
288
- public static final int REQUESTED = 2;
289
- public static final int PREACTIVE = 3;
290
- public static final int ACTIVE = 4;
291
- public static final int EXPIRED = 5;
292
- public static final int CANCELED = 6;
293
- public static final int DELETED = 7;
285
+ public static class Status {
286
+ public static final int CREATED = 1;
287
+ public static final int REQUESTED = 2;
288
+ public static final int PREACTIVE = 3;
289
+ public static final int ACTIVE = 4;
290
+ public static final int EXPIRED = 5;
291
+ public static final int CANCELED = 6;
292
+ public static final int DELETED = 7;
294293
295
- private static final Map<Integer, List<Integer>> transitions = Utils.createMap( //
296
- Action.REQUEST, Arrays.asList(CREATED, REQUESTED), //
297
- Action.ACTIVATION, Arrays.asList(REQUESTED, PREACTIVE, EXPIRED), //
298
- Action.SEND, Arrays.asList(ACTIVE, PREACTIVE), //
299
- Action.DOWNLOAD, Arrays.asList(ACTIVE, PREACTIVE), //
300
- Action.CANCEL, Arrays.asList(ACTIVE, PREACTIVE, REQUESTED, EXPIRED), //
301
- Action.DELETE, Arrays.asList(CANCELED, CREATED) //
294
+ private static final Map<Integer, List<Integer>> transitions = Utils.createMap( //
295
+ Action.REQUEST, Arrays.asList(CREATED, REQUESTED), //
296
+ Action.ACTIVATION, Arrays.asList(REQUESTED, PREACTIVE, EXPIRED), //
297
+ Action.SEND, Arrays.asList(ACTIVE, PREACTIVE), //
298
+ Action.DOWNLOAD, Arrays.asList(ACTIVE, PREACTIVE), //
299
+ Action.CANCEL, Arrays.asList(ACTIVE, PREACTIVE, REQUESTED, EXPIRED), //
300
+ Action.DELETE, Arrays.asList(CANCELED, CREATED) //
302301
303
- );
302
+ );
304303
305
- /**
306
- * It checks if a given action is valid for the License, passing the action and the current license status
307
- *
308
- * @param oldStatus
309
- * @param newStatus
310
- * @return
311
- */
312
- public static boolean isActionValid(Integer action, Integer currentStatus) {
313
- List<Integer> validStatuses = transitions.get(currentStatus);
304
+ /**
305
+ * It checks if a given action is valid for the License, passing the
306
+ * action and the current license status
307
+ *
308
+ * @param oldStatus
309
+ * @param newStatus
310
+ * @return
311
+ */
312
+ public static boolean isActionValid(Integer action, Integer currentStatus) {
313
+ List<Integer> validStatuses = transitions.get(currentStatus);
314314
315
- return validStatuses != null && validStatuses.contains(currentStatus);
316
- }
317
- }
315
+ return validStatuses != null && validStatuses.contains(currentStatus);
316
+ }
317
+ }
318318 }
securis/src/main/java/net/curisit/securis/db/LicenseHistory.java
....@@ -27,91 +27,90 @@
2727 @Entity
2828 @Table(name = "license_history")
2929 @JsonIgnoreProperties(ignoreUnknown = true)
30
-@NamedQueries(
31
- { @NamedQuery(name = "list-license-history", query = "SELECT lh FROM LicenseHistory lh where lh.license.id = :licId") })
30
+@NamedQueries({ @NamedQuery(name = "list-license-history", query = "SELECT lh FROM LicenseHistory lh where lh.license.id = :licId") })
3231 public class LicenseHistory implements Serializable {
3332
34
- private static final long serialVersionUID = 1L;
33
+ private static final long serialVersionUID = 1L;
3534
36
- @Id
37
- @GeneratedValue
38
- private int id;
35
+ @Id
36
+ @GeneratedValue
37
+ private int id;
3938
40
- @JsonIgnore
41
- @ManyToOne
42
- @JoinColumn(name = "license_id")
43
- private License license;
39
+ @JsonIgnore
40
+ @ManyToOne
41
+ @JoinColumn(name = "license_id")
42
+ private License license;
4443
45
- @JsonIgnore
46
- @ManyToOne
47
- @JoinColumn(name = "username")
48
- private User user;
44
+ @JsonIgnore
45
+ @ManyToOne
46
+ @JoinColumn(name = "username")
47
+ private User user;
4948
50
- private String action;
51
- private String comments;
49
+ private String action;
50
+ private String comments;
5251
53
- private Date timestamp;
52
+ private Date timestamp;
5453
55
- public int getId() {
56
- return id;
57
- }
54
+ public int getId() {
55
+ return id;
56
+ }
5857
59
- public License getLicense() {
60
- return license;
61
- }
58
+ public License getLicense() {
59
+ return license;
60
+ }
6261
63
- public void setLicense(License license) {
64
- this.license = license;
65
- }
62
+ public void setLicense(License license) {
63
+ this.license = license;
64
+ }
6665
67
- public User getUser() {
68
- return user;
69
- }
66
+ public User getUser() {
67
+ return user;
68
+ }
7069
71
- @JsonProperty("username")
72
- public String getUsername() {
73
- return user == null ? null : user.getUsername();
74
- }
70
+ @JsonProperty("username")
71
+ public String getUsername() {
72
+ return user == null ? null : user.getUsername();
73
+ }
7574
76
- public void setUser(User user) {
77
- this.user = user;
78
- }
75
+ public void setUser(User user) {
76
+ this.user = user;
77
+ }
7978
80
- public String getAction() {
81
- return action;
82
- }
79
+ public String getAction() {
80
+ return action;
81
+ }
8382
84
- public void setAction(String action) {
85
- this.action = action;
86
- }
83
+ public void setAction(String action) {
84
+ this.action = action;
85
+ }
8786
88
- public String getComments() {
89
- return comments;
90
- }
87
+ public String getComments() {
88
+ return comments;
89
+ }
9190
92
- public void setComments(String comments) {
93
- this.comments = comments;
94
- }
91
+ public void setComments(String comments) {
92
+ this.comments = comments;
93
+ }
9594
96
- public Date getTimestamp() {
97
- return timestamp;
98
- }
95
+ public Date getTimestamp() {
96
+ return timestamp;
97
+ }
9998
100
- public void setTimestamp(Date timestamp) {
101
- this.timestamp = timestamp;
102
- }
99
+ public void setTimestamp(Date timestamp) {
100
+ this.timestamp = timestamp;
101
+ }
103102
104
- public void setId(int id) {
105
- this.id = id;
106
- }
103
+ public void setId(int id) {
104
+ this.id = id;
105
+ }
107106
108
- public static class Actions {
109
- public static final String CREATE = "creation";
110
- public static final String ADD_REQUEST = "request";
111
- public static final String SEND = "send";
112
- public static final String MODIFY = "modify";
113
- public static final String ACTIVATE = "activate";
114
- public static final String CANCEL = "cancel";
115
- public static final String DELETE = "delete";
116
- }
107
+ public static class Actions {
108
+ public static final String CREATE = "creation";
109
+ public static final String ADD_REQUEST = "request";
110
+ public static final String SEND = "send";
111
+ public static final String MODIFY = "modify";
112
+ public static final String ACTIVATE = "activate";
113
+ public static final String CANCEL = "cancel";
114
+ public static final String DELETE = "delete";
115
+ }
117116 }
securis/src/main/java/net/curisit/securis/db/LicenseType.java
....@@ -30,93 +30,92 @@
3030 @JsonIgnoreProperties(ignoreUnknown = true)
3131 @Entity
3232 @Table(name = "license_type")
33
-@NamedQueries(
34
- { @NamedQuery(name = "list-license_types", query = "SELECT lt FROM LicenseType lt") })
33
+@NamedQueries({ @NamedQuery(name = "list-license_types", query = "SELECT lt FROM LicenseType lt") })
3534 public class LicenseType implements Serializable {
3635
37
- private static final Logger LOG = LogManager.getLogger(LicenseType.class);
38
- private static final long serialVersionUID = 1L;
36
+ private static final Logger LOG = LogManager.getLogger(LicenseType.class);
37
+ private static final long serialVersionUID = 1L;
3938
40
- @Id
41
- @GeneratedValue
42
- private int id;
39
+ @Id
40
+ @GeneratedValue
41
+ private int id;
4342
44
- private String code;
45
- private String name;
46
- private String description;
43
+ private String code;
44
+ private String name;
45
+ private String description;
4746
48
- @Column(name = "creation_timestamp")
49
- private Date creationTimestamp;
47
+ @Column(name = "creation_timestamp")
48
+ private Date creationTimestamp;
5049
51
- @JsonIgnore
52
- @ManyToOne
53
- @JoinColumn(name = "application_id")
54
- private Application application;
50
+ @JsonIgnore
51
+ @ManyToOne
52
+ @JoinColumn(name = "application_id")
53
+ private Application application;
5554
56
- public int getId() {
57
- return id;
58
- }
55
+ public int getId() {
56
+ return id;
57
+ }
5958
60
- public void setId(Integer id) {
61
- this.id = id;
62
- }
59
+ public void setId(Integer id) {
60
+ this.id = id;
61
+ }
6362
64
- public String getName() {
65
- return name;
66
- }
63
+ public String getName() {
64
+ return name;
65
+ }
6766
68
- public void setName(String name) {
69
- this.name = name;
70
- }
67
+ public void setName(String name) {
68
+ this.name = name;
69
+ }
7170
72
- public String getDescription() {
73
- return description;
74
- }
71
+ public String getDescription() {
72
+ return description;
73
+ }
7574
76
- public void setDescription(String description) {
77
- this.description = description;
78
- }
75
+ public void setDescription(String description) {
76
+ this.description = description;
77
+ }
7978
80
- public String getCode() {
81
- return code;
82
- }
79
+ public String getCode() {
80
+ return code;
81
+ }
8382
84
- public void setCode(String code) {
85
- this.code = code;
86
- }
83
+ public void setCode(String code) {
84
+ this.code = code;
85
+ }
8786
88
- public Application getApplication() {
89
- return application;
90
- }
87
+ public Application getApplication() {
88
+ return application;
89
+ }
9190
92
- @JsonProperty("application_name")
93
- public String getParentOrgName() {
94
- return application == null ? null : application.getName();
95
- }
91
+ @JsonProperty("application_name")
92
+ public String getParentOrgName() {
93
+ return application == null ? null : application.getName();
94
+ }
9695
97
- @JsonProperty("application_id")
98
- public Integer getApplicationId() {
99
- LOG.info("application " + application);
100
- return application == null ? null : application.getId();
101
- }
96
+ @JsonProperty("application_id")
97
+ public Integer getApplicationId() {
98
+ LOG.info("application " + application);
99
+ return application == null ? null : application.getId();
100
+ }
102101
103
- @JsonProperty("application_id")
104
- public void setApplicationId(Integer appId) {
105
- LOG.info("setApplicationId(Integer appId) " + appId);
106
- application = new Application();
107
- application.setId(appId);
108
- }
102
+ @JsonProperty("application_id")
103
+ public void setApplicationId(Integer appId) {
104
+ LOG.info("setApplicationId(Integer appId) " + appId);
105
+ application = new Application();
106
+ application.setId(appId);
107
+ }
109108
110
- public void setApplication(Application application) {
111
- this.application = application;
112
- }
109
+ public void setApplication(Application application) {
110
+ this.application = application;
111
+ }
113112
114
- public Date getCreationTimestamp() {
115
- return creationTimestamp;
116
- }
113
+ public Date getCreationTimestamp() {
114
+ return creationTimestamp;
115
+ }
117116
118
- public void setCreationTimestamp(Date creationTimestamp) {
119
- this.creationTimestamp = creationTimestamp;
120
- }
117
+ public void setCreationTimestamp(Date creationTimestamp) {
118
+ this.creationTimestamp = creationTimestamp;
119
+ }
121120
122121 }
securis/src/main/java/net/curisit/securis/db/Organization.java
....@@ -36,153 +36,153 @@
3636 @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
3737 @Entity
3838 @Table(name = "organization")
39
-@NamedQueries(
40
- { @NamedQuery(name = "list-organizations", query = "SELECT o FROM Organization o"), @NamedQuery(name = "list-organizations-by-ids", query = "SELECT o FROM Organization o where id in :list_ids"),
41
- @NamedQuery(name = "find-children-org", query = "SELECT o FROM Organization o where o.parentOrganization = :parentOrganization") })
39
+@NamedQueries({ @NamedQuery(name = "list-organizations", query = "SELECT o FROM Organization o"),
40
+ @NamedQuery(name = "list-organizations-by-ids", query = "SELECT o FROM Organization o where id in :list_ids"),
41
+ @NamedQuery(name = "find-children-org", query = "SELECT o FROM Organization o where o.parentOrganization = :parentOrganization") })
4242 public class Organization implements Serializable {
4343
44
- @SuppressWarnings("unused")
45
- private static final Logger LOG = LogManager.getLogger(Organization.class);
44
+ @SuppressWarnings("unused")
45
+ private static final Logger LOG = LogManager.getLogger(Organization.class);
4646
47
- private static final long serialVersionUID = 1L;
47
+ private static final long serialVersionUID = 1L;
4848
49
- @Id
50
- @GeneratedValue
51
- private int id;
49
+ @Id
50
+ @GeneratedValue
51
+ private int id;
5252
53
- private String code;
54
- private String name;
55
- private String description;
53
+ private String code;
54
+ private String name;
55
+ private String description;
5656
57
- @Column(name = "creation_timestamp")
58
- private Date creationTimestamp;
57
+ @Column(name = "creation_timestamp")
58
+ private Date creationTimestamp;
5959
60
- @JsonIgnore
61
- // We don't include the users to limit the size of each row a the listing
62
- @ManyToMany(cascade = CascadeType.REMOVE)
63
- @JoinTable(name = "user_organization", //
64
- joinColumns =
65
- { @JoinColumn(name = "organization_id", referencedColumnName = "id") }, //
66
- inverseJoinColumns =
67
- { @JoinColumn(name = "username", referencedColumnName = "username") })
68
- private List<User> users;
60
+ @JsonIgnore
61
+ // We don't include the users to limit the size of each row a the listing
62
+ @ManyToMany(cascade = CascadeType.REMOVE)
63
+ @JoinTable(name = "user_organization", //
64
+ joinColumns = { @JoinColumn(name = "organization_id", referencedColumnName = "id") }, //
65
+ inverseJoinColumns = { @JoinColumn(name = "username", referencedColumnName = "username") })
66
+ private List<User> users;
6967
70
- @JsonIgnore
71
- // We don't include the users to limit the size of each row a the listing
72
- @ManyToOne
73
- @JoinColumn(name = "org_parent_id")
74
- private Organization parentOrganization;
68
+ @JsonIgnore
69
+ // We don't include the users to limit the size of each row a the listing
70
+ @ManyToOne
71
+ @JoinColumn(name = "org_parent_id")
72
+ private Organization parentOrganization;
7573
76
- @JsonIgnore
77
- // We don't include the users to limit the size of each row a the listing
78
- @OneToMany(fetch = FetchType.LAZY, mappedBy = "parentOrganization")
79
- private Set<Organization> childOrganizations;
74
+ @JsonIgnore
75
+ // We don't include the users to limit the size of each row a the listing
76
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "parentOrganization")
77
+ private Set<Organization> childOrganizations;
8078
81
- public int getId() {
82
- return id;
83
- }
79
+ public int getId() {
80
+ return id;
81
+ }
8482
85
- public void setId(int id) {
86
- this.id = id;
87
- }
83
+ public void setId(int id) {
84
+ this.id = id;
85
+ }
8886
89
- public String getName() {
90
- return name;
91
- }
87
+ public String getName() {
88
+ return name;
89
+ }
9290
93
- public void setName(String name) {
94
- this.name = name;
95
- }
91
+ public void setName(String name) {
92
+ this.name = name;
93
+ }
9694
97
- public String getDescription() {
98
- return description;
99
- }
95
+ public String getDescription() {
96
+ return description;
97
+ }
10098
101
- public void setDescription(String description) {
102
- this.description = description;
103
- }
99
+ public void setDescription(String description) {
100
+ this.description = description;
101
+ }
104102
105
- public String getCode() {
106
- return code;
107
- }
103
+ public String getCode() {
104
+ return code;
105
+ }
108106
109
- public void setCode(String code) {
110
- this.code = code;
111
- }
107
+ public void setCode(String code) {
108
+ this.code = code;
109
+ }
112110
113
- public Date getCreationTimestamp() {
114
- return creationTimestamp;
115
- }
111
+ public Date getCreationTimestamp() {
112
+ return creationTimestamp;
113
+ }
116114
117
- public void setCreationTimestamp(Date creationTimestamp) {
118
- this.creationTimestamp = creationTimestamp;
119
- }
115
+ public void setCreationTimestamp(Date creationTimestamp) {
116
+ this.creationTimestamp = creationTimestamp;
117
+ }
120118
121
- public List<User> getUsers() {
122
- return users;
123
- }
119
+ public List<User> getUsers() {
120
+ return users;
121
+ }
124122
125
- public void setUsers(List<User> users) {
126
- this.users = users;
127
- }
123
+ public void setUsers(List<User> users) {
124
+ this.users = users;
125
+ }
128126
129
- public Organization getParentOrganization() {
130
- return parentOrganization;
131
- }
127
+ public Organization getParentOrganization() {
128
+ return parentOrganization;
129
+ }
132130
133
- public void setParentOrganization(Organization parentOrganization) {
134
- this.parentOrganization = parentOrganization;
135
- }
131
+ public void setParentOrganization(Organization parentOrganization) {
132
+ this.parentOrganization = parentOrganization;
133
+ }
136134
137
- // Roberto: Following methods are necessary to include in the REST list response
138
- // information about the referenced entities.
139
- @JsonProperty("org_parent_id")
140
- public void setParentOrgId(Integer orgId) {
141
- if (orgId != null) {
142
- parentOrganization = new Organization();
143
- parentOrganization.setId(orgId);
144
- } else {
145
- parentOrganization = null;
146
- }
147
- }
135
+ // Roberto: Following methods are necessary to include in the REST list
136
+ // response
137
+ // information about the referenced entities.
138
+ @JsonProperty("org_parent_id")
139
+ public void setParentOrgId(Integer orgId) {
140
+ if (orgId != null) {
141
+ parentOrganization = new Organization();
142
+ parentOrganization.setId(orgId);
143
+ } else {
144
+ parentOrganization = null;
145
+ }
146
+ }
148147
149
- @JsonProperty("org_parent_id")
150
- public Integer getParentOrgId() {
151
- return parentOrganization == null ? null : parentOrganization.getId();
152
- }
148
+ @JsonProperty("org_parent_id")
149
+ public Integer getParentOrgId() {
150
+ return parentOrganization == null ? null : parentOrganization.getId();
151
+ }
153152
154
- @JsonProperty("org_parent_name")
155
- public String getParentOrgName() {
156
- return parentOrganization == null ? null : parentOrganization.getName();
157
- }
153
+ @JsonProperty("org_parent_name")
154
+ public String getParentOrgName() {
155
+ return parentOrganization == null ? null : parentOrganization.getName();
156
+ }
158157
159
- @JsonProperty("users_ids")
160
- public void setUsersIds(List<String> usersIds) {
161
- users = new ArrayList<>();
162
- for (String userid : usersIds) {
163
- User u = new User();
164
- u.setUsername(userid);
165
- users.add(u);
166
- }
167
- }
158
+ @JsonProperty("users_ids")
159
+ public void setUsersIds(List<String> usersIds) {
160
+ users = new ArrayList<>();
161
+ for (String userid : usersIds) {
162
+ User u = new User();
163
+ u.setUsername(userid);
164
+ users.add(u);
165
+ }
166
+ }
168167
169
- @JsonProperty("users_ids")
170
- public List<String> getUsersIds() {
171
- if (users == null)
172
- return null;
173
- List<String> ids = new ArrayList<>();
174
- for (User user : users) {
175
- ids.add(user.getUsername());
176
- }
177
- return ids;
178
- }
168
+ @JsonProperty("users_ids")
169
+ public List<String> getUsersIds() {
170
+ if (users == null) {
171
+ return null;
172
+ }
173
+ List<String> ids = new ArrayList<>();
174
+ for (User user : users) {
175
+ ids.add(user.getUsername());
176
+ }
177
+ return ids;
178
+ }
179179
180
- public Set<Organization> getChildOrganizations() {
181
- return childOrganizations;
182
- }
180
+ public Set<Organization> getChildOrganizations() {
181
+ return childOrganizations;
182
+ }
183183
184
- public void setChildOrganizations(Set<Organization> childOrganizations) {
185
- this.childOrganizations = childOrganizations;
186
- }
184
+ public void setChildOrganizations(Set<Organization> childOrganizations) {
185
+ this.childOrganizations = childOrganizations;
186
+ }
187187
188188 }
securis/src/main/java/net/curisit/securis/db/Pack.java
....@@ -32,224 +32,230 @@
3232 @Entity
3333 @Table(name = "pack")
3434 @JsonIgnoreProperties(ignoreUnknown = true)
35
-@NamedQueries(
36
- { @NamedQuery(name = "list-packs", query = "SELECT pa FROM Pack pa"),//
37
- @NamedQuery(name = "list-packs-by-orgs", query = "SELECT pa FROM Pack pa where pa.organization.id in :list_ids") })
35
+@NamedQueries({ @NamedQuery(name = "list-packs", query = "SELECT pa FROM Pack pa"),//
36
+ @NamedQuery(name = "list-packs-by-orgs", query = "SELECT pa FROM Pack pa where pa.organization.id in :list_ids") })
3837 public class Pack implements Serializable {
3938
40
- private static final long serialVersionUID = 1L;
39
+ private static final long serialVersionUID = 1L;
4140
42
- @Id
43
- @GeneratedValue
44
- private int id;
41
+ @Id
42
+ @GeneratedValue
43
+ private int id;
4544
46
- private String code;
45
+ private String code;
4746
48
- private String comments;
47
+ private String comments;
4948
50
- @Column(name = "creation_timestamp")
51
- private Date creationTimestamp;
49
+ @Column(name = "creation_timestamp")
50
+ private Date creationTimestamp;
5251
53
- @JsonIgnore
54
- @ManyToOne
55
- @JoinColumn(name = "organization_id")
56
- private Organization organization;
52
+ @JsonIgnore
53
+ @ManyToOne
54
+ @JoinColumn(name = "organization_id")
55
+ private Organization organization;
5756
58
- @JsonIgnore
59
- @ManyToOne
60
- @JoinColumn(name = "license_type_id")
61
- private LicenseType licenseType;
57
+ @JsonIgnore
58
+ @ManyToOne
59
+ @JoinColumn(name = "license_type_id")
60
+ private LicenseType licenseType;
6261
63
- @JsonIgnore
64
- @ManyToOne
65
- @JoinColumn(name = "created_by")
66
- private User createdBy;
62
+ @JsonIgnore
63
+ @ManyToOne
64
+ @JoinColumn(name = "created_by")
65
+ private User createdBy;
6766
68
- @JsonIgnore
69
- @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "pack")
70
- private Set<License> licenses;
67
+ @JsonIgnore
68
+ @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "pack")
69
+ private Set<License> licenses;
7170
72
- @Column(name = "num_licenses")
73
- @JsonProperty("num_licenses")
74
- private int numLicenses;
71
+ @Column(name = "num_licenses")
72
+ @JsonProperty("num_licenses")
73
+ private int numLicenses;
7574
76
- @Column(name = "license_preactivation")
77
- @JsonProperty("license_preactivation")
78
- private boolean licensePreactivation;
75
+ @Column(name = "license_preactivation")
76
+ @JsonProperty("license_preactivation")
77
+ private boolean licensePreactivation;
7978
80
- public int getId() {
81
- return id;
82
- }
79
+ public int getId() {
80
+ return id;
81
+ }
8382
84
- public void setId(int id) {
85
- this.id = id;
86
- }
83
+ public void setId(int id) {
84
+ this.id = id;
85
+ }
8786
88
- public String getCode() {
89
- return code;
90
- }
87
+ public String getCode() {
88
+ return code;
89
+ }
9190
92
- public void setCode(String code) {
93
- this.code = code;
94
- }
91
+ public void setCode(String code) {
92
+ this.code = code;
93
+ }
9594
96
- public Date getCreationTimestamp() {
97
- return creationTimestamp;
98
- }
95
+ public Date getCreationTimestamp() {
96
+ return creationTimestamp;
97
+ }
9998
100
- public void setCreationTimestamp(Date creationTimestamp) {
101
- this.creationTimestamp = creationTimestamp;
102
- }
99
+ public void setCreationTimestamp(Date creationTimestamp) {
100
+ this.creationTimestamp = creationTimestamp;
101
+ }
103102
104
- public Organization getOrganization() {
105
- return organization;
106
- }
103
+ public Organization getOrganization() {
104
+ return organization;
105
+ }
107106
108
- public void setOrganization(Organization organization) {
109
- this.organization = organization;
110
- }
107
+ public void setOrganization(Organization organization) {
108
+ this.organization = organization;
109
+ }
111110
112
- public LicenseType getLicenseType() {
113
- return licenseType;
114
- }
111
+ public LicenseType getLicenseType() {
112
+ return licenseType;
113
+ }
115114
116
- public void setLicenseType(LicenseType licenseType) {
117
- this.licenseType = licenseType;
118
- }
115
+ public void setLicenseType(LicenseType licenseType) {
116
+ this.licenseType = licenseType;
117
+ }
119118
120
- public User getCreatedBy() {
121
- return createdBy;
122
- }
119
+ public User getCreatedBy() {
120
+ return createdBy;
121
+ }
123122
124
- public void setCreatedBy(User createdBy) {
125
- this.createdBy = createdBy;
126
- }
123
+ public void setCreatedBy(User createdBy) {
124
+ this.createdBy = createdBy;
125
+ }
127126
128
- public int getNumLicenses() {
129
- return numLicenses;
130
- }
127
+ public int getNumLicenses() {
128
+ return numLicenses;
129
+ }
131130
132
- public void setNumLicenses(int numLicenses) {
133
- this.numLicenses = numLicenses;
134
- }
131
+ public void setNumLicenses(int numLicenses) {
132
+ this.numLicenses = numLicenses;
133
+ }
135134
136
- @JsonProperty("num_activations")
137
- public int getNumActivations() {
138
- if (licenses == null)
139
- return 0;
140
- int num = 0;
141
- for (License lic : licenses) {
142
- if (lic.getStatus() == License.Status.ACTIVE)
143
- num++;
144
- }
145
- return num;
146
- }
135
+ @JsonProperty("num_activations")
136
+ public int getNumActivations() {
137
+ if (licenses == null) {
138
+ return 0;
139
+ }
140
+ int num = 0;
141
+ for (License lic : licenses) {
142
+ if (lic.getStatus() == License.Status.ACTIVE) {
143
+ num++;
144
+ }
145
+ }
146
+ return num;
147
+ }
147148
148
- /**
149
- * Counts all created licenses, It counts active licenses and licenses waiting for activation This number will be used to control the max number of licenses created. Ignore canceled licenses.
150
- *
151
- * @return
152
- */
153
- @JsonProperty("num_creations")
154
- public int getNumCreations() {
155
- if (licenses == null)
156
- return 0;
157
- int num = 0;
158
- for (License lic : licenses) {
159
- if (lic.getStatus() != License.Status.CANCELED)
160
- num++;
161
- }
162
- return num;
163
- }
149
+ /**
150
+ * Counts all created licenses, It counts active licenses and licenses
151
+ * waiting for activation This number will be used to control the max number
152
+ * of licenses created. Ignore canceled licenses.
153
+ *
154
+ * @return
155
+ */
156
+ @JsonProperty("num_creations")
157
+ public int getNumCreations() {
158
+ if (licenses == null) {
159
+ return 0;
160
+ }
161
+ int num = 0;
162
+ for (License lic : licenses) {
163
+ if (lic.getStatus() != License.Status.CANCELED) {
164
+ num++;
165
+ }
166
+ }
167
+ return num;
168
+ }
164169
165
- /**
166
- * Number of available licenses in this pack
167
- *
168
- * @return
169
- */
170
- @JsonProperty("num_available")
171
- public int getNumAvailables() {
172
- return numLicenses - getNumCreations();
173
- }
170
+ /**
171
+ * Number of available licenses in this pack
172
+ *
173
+ * @return
174
+ */
175
+ @JsonProperty("num_available")
176
+ public int getNumAvailables() {
177
+ return numLicenses - getNumCreations();
178
+ }
174179
175
- @JsonProperty("organization_name")
176
- public String getOrgName() {
177
- return organization == null ? null : organization.getName();
178
- }
180
+ @JsonProperty("organization_name")
181
+ public String getOrgName() {
182
+ return organization == null ? null : organization.getName();
183
+ }
179184
180
- @JsonProperty("application_name")
181
- public String getAppName() {
182
- if (licenseType == null)
183
- return null;
184
- Application app = licenseType.getApplication();
185
- return app == null ? null : app.getName();
186
- }
185
+ @JsonProperty("application_name")
186
+ public String getAppName() {
187
+ if (licenseType == null) {
188
+ return null;
189
+ }
190
+ Application app = licenseType.getApplication();
191
+ return app == null ? null : app.getName();
192
+ }
187193
188
- @JsonProperty("organization_id")
189
- public Integer getOrgId() {
190
- return organization == null ? null : organization.getId();
191
- }
194
+ @JsonProperty("organization_id")
195
+ public Integer getOrgId() {
196
+ return organization == null ? null : organization.getId();
197
+ }
192198
193
- @JsonProperty("organization_id")
194
- public void setOrgId(Integer idOrg) {
195
- if (idOrg == null) {
196
- organization = null;
197
- } else {
198
- organization = new Organization();
199
- organization.setId(idOrg);
200
- }
201
- }
199
+ @JsonProperty("organization_id")
200
+ public void setOrgId(Integer idOrg) {
201
+ if (idOrg == null) {
202
+ organization = null;
203
+ } else {
204
+ organization = new Organization();
205
+ organization.setId(idOrg);
206
+ }
207
+ }
202208
203
- @JsonProperty("license_type_id")
204
- public void setLicTypeId(Integer idLT) {
205
- if (idLT == null) {
206
- licenseType = null;
207
- } else {
208
- licenseType = new LicenseType();
209
- licenseType.setId(idLT);
210
- }
211
- }
209
+ @JsonProperty("license_type_id")
210
+ public void setLicTypeId(Integer idLT) {
211
+ if (idLT == null) {
212
+ licenseType = null;
213
+ } else {
214
+ licenseType = new LicenseType();
215
+ licenseType.setId(idLT);
216
+ }
217
+ }
212218
213
- @JsonProperty("license_type_id")
214
- public Integer getLicTypeId() {
215
- return licenseType == null ? null : licenseType.getId();
216
- }
219
+ @JsonProperty("license_type_id")
220
+ public Integer getLicTypeId() {
221
+ return licenseType == null ? null : licenseType.getId();
222
+ }
217223
218
- @JsonProperty("created_by_id")
219
- public String getCreatedById() {
220
- return createdBy == null ? null : createdBy.getUsername();
221
- }
224
+ @JsonProperty("created_by_id")
225
+ public String getCreatedById() {
226
+ return createdBy == null ? null : createdBy.getUsername();
227
+ }
222228
223
- @JsonProperty("created_by_id")
224
- public void setCreatedById(String username) {
225
- createdBy = new User();
226
- createdBy.setUsername(username);
227
- }
229
+ @JsonProperty("created_by_id")
230
+ public void setCreatedById(String username) {
231
+ createdBy = new User();
232
+ createdBy.setUsername(username);
233
+ }
228234
229
- @JsonProperty("created_by_name")
230
- public String getCreatedByname() {
231
- return createdBy == null ? null : String.format("%s %s (%s)", createdBy.getFirstName(), createdBy.getLastName(), createdBy.getUsername());
232
- }
235
+ @JsonProperty("created_by_name")
236
+ public String getCreatedByname() {
237
+ return createdBy == null ? null : String.format("%s %s (%s)", createdBy.getFirstName(), createdBy.getLastName(), createdBy.getUsername());
238
+ }
233239
234
- @JsonProperty("licensetype_code")
235
- public String getLicenseTypcode() {
236
- return licenseType == null ? null : licenseType.getCode();
237
- }
240
+ @JsonProperty("licensetype_code")
241
+ public String getLicenseTypcode() {
242
+ return licenseType == null ? null : licenseType.getCode();
243
+ }
238244
239
- public String getComments() {
240
- return comments;
241
- }
245
+ public String getComments() {
246
+ return comments;
247
+ }
242248
243
- public void setComments(String comments) {
244
- this.comments = comments;
245
- }
249
+ public void setComments(String comments) {
250
+ this.comments = comments;
251
+ }
246252
247
- public boolean isLicensePreactivation() {
248
- return licensePreactivation;
249
- }
253
+ public boolean isLicensePreactivation() {
254
+ return licensePreactivation;
255
+ }
250256
251
- public void setLicensePreactivation(boolean licensePreactivation) {
252
- this.licensePreactivation = licensePreactivation;
253
- }
257
+ public void setLicensePreactivation(boolean licensePreactivation) {
258
+ this.licensePreactivation = licensePreactivation;
259
+ }
254260
255261 }
securis/src/main/java/net/curisit/securis/db/User.java
....@@ -30,187 +30,191 @@
3030 @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
3131 @Entity
3232 @Table(name = "user")
33
-@NamedQueries(
34
- { @NamedQuery(name = "list-users", query = "SELECT u FROM User u"), @NamedQuery(name = "get-user", query = "SELECT u FROM User u where u.username = :username"),
35
- @NamedQuery(name = "auth-user", query = "SELECT u FROM User u where u.username = :username and u.password = :password"), @NamedQuery(name = "delete-all-users", query = "delete FROM User u") })
33
+@NamedQueries({ @NamedQuery(name = "list-users", query = "SELECT u FROM User u"),
34
+ @NamedQuery(name = "get-user", query = "SELECT u FROM User u where u.username = :username"),
35
+ @NamedQuery(name = "auth-user", query = "SELECT u FROM User u where u.username = :username and u.password = :password"),
36
+ @NamedQuery(name = "delete-all-users", query = "delete FROM User u") })
3637 public class User implements Serializable {
3738
38
- private static final long serialVersionUID = 1L;
39
+ private static final long serialVersionUID = 1L;
3940
40
- @Id
41
- private String username;
41
+ @Id
42
+ private String username;
4243
43
- private String password;
44
+ private String password;
4445
45
- @JsonProperty(value = "first_name")
46
- @Column(name = "first_name")
47
- private String firstName;
46
+ @JsonProperty(value = "first_name")
47
+ @Column(name = "first_name")
48
+ private String firstName;
4849
49
- @JsonProperty(value = "last_name")
50
- @Column(name = "last_name")
51
- private String lastName;
50
+ @JsonProperty(value = "last_name")
51
+ @Column(name = "last_name")
52
+ private String lastName;
5253
53
- private int roles;
54
+ private int roles;
5455
55
- @Column(name = "last_login")
56
- private Date lastLogin;
56
+ @Column(name = "last_login")
57
+ private Date lastLogin;
5758
58
- @Column(name = "modification_timestamp")
59
- private Date modificationTimestamp;
59
+ @Column(name = "modification_timestamp")
60
+ private Date modificationTimestamp;
6061
61
- @Column(name = "creation_timestamp")
62
- private Date creationTimestamp;
62
+ @Column(name = "creation_timestamp")
63
+ private Date creationTimestamp;
6364
64
- private String lang;
65
+ private String lang;
6566
66
- @JsonIgnore
67
- @ManyToMany
68
- @JoinTable(name = "user_organization", //
69
- joinColumns =
70
- { @JoinColumn(name = "username", referencedColumnName = "username") }, //
71
- inverseJoinColumns =
72
- { @JoinColumn(name = "organization_id", referencedColumnName = "id") } //
73
- )
74
- private Set<Organization> organizations;
67
+ @JsonIgnore
68
+ @ManyToMany
69
+ @JoinTable(name = "user_organization", //
70
+ joinColumns = { @JoinColumn(name = "username", referencedColumnName = "username") }, //
71
+ inverseJoinColumns = { @JoinColumn(name = "organization_id", referencedColumnName = "id") } //
72
+ )
73
+ private Set<Organization> organizations;
7574
76
- public String getUsername() {
77
- return username;
78
- }
75
+ public String getUsername() {
76
+ return username;
77
+ }
7978
80
- public void setUsername(String username) {
81
- this.username = username;
82
- }
79
+ public void setUsername(String username) {
80
+ this.username = username;
81
+ }
8382
84
- public String getPassword() {
85
- return password;
86
- }
83
+ public String getPassword() {
84
+ return password;
85
+ }
8786
88
- public void setPassword(String password) {
89
- this.password = password;
90
- }
87
+ public void setPassword(String password) {
88
+ this.password = password;
89
+ }
9190
92
- public List<Integer> getRoles() {
93
- if (roles == 0)
94
- return null;
95
- List<Integer> aux = new ArrayList<>();
96
- for (int rol : Rol.ALL) {
97
- if ((roles & rol) != 0) // Each rol is a number with only 1 bit == 1 in binary representation
98
- aux.add(rol);
99
- }
100
- return aux;
101
- }
91
+ public List<Integer> getRoles() {
92
+ if (roles == 0) {
93
+ return null;
94
+ }
95
+ List<Integer> aux = new ArrayList<>();
96
+ for (int rol : Rol.ALL) {
97
+ if ((roles & rol) != 0) { // Each rol is a number with only 1 bit ==
98
+ // 1 in binary representation
99
+ aux.add(rol);
100
+ }
101
+ }
102
+ return aux;
103
+ }
102104
103
- public void setRoles(List<Integer> roles) {
104
- this.roles = 0;
105
- if (roles != null)
106
- for (Integer rol : roles) {
107
- this.roles |= rol;
108
- }
109
- }
105
+ public void setRoles(List<Integer> roles) {
106
+ this.roles = 0;
107
+ if (roles != null) {
108
+ for (Integer rol : roles) {
109
+ this.roles |= rol;
110
+ }
111
+ }
112
+ }
110113
111
- public String getFirstName() {
112
- return firstName;
113
- }
114
+ public String getFirstName() {
115
+ return firstName;
116
+ }
114117
115
- public void setFirstName(String firstName) {
116
- this.firstName = firstName;
117
- }
118
+ public void setFirstName(String firstName) {
119
+ this.firstName = firstName;
120
+ }
118121
119
- public String getLastName() {
120
- return lastName;
121
- }
122
+ public String getLastName() {
123
+ return lastName;
124
+ }
122125
123
- public void setLastName(String lastName) {
124
- this.lastName = lastName;
125
- }
126
+ public void setLastName(String lastName) {
127
+ this.lastName = lastName;
128
+ }
126129
127
- public Date getLastLogin() {
128
- return lastLogin;
129
- }
130
+ public Date getLastLogin() {
131
+ return lastLogin;
132
+ }
130133
131
- public void setLastLogin(Date lastLogin) {
132
- this.lastLogin = lastLogin;
133
- }
134
+ public void setLastLogin(Date lastLogin) {
135
+ this.lastLogin = lastLogin;
136
+ }
134137
135
- public Date getModificationTimestamp() {
136
- return modificationTimestamp;
137
- }
138
+ public Date getModificationTimestamp() {
139
+ return modificationTimestamp;
140
+ }
138141
139
- public void setModificationTimestamp(Date modificationTimestamp) {
140
- this.modificationTimestamp = modificationTimestamp;
141
- }
142
+ public void setModificationTimestamp(Date modificationTimestamp) {
143
+ this.modificationTimestamp = modificationTimestamp;
144
+ }
142145
143
- public Date getCreationTimestamp() {
144
- return creationTimestamp;
145
- }
146
+ public Date getCreationTimestamp() {
147
+ return creationTimestamp;
148
+ }
146149
147
- public void setCreationTimestamp(Date creationTimestamp) {
148
- this.creationTimestamp = creationTimestamp;
149
- }
150
+ public void setCreationTimestamp(Date creationTimestamp) {
151
+ this.creationTimestamp = creationTimestamp;
152
+ }
150153
151
- @Override
152
- public String toString() {
153
- return "{User: " + username + " Name: " + firstName + " " + lastName + ", last login: " + lastLogin + "}";
154
- }
154
+ @Override
155
+ public String toString() {
156
+ return "{User: " + username + " Name: " + firstName + " " + lastName + ", last login: " + lastLogin + "}";
157
+ }
155158
156
- public String getLang() {
157
- return lang;
158
- }
159
+ public String getLang() {
160
+ return lang;
161
+ }
159162
160
- public void setLang(String lang) {
161
- this.lang = lang;
162
- }
163
+ public void setLang(String lang) {
164
+ this.lang = lang;
165
+ }
163166
164
- public Set<Organization> getOrganizations() {
165
- return organizations;
166
- }
167
+ public Set<Organization> getOrganizations() {
168
+ return organizations;
169
+ }
167170
168
- public void setOrganizations(Set<Organization> organizations) {
169
- this.organizations = organizations;
170
- }
171
+ public void setOrganizations(Set<Organization> organizations) {
172
+ this.organizations = organizations;
173
+ }
171174
172
- @JsonProperty("organizations_ids")
173
- public void setOrgsIds(List<Integer> orgsIds) {
174
- organizations = new HashSet<>();
175
- for (Integer orgid : orgsIds) {
176
- Organization o = new Organization();
177
- o.setId(orgid);
178
- organizations.add(o);
179
- }
180
- }
175
+ @JsonProperty("organizations_ids")
176
+ public void setOrgsIds(List<Integer> orgsIds) {
177
+ organizations = new HashSet<>();
178
+ for (Integer orgid : orgsIds) {
179
+ Organization o = new Organization();
180
+ o.setId(orgid);
181
+ organizations.add(o);
182
+ }
183
+ }
181184
182
- @JsonProperty("organizations_ids")
183
- public Set<Integer> getOrgsIds() {
184
- if (organizations == null)
185
- return null;
186
- Set<Integer> ids = new HashSet<>();
187
- for (Organization org : organizations) {
188
- ids.add(org.getId());
189
- }
190
- return ids;
191
- }
185
+ @JsonProperty("organizations_ids")
186
+ public Set<Integer> getOrgsIds() {
187
+ if (organizations == null) {
188
+ return null;
189
+ }
190
+ Set<Integer> ids = new HashSet<>();
191
+ for (Organization org : organizations) {
192
+ ids.add(org.getId());
193
+ }
194
+ return ids;
195
+ }
192196
193
- @JsonIgnore
194
- public Set<Integer> getAllOrgsIds() {
195
- if (organizations == null)
196
- return null;
197
- Set<Integer> ids = new HashSet<>();
198
- includeAllOrgs(this.organizations, ids);
199
- return ids;
200
- }
197
+ @JsonIgnore
198
+ public Set<Integer> getAllOrgsIds() {
199
+ if (organizations == null) {
200
+ return null;
201
+ }
202
+ Set<Integer> ids = new HashSet<>();
203
+ includeAllOrgs(this.organizations, ids);
204
+ return ids;
205
+ }
201206
202
- private void includeAllOrgs(Set<Organization> list, Set<Integer> orgIds) {
203
- for (Organization org : list) {
204
- orgIds.add(org.getId());
205
- includeAllOrgs(org.getChildOrganizations(), orgIds);
206
- }
207
- }
207
+ private void includeAllOrgs(Set<Organization> list, Set<Integer> orgIds) {
208
+ for (Organization org : list) {
209
+ orgIds.add(org.getId());
210
+ includeAllOrgs(org.getChildOrganizations(), orgIds);
211
+ }
212
+ }
208213
209
- static public class Rol {
210
- static public final int ADVANCE = 0x01;
211
- static public final int ADMIN = 0x02;
212
- static public final int[] ALL = new int[]
213
- { ADVANCE, ADMIN };
214
- }
214
+ public static class Rol {
215
+ public static final int ADVANCE = 0x01;
216
+ public static final int ADMIN = 0x02;
217
+ public static final int[] ALL = new int[] { ADVANCE, ADMIN };
218
+ }
215219
216220 }
securis/src/main/java/net/curisit/securis/ioc/RequestsModule.java
....@@ -20,29 +20,28 @@
2020
2121 public class RequestsModule extends RequestScopeModule {
2222
23
- @Override
24
- protected void configure() {
25
- super.configure();
26
- // TODO: Make the bind using reflection dynamically
27
- bind(SecurityInterceptor.class);
28
- // bind(SecurityContextWrapper.class).in(RequestScoped.class);
23
+ @Override
24
+ protected void configure() {
25
+ super.configure();
26
+ // TODO: Make the bind using reflection dynamically
27
+ bind(SecurityInterceptor.class);
2928
30
- bind(BasicServices.class);
31
- bind(LicenseServices.class);
32
- bind(UserResource.class);
29
+ bind(BasicServices.class);
30
+ bind(LicenseServices.class);
31
+ bind(UserResource.class);
3332
34
- bind(ApplicationResource.class);
35
- bind(LicenseTypeResource.class);
36
- bind(OrganizationResource.class);
37
- bind(ApiResource.class);
38
- bind(LicenseResource.class);
39
- bind(PackResource.class);
40
- }
33
+ bind(ApplicationResource.class);
34
+ bind(LicenseTypeResource.class);
35
+ bind(OrganizationResource.class);
36
+ bind(ApiResource.class);
37
+ bind(LicenseResource.class);
38
+ bind(PackResource.class);
39
+ }
4140
42
- @Provides
43
- @RequestScoped
44
- public User provideUser() {
45
- return ResteasyProviderFactory.getContextData(User.class);
46
- }
41
+ @Provides
42
+ @RequestScoped
43
+ public User provideUser() {
44
+ return ResteasyProviderFactory.getContextData(User.class);
45
+ }
4746
4847 }
securis/src/main/java/net/curisit/securis/ioc/SecurisModule.java
....@@ -22,142 +22,144 @@
2222
2323 public class SecurisModule extends AbstractModule {
2424
25
- private static final int DEFAULT_PORT = 9997;
26
- private static final String PROPERTIES_FILE_NAME = "/server.properties";
25
+ private static final int DEFAULT_PORT = 9997;
26
+ private static final String PROPERTIES_FILE_NAME = "/server.properties";
2727
28
- private static final Logger LOG = LogManager.getLogger(SecurisModule.class);
28
+ private static final Logger LOG = LogManager.getLogger(SecurisModule.class);
2929
30
- @Override
31
- protected void configure() {
30
+ @Override
31
+ protected void configure() {
3232
33
- }
33
+ }
3434
35
- public String getPassword() {
36
- return getFilePassword() + " " + "53curi5";
37
- }
35
+ public String getPassword() {
36
+ return getFilePassword() + " " + "53curi5";
37
+ }
3838
39
- public String getFilePassword() {
40
- return "cur151T";
41
- }
39
+ public String getFilePassword() {
40
+ return "cur151T";
41
+ }
4242
43
- public String getUrl(File appDir) {
44
- return String.format("jdbc:h2:%s/db/securis;CIPHER=AES", appDir.getAbsolutePath());
45
- }
43
+ public String getUrl(File appDir) {
44
+ return String.format("jdbc:h2:%s/db/securis;CIPHER=AES", appDir.getAbsolutePath());
45
+ }
4646
47
- @Named("base-uri")
48
- @Provides
49
- @Singleton
50
- public URI getBaseURI() {
51
- // TODO Read from configuration, where?
52
- try {
53
- // String url = MessageFormat.format("http://{0}/", InetAddress.getLocalHost().getHostAddress());
54
- String url = MessageFormat.format("http://{0}/", "0.0.0.0");
55
- LOG.debug("Server url{}", url);
56
- return UriBuilder.fromUri(url).port(getPort()).build();
57
- } catch (IllegalArgumentException | UriBuilderException e) {
58
- return UriBuilder.fromUri("http://localhost/").port(getPort()).build();
59
- }
60
- }
47
+ @Named("base-uri")
48
+ @Provides
49
+ @Singleton
50
+ public URI getBaseURI() {
51
+ // TODO Read from configuration, where?
52
+ try {
53
+ String url = MessageFormat.format("http://{0}/", "0.0.0.0");
54
+ LOG.debug("Server url{}", url);
55
+ return UriBuilder.fromUri(url).port(getPort()).build();
56
+ } catch (IllegalArgumentException | UriBuilderException e) {
57
+ return UriBuilder.fromUri("http://localhost/").port(getPort()).build();
58
+ }
59
+ }
6160
62
- private int getPort() {
63
- Integer port;
64
- Properties prop = new Properties();
65
- try {
66
- prop.load(getClass().getResourceAsStream(PROPERTIES_FILE_NAME));
67
- port = Integer.valueOf(prop.getProperty("port"));
68
- if (port == null)
69
- return DEFAULT_PORT;
70
- else
71
- return port;
72
- } catch (Exception ex) {
73
- return DEFAULT_PORT;
74
- }
75
- }
61
+ private int getPort() {
62
+ Integer port;
63
+ Properties prop = new Properties();
64
+ try {
65
+ prop.load(getClass().getResourceAsStream(PROPERTIES_FILE_NAME));
66
+ port = Integer.valueOf(prop.getProperty("port"));
67
+ if (port == null) {
68
+ return DEFAULT_PORT;
69
+ } else {
70
+ return port;
71
+ }
72
+ } catch (Exception ex) {
73
+ return DEFAULT_PORT;
74
+ }
75
+ }
7676
77
- protected List<String> getAppDbFiles() {
77
+ protected List<String> getAppDbFiles() {
7878
79
- return Arrays.asList("/db/schema.sql");
80
- }
79
+ return Arrays.asList("/db/schema.sql");
80
+ }
8181
82
- @Named("temporary-dir")
83
- @Provides
84
- @Singleton
85
- public File getTemporaryDir() {
86
- String tmp = getAppDir().getAbsolutePath();
87
- tmp += File.separator + ".TEMP";
88
- File ftmp = new File(tmp);
89
- if (!ftmp.exists()) {
90
- if (!ftmp.mkdirs())
91
- return null;
92
- LOG.debug("Created temporary directory for app in: {}", ftmp.getAbsolutePath());
93
- ftmp.deleteOnExit();
94
- }
95
- return ftmp;
96
- }
82
+ @Named("temporary-dir")
83
+ @Provides
84
+ @Singleton
85
+ public File getTemporaryDir() {
86
+ String tmp = getAppDir().getAbsolutePath();
87
+ tmp += File.separator + ".TEMP";
88
+ File ftmp = new File(tmp);
89
+ if (!ftmp.exists()) {
90
+ if (!ftmp.mkdirs()) {
91
+ return null;
92
+ }
93
+ LOG.debug("Created temporary directory for app in: {}", ftmp.getAbsolutePath());
94
+ ftmp.deleteOnExit();
95
+ }
96
+ return ftmp;
97
+ }
9798
98
- @Named("app-dir")
99
- @Provides
100
- @Singleton
101
- public File getAppDir() {
102
- String appDir = System.getProperty("user.home", System.getProperty("user.dir"));
103
- if (appDir == null) {
104
- appDir = ".";
105
- }
106
- appDir += File.separator + ".SeCuris";
107
- File fAppDir = new File(appDir);
108
- if (!fAppDir.exists()) {
109
- if (!fAppDir.mkdirs())
110
- return null;
111
- LOG.debug("Created app working directory app in: {}", fAppDir.getAbsolutePath());
112
- }
113
- return fAppDir;
114
- }
99
+ @Named("app-dir")
100
+ @Provides
101
+ @Singleton
102
+ public File getAppDir() {
103
+ String appDir = System.getProperty("user.home", System.getProperty("user.dir"));
104
+ if (appDir == null) {
105
+ appDir = ".";
106
+ }
107
+ appDir += File.separator + ".SeCuris";
108
+ File fAppDir = new File(appDir);
109
+ if (!fAppDir.exists()) {
110
+ if (!fAppDir.mkdirs()) {
111
+ return null;
112
+ }
113
+ LOG.debug("Created app working directory app in: {}", fAppDir.getAbsolutePath());
114
+ }
115
+ return fAppDir;
116
+ }
115117
116
- @Named("support-email")
117
- @Provides
118
- @Singleton
119
- public String getSupportEmail() {
120
- return "integrity@curistec.com";
121
- }
118
+ @Named("support-email")
119
+ @Provides
120
+ @Singleton
121
+ public String getSupportEmail() {
122
+ return "integrity@curistec.com";
123
+ }
122124
123
- @Named("hash-logo")
124
- @Provides
125
- @Singleton
126
- public String getHashLogo() {
127
- return "1b42616809d4cd8ccf109e3c30d0ab25067f160b30b7354a08ddd563de0096ba";
128
- }
125
+ @Named("hash-logo")
126
+ @Provides
127
+ @Singleton
128
+ public String getHashLogo() {
129
+ return "1b42616809d4cd8ccf109e3c30d0ab25067f160b30b7354a08ddd563de0096ba";
130
+ }
129131
130
- @Named("license-req-file-name")
131
- @Provides
132
- @Singleton
133
- public String getLicenseReqFileName() {
134
- return "license.req";
135
- }
132
+ @Named("license-req-file-name")
133
+ @Provides
134
+ @Singleton
135
+ public String getLicenseReqFileName() {
136
+ return "license.req";
137
+ }
136138
137
- @Named("license-file-name")
138
- @Provides
139
- @Singleton
140
- public String getLicenseFileName() {
141
- return "license.lic";
142
- }
139
+ @Named("license-file-name")
140
+ @Provides
141
+ @Singleton
142
+ public String getLicenseFileName() {
143
+ return "license.lic";
144
+ }
143145
144
- @Provides
145
- @Singleton
146
- public DataSource getDataSource(@Named("app-dir") File appDir) {
146
+ @Provides
147
+ @Singleton
148
+ public DataSource getDataSource(@Named("app-dir") File appDir) {
147149
148
- JdbcDataSource dataSource = new JdbcDataSource();
149
- dataSource.setURL(getUrl(appDir));
150
- dataSource.setUser("curis");
151
- dataSource.setPassword(getPassword());
152
- LOG.debug("JdbcDataSource: {}", dataSource);
153
- return dataSource;
154
- }
150
+ JdbcDataSource dataSource = new JdbcDataSource();
151
+ dataSource.setURL(getUrl(appDir));
152
+ dataSource.setUser("curis");
153
+ dataSource.setPassword(getPassword());
154
+ LOG.debug("JdbcDataSource: {}", dataSource);
155
+ return dataSource;
156
+ }
155157
156
- @Named("db-files")
157
- @Provides
158
- @Singleton
159
- public List<String> getDbFiles() {
160
- return getAppDbFiles();
161
- }
158
+ @Named("db-files")
159
+ @Provides
160
+ @Singleton
161
+ public List<String> getDbFiles() {
162
+ return getAppDbFiles();
163
+ }
162164
163165 }
securis/src/main/java/net/curisit/securis/security/BasicSecurityContext.java
....@@ -11,82 +11,83 @@
1111
1212 public class BasicSecurityContext implements SecurityContext {
1313
14
- final public static String ROL_ADVANCE = "advance";
15
- final public static String ROL_ADMIN = "admin";
14
+ final public static String ROL_ADVANCE = "advance";
15
+ final public static String ROL_ADMIN = "admin";
1616
17
- final static Map<String, Integer> ROLES = Utils.<String, Integer> createMap(ROL_ADVANCE, User.Rol.ADVANCE, ROL_ADMIN, User.Rol.ADMIN);
17
+ final static Map<String, Integer> ROLES = Utils.<String, Integer> createMap(ROL_ADVANCE, User.Rol.ADVANCE, ROL_ADMIN, User.Rol.ADMIN);
1818
19
- Principal user = null;
20
- int roles = 0;
21
- boolean secure = false;
22
- Set<Integer> organizationsIds = null;
23
- double ran = 0;
19
+ Principal user = null;
20
+ int roles = 0;
21
+ boolean secure = false;
22
+ Set<Integer> organizationsIds = null;
23
+ double ran = 0;
2424
25
- public BasicSecurityContext(String username, int roles, boolean secure) {
26
- user = new UserPrincipal(username);
27
- this.roles = roles;
28
- this.secure = secure;
29
- ran = Math.random();
30
- }
25
+ public BasicSecurityContext(String username, int roles, boolean secure) {
26
+ user = new UserPrincipal(username);
27
+ this.roles = roles;
28
+ this.secure = secure;
29
+ ran = Math.random();
30
+ }
3131
32
- @Override
33
- public Principal getUserPrincipal() {
34
- return user;
35
- }
32
+ @Override
33
+ public Principal getUserPrincipal() {
34
+ return user;
35
+ }
3636
37
- @Override
38
- public boolean isUserInRole(String role) {
39
- Integer introle = ROLES.get(role);
40
- return introle != null && (introle & roles) != 0;
41
- }
37
+ @Override
38
+ public boolean isUserInRole(String role) {
39
+ Integer introle = ROLES.get(role);
40
+ return introle != null && (introle & roles) != 0;
41
+ }
4242
43
- @Override
44
- public boolean isSecure() {
45
- return secure;
46
- }
43
+ @Override
44
+ public boolean isSecure() {
45
+ return secure;
46
+ }
4747
48
- @Override
49
- public String getAuthenticationScheme() {
50
- return null;
51
- }
48
+ @Override
49
+ public String getAuthenticationScheme() {
50
+ return null;
51
+ }
5252
53
- @Override
54
- public String toString() {
53
+ @Override
54
+ public String toString() {
5555
56
- return String.format("SecurityContextWrapper(%f) %s", ran, user);
57
- }
56
+ return String.format("SecurityContextWrapper(%f) %s", ran, user);
57
+ }
5858
59
- public void setOrganizationsIds(Set<Integer> orgs) {
60
- this.organizationsIds = orgs;
61
- }
59
+ public void setOrganizationsIds(Set<Integer> orgs) {
60
+ this.organizationsIds = orgs;
61
+ }
6262
63
- public Set<Integer> getOrganizationsIds() {
64
- return this.organizationsIds;
65
- }
63
+ public Set<Integer> getOrganizationsIds() {
64
+ return this.organizationsIds;
65
+ }
6666
67
- private class UserPrincipal implements Principal {
67
+ private class UserPrincipal implements Principal {
6868
69
- final String name;
69
+ final String name;
7070
71
- public UserPrincipal(String name) {
72
- this.name = name;
73
- }
71
+ public UserPrincipal(String name) {
72
+ this.name = name;
73
+ }
7474
75
- @Override
76
- public String getName() {
77
- return this.name;
78
- }
75
+ @Override
76
+ public String getName() {
77
+ return this.name;
78
+ }
7979
80
- @Override
81
- public String toString() {
82
- return String.format("[%s]", name);
83
- }
80
+ @Override
81
+ public String toString() {
82
+ return String.format("[%s]", name);
83
+ }
8484
85
- }
85
+ }
8686
87
- public boolean isOrgAccesible(Integer orgid) {
88
- if (organizationsIds == null || orgid == null)
89
- return false;
90
- return organizationsIds.contains(orgid);
91
- }
87
+ public boolean isOrgAccesible(Integer orgid) {
88
+ if (organizationsIds == null || orgid == null) {
89
+ return false;
90
+ }
91
+ return organizationsIds.contains(orgid);
92
+ }
9293 }
securis/src/main/java/net/curisit/securis/security/Securable.java
....@@ -10,13 +10,13 @@
1010 @Retention(RetentionPolicy.RUNTIME)
1111 @Target(ElementType.METHOD)
1212 public @interface Securable {
13
- /**
14
- * Name of header parameter with the auth token to validate
15
- */
16
- String header() default TokenHelper.TOKEN_HEADER_PÀRAM;
13
+ /**
14
+ * Name of header parameter with the auth token to validate
15
+ */
16
+ String header() default TokenHelper.TOKEN_HEADER_PÀRAM;
1717
18
- /**
19
- * Bit mask with the rol or roles necessary to access the method
20
- */
21
- int roles() default 0;
18
+ /**
19
+ * Bit mask with the rol or roles necessary to access the method
20
+ */
21
+ int roles() default 0;
2222 }
securis/src/main/java/net/curisit/securis/security/SecurityInterceptor.java
....@@ -34,98 +34,94 @@
3434 // @PreMatching
3535 @Priority(Priorities.AUTHENTICATION)
3636 public class SecurityInterceptor implements javax.ws.rs.container.ContainerRequestFilter {
37
- private static final Logger LOG = LogManager.getLogger(SecurityInterceptor.class);
37
+ private static final Logger LOG = LogManager.getLogger(SecurityInterceptor.class);
3838
39
- @Inject
40
- private TokenHelper tokenHelper;
39
+ @Inject
40
+ private TokenHelper tokenHelper;
4141
42
- @Context
43
- private HttpServletRequest servletRequest;
42
+ @Context
43
+ private HttpServletRequest servletRequest;
4444
45
- @Inject
46
- CacheTTL cache;
45
+ @Inject
46
+ CacheTTL cache;
4747
48
- @Context
49
- Dispatcher dispatcher;
48
+ @Context
49
+ Dispatcher dispatcher;
5050
51
- @Inject
52
- com.google.inject.Provider<EntityManager> emProvider;
51
+ @Inject
52
+ com.google.inject.Provider<EntityManager> emProvider;
5353
54
- public void filter(ContainerRequestContext containerRequestContext) throws IOException {
55
- ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) containerRequestContext.getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
56
- Method method = methodInvoker.getMethod();
54
+ public void filter(ContainerRequestContext containerRequestContext) throws IOException {
55
+ ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) containerRequestContext
56
+ .getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
57
+ Method method = methodInvoker.getMethod();
5758
58
- if (!method.isAnnotationPresent(Securable.class))
59
- return;
60
- String token = servletRequest.getHeader(TokenHelper.TOKEN_HEADER_PÀRAM);
61
- if (token == null || !tokenHelper.isTokenValid(token)) {
62
- LOG.info("Access denied to '{}', Token not valid.", servletRequest.getPathInfo());
63
- containerRequestContext.abortWith(Response.status(Status.UNAUTHORIZED).build());
64
- } else {
65
- Securable sec = method.getAnnotation(Securable.class);
59
+ if (!method.isAnnotationPresent(Securable.class)) {
60
+ return;
61
+ }
62
+ String token = servletRequest.getHeader(TokenHelper.TOKEN_HEADER_PÀRAM);
63
+ if (token == null || !tokenHelper.isTokenValid(token)) {
64
+ LOG.info("Access denied to '{}', Token not valid.", servletRequest.getPathInfo());
65
+ containerRequestContext.abortWith(Response.status(Status.UNAUTHORIZED).build());
66
+ } else {
67
+ Securable sec = method.getAnnotation(Securable.class);
6668
67
- // If roles == 0 we only need to validate the token
68
- String username = tokenHelper.extractUserFromToken(token);
69
- int userRoles = getUserRoles(username);
70
- // if (sec.roles() != 0) {
71
- // if ((sec.roles() & userRoles) == 0) {
72
- // LOG.info("User {} has no necessary role to access url: {}", username, servletRequest.getPathInfo());
73
- // containerRequestContext.abortWith(Response.status(Status.UNAUTHORIZED).build());
74
- // }
75
- // }
76
- Set<Integer> orgs = getUserOrganizations(username);
69
+ // If roles == 0 we only need to validate the token
70
+ String username = tokenHelper.extractUserFromToken(token);
71
+ int userRoles = getUserRoles(username);
72
+ Set<Integer> orgs = getUserOrganizations(username);
7773
78
- BasicSecurityContext scw = new BasicSecurityContext(username, userRoles, servletRequest.isSecure());
79
- scw.setOrganizationsIds(orgs);
80
- containerRequestContext.setSecurityContext(scw);
81
- // Next line provide injection in resource methods
82
- ResteasyProviderFactory.pushContext(BasicSecurityContext.class, scw);
83
- LOG.debug("Added custom SecurityContext for user {}, orgs: {}", username, orgs);
84
- }
85
- }
74
+ BasicSecurityContext scw = new BasicSecurityContext(username, userRoles, servletRequest.isSecure());
75
+ scw.setOrganizationsIds(orgs);
76
+ containerRequestContext.setSecurityContext(scw);
77
+ // Next line provide injection in resource methods
78
+ ResteasyProviderFactory.pushContext(BasicSecurityContext.class, scw);
79
+ LOG.debug("Added custom SecurityContext for user {}, orgs: {}", username, orgs);
80
+ }
81
+ }
8682
87
- private Set<Integer> getUserOrganizations(String username) {
88
- @SuppressWarnings("unchecked")
89
- Set<Integer> userOrgs = cache.get("orgs_" + username, Set.class);
90
- if (userOrgs == null) {
91
- // Theorically this shouldn't be never null, but just in case...
92
- EntityManager em = emProvider.get();
93
- User user = em.find(User.class, username);
94
- if (user != null) {
95
- userOrgs = user.getAllOrgsIds();
96
- // We store user orgs in cache only for one hour
97
- cache.set("orgs_" + username, userOrgs, 3600);
98
- }
99
- }
83
+ private Set<Integer> getUserOrganizations(String username) {
84
+ @SuppressWarnings("unchecked")
85
+ Set<Integer> userOrgs = cache.get("orgs_" + username, Set.class);
86
+ if (userOrgs == null) {
87
+ // Theorically this shouldn't be never null, but just in case...
88
+ EntityManager em = emProvider.get();
89
+ User user = em.find(User.class, username);
90
+ if (user != null) {
91
+ userOrgs = user.getAllOrgsIds();
92
+ // We store user orgs in cache only for one hour
93
+ cache.set("orgs_" + username, userOrgs, 3600);
94
+ }
95
+ }
10096
101
- return userOrgs;
102
- }
97
+ return userOrgs;
98
+ }
10399
104
- private int getUserRoles(String username) {
105
- if (username == null)
106
- return 0;
107
- Integer userRoles = cache.get("roles_" + username, Integer.class);
108
- if (userRoles == null) {
109
- EntityManager em = emProvider.get();
110
- User user = em.find(User.class, username);
111
- if (user != null) {
112
- userRoles = 0;
113
- List<Integer> roles = user.getRoles();
114
- for (Integer rol : roles) {
115
- userRoles += rol;
116
- }
117
- // We store user roles in cache only for one hour
118
- cache.set("roles_" + username, userRoles, 3600);
119
- cache.set("orgs_" + username, user.getOrgsIds(), 3600);
120
- }
121
- }
122
- return userRoles == null ? 0 : userRoles.intValue();
123
- }
100
+ private int getUserRoles(String username) {
101
+ if (username == null) {
102
+ return 0;
103
+ }
104
+ Integer userRoles = cache.get("roles_" + username, Integer.class);
105
+ if (userRoles == null) {
106
+ EntityManager em = emProvider.get();
107
+ User user = em.find(User.class, username);
108
+ if (user != null) {
109
+ userRoles = 0;
110
+ List<Integer> roles = user.getRoles();
111
+ for (Integer rol : roles) {
112
+ userRoles += rol;
113
+ }
114
+ // We store user roles in cache only for one hour
115
+ cache.set("roles_" + username, userRoles, 3600);
116
+ cache.set("orgs_" + username, user.getOrgsIds(), 3600);
117
+ }
118
+ }
119
+ return userRoles == null ? 0 : userRoles.intValue();
120
+ }
124121
125
- // @Override
126
- public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
127
- // TODO Auto-generated method stub
128
- return null;
129
- }
122
+ // @Override
123
+ public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException {
124
+ return null;
125
+ }
130126
131127 }
securis/src/main/java/net/curisit/securis/services/ApiResource.java
....@@ -22,28 +22,26 @@
2222 @Path("/api")
2323 public class ApiResource {
2424
25
- @SuppressWarnings("unused")
26
- private static final Logger LOG = LogManager.getLogger(ApiResource.class);
25
+ @SuppressWarnings("unused")
26
+ private static final Logger LOG = LogManager.getLogger(ApiResource.class);
2727
28
- @Inject
29
- TokenHelper tokenHelper;
28
+ @Inject
29
+ TokenHelper tokenHelper;
3030
31
- @Inject
32
- Provider<EntityManager> emProvider;
31
+ @Inject
32
+ Provider<EntityManager> emProvider;
3333
34
- public ApiResource() {
35
- }
34
+ public ApiResource() {}
3635
37
- /**
38
- *
39
- * @return Simple text message to check API status
40
- */
41
- @GET
42
- @Path("/")
43
- @Produces(
44
- { MediaType.TEXT_PLAIN })
45
- public Response index() {
46
- return Response.ok("SeCuris API").build();
47
- }
36
+ /**
37
+ *
38
+ * @return Simple text message to check API status
39
+ */
40
+ @GET
41
+ @Path("/")
42
+ @Produces({ MediaType.TEXT_PLAIN })
43
+ public Response index() {
44
+ return Response.ok("SeCuris API").build();
45
+ }
4846
4947 }
securis/src/main/java/net/curisit/securis/services/ApplicationResource.java
....@@ -33,124 +33,125 @@
3333 import com.google.inject.persist.Transactional;
3434
3535 /**
36
- * Application resource, this service will provide methods to create, modify and delete applications
36
+ * Application resource, this service will provide methods to create, modify and
37
+ * delete applications
3738 *
3839 * @author roberto <roberto.sanchez@curisit.net>
3940 */
4041 @Path("/application")
4142 public class ApplicationResource {
4243
43
- @Inject
44
- TokenHelper tokenHelper;
44
+ @Inject
45
+ TokenHelper tokenHelper;
4546
46
- @Inject
47
- Provider<EntityManager> emProvider;
47
+ @Inject
48
+ Provider<EntityManager> emProvider;
4849
49
- private static final Logger LOG = LogManager.getLogger(ApplicationResource.class);
50
+ private static final Logger LOG = LogManager.getLogger(ApplicationResource.class);
5051
51
- public ApplicationResource() {
52
- }
52
+ public ApplicationResource() {}
5353
54
- /**
55
- *
56
- * @return the server version in format majorVersion.minorVersion
57
- */
58
- @GET
59
- @Path("/")
60
- @Produces(
61
- { MediaType.APPLICATION_JSON })
62
- public Response index() {
63
- LOG.info("Getting applications list ");
54
+ /**
55
+ *
56
+ * @return the server version in format majorVersion.minorVersion
57
+ */
58
+ @GET
59
+ @Path("/")
60
+ @Produces({ MediaType.APPLICATION_JSON })
61
+ public Response index() {
62
+ LOG.info("Getting applications list ");
6463
65
- EntityManager em = emProvider.get();
66
- TypedQuery<Application> q = em.createNamedQuery("list-applications", Application.class);
67
- List<Application> list = q.getResultList();
64
+ EntityManager em = emProvider.get();
65
+ TypedQuery<Application> q = em.createNamedQuery("list-applications", Application.class);
66
+ List<Application> list = q.getResultList();
6867
69
- return Response.ok(list).build();
70
- }
68
+ return Response.ok(list).build();
69
+ }
7170
72
- /**
73
- *
74
- * @return the server version in format majorVersion.minorVersion
75
- */
76
- @GET
77
- @Path("/{appid}")
78
- @Produces(
79
- { MediaType.APPLICATION_JSON })
80
- public Response get(@PathParam("appid") String appid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
81
- LOG.info("Getting application data for id: {}: ", appid);
82
- if (appid == null || appid.equals("")) {
83
- LOG.error("Application ID is mandatory");
84
- return Response.status(Status.NOT_FOUND).build();
85
- }
71
+ /**
72
+ *
73
+ * @return the server version in format majorVersion.minorVersion
74
+ */
75
+ @GET
76
+ @Path("/{appid}")
77
+ @Produces({ MediaType.APPLICATION_JSON })
78
+ public Response get(@PathParam("appid") String appid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
79
+ LOG.info("Getting application data for id: {}: ", appid);
80
+ if (appid == null || "".equals(appid)) {
81
+ LOG.error("Application ID is mandatory");
82
+ return Response.status(Status.NOT_FOUND).build();
83
+ }
8684
87
- EntityManager em = emProvider.get();
88
- Application app = em.find(Application.class, Integer.parseInt(appid));
89
- if (app == null) {
90
- LOG.error("Application with id {} not found in DB", appid);
85
+ EntityManager em = emProvider.get();
86
+ Application app = em.find(Application.class, Integer.parseInt(appid));
87
+ if (app == null) {
88
+ LOG.error("Application with id {} not found in DB", appid);
9189
92
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid).build();
93
- }
94
- return Response.ok(app).build();
95
- }
90
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid)
91
+ .build();
92
+ }
93
+ return Response.ok(app).build();
94
+ }
9695
97
- @POST
98
- @Path("/")
99
- @Consumes(MediaType.APPLICATION_JSON)
100
- @Produces(
101
- { MediaType.APPLICATION_JSON })
102
- @Transactional
103
- public Response create(Application app, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
104
- LOG.info("Creating new application");
105
- EntityManager em = emProvider.get();
106
- app.setCreationTimestamp(new Date());
107
- em.persist(app);
96
+ @POST
97
+ @Path("/")
98
+ @Consumes(MediaType.APPLICATION_JSON)
99
+ @Produces({ MediaType.APPLICATION_JSON })
100
+ @Transactional
101
+ public Response create(Application app, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
102
+ LOG.info("Creating new application");
103
+ EntityManager em = emProvider.get();
104
+ app.setCreationTimestamp(new Date());
105
+ em.persist(app);
108106
109
- return Response.ok(app).build();
110
- }
107
+ return Response.ok(app).build();
108
+ }
111109
112
- @PUT
113
- @POST
114
- @Path("/{appid}")
115
- @Transactional
116
- @Consumes(MediaType.APPLICATION_JSON)
117
- @Produces(
118
- { MediaType.APPLICATION_JSON })
119
- public Response modify(Application app, @PathParam("appid") String appid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
120
- LOG.info("Modifying application with id: {}", appid);
121
- EntityManager em = emProvider.get();
122
- Application currentapp = em.find(Application.class, Integer.parseInt(appid));
123
- if (currentapp == null) {
124
- LOG.error("Application with id {} not found in DB", appid);
125
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid).build();
126
- }
127
- currentapp.setName(app.getName());
128
- currentapp.setDescription(app.getDescription());
129
- em.persist(currentapp);
110
+ @PUT
111
+ @POST
112
+ @Path("/{appid}")
113
+ @Transactional
114
+ @Consumes(MediaType.APPLICATION_JSON)
115
+ @Produces({ MediaType.APPLICATION_JSON })
116
+ public Response modify(Application app, @PathParam("appid") String appid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
117
+ LOG.info("Modifying application with id: {}", appid);
118
+ EntityManager em = emProvider.get();
119
+ Application currentapp = em.find(Application.class, Integer.parseInt(appid));
120
+ if (currentapp == null) {
121
+ LOG.error("Application with id {} not found in DB", appid);
122
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid)
123
+ .build();
124
+ }
125
+ currentapp.setName(app.getName());
126
+ currentapp.setDescription(app.getDescription());
127
+ em.persist(currentapp);
130128
131
- return Response.ok(currentapp).build();
132
- }
129
+ return Response.ok(currentapp).build();
130
+ }
133131
134
- @DELETE
135
- @Path("/{appid}")
136
- @Transactional
137
- @Produces(
138
- { MediaType.APPLICATION_JSON })
139
- public Response delete(@PathParam("appid") String appid, @Context HttpServletRequest request) {
140
- LOG.info("Deleting app with id: {}", appid);
141
- EntityManager em = emProvider.get();
142
- Application app = em.find(Application.class, Integer.parseInt(appid));
143
- if (app == null) {
144
- LOG.error("Application with id {} can not be deleted, It was not found in DB", appid);
145
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid).build();
146
- }
132
+ @DELETE
133
+ @Path("/{appid}")
134
+ @Transactional
135
+ @Produces({ MediaType.APPLICATION_JSON })
136
+ public Response delete(@PathParam("appid") String appid, @Context HttpServletRequest request) {
137
+ LOG.info("Deleting app with id: {}", appid);
138
+ EntityManager em = emProvider.get();
139
+ Application app = em.find(Application.class, Integer.parseInt(appid));
140
+ if (app == null) {
141
+ LOG.error("Application with id {} can not be deleted, It was not found in DB", appid);
142
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application not found with ID: " + appid)
143
+ .build();
144
+ }
147145
148
- if (app.getLicenseTypes() != null && app.getLicenseTypes().size() > 0) {
149
- return Response.status(Status.FORBIDDEN).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application can not be deleted becasue has assigned one or more License types, ID: " + appid).build();
150
- }
146
+ if (app.getLicenseTypes() != null && app.getLicenseTypes().size() > 0) {
147
+ return Response
148
+ .status(Status.FORBIDDEN)
149
+ .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER,
150
+ "Application can not be deleted becasue has assigned one or more License types, ID: " + appid).build();
151
+ }
151152
152
- em.remove(app);
153
- return Response.ok(Utils.createMap("success", true, "id", appid)).build();
154
- }
153
+ em.remove(app);
154
+ return Response.ok(Utils.createMap("success", true, "id", appid)).build();
155
+ }
155156
156157 }
securis/src/main/java/net/curisit/securis/services/BasicServices.java
....@@ -36,90 +36,87 @@
3636 @Singleton
3737 public class BasicServices {
3838
39
- private static final Logger LOG = LogManager.getLogger(BasicServices.class);
39
+ private static final Logger LOG = LogManager.getLogger(BasicServices.class);
4040
41
- @Inject
42
- TokenHelper tokenHelper;
41
+ @Inject
42
+ TokenHelper tokenHelper;
4343
44
- @Inject
45
- public BasicServices() {
46
- }
44
+ @Inject
45
+ public BasicServices() {}
4746
48
- @GET
49
- @Path("/info")
50
- @Produces(
51
- { MediaType.TEXT_PLAIN })
52
- public Response info(@Context HttpServletRequest request) {
53
- return Response.ok().entity("License server running OK. Date: " + new Date()).build();
54
- }
47
+ @GET
48
+ @Path("/info")
49
+ @Produces({ MediaType.TEXT_PLAIN })
50
+ public Response info(@Context HttpServletRequest request) {
51
+ return Response.ok().entity("License server running OK. Date: " + new Date()).build();
52
+ }
5553
56
- @GET
57
- @Path("/{module:(admin)|(login)|(licenses)}")
58
- @Produces(
59
- { MediaType.TEXT_HTML })
60
- public Response init(@PathParam("module") String module, @Context HttpServletRequest request) {
61
- LOG.info("App index main.html");
62
- String page = "/main.html";
63
- URI uri = UriBuilder.fromUri(page).build();
64
- return Response.seeOther(uri).build();
65
- }
54
+ @GET
55
+ @Path("/{module:(admin)|(login)|(licenses)}")
56
+ @Produces({ MediaType.TEXT_HTML })
57
+ public Response init(@PathParam("module") String module, @Context HttpServletRequest request) {
58
+ LOG.info("App index main.html");
59
+ String page = "/main.html";
60
+ URI uri = UriBuilder.fromUri(page).build();
61
+ return Response.seeOther(uri).build();
62
+ }
6663
67
- @POST
68
- @Path("/login")
69
- @Produces(
70
- { MediaType.APPLICATION_JSON })
71
- public Response login(@FormParam("username") String user, @FormParam("password") String password, @Context HttpServletRequest request) {
72
- LOG.info("index session: " + request.getSession());
73
- LOG.info("user: {}, pass: {}", user, password);
74
- LOG.info("is user in role: {} == {} ? ", "advance", request.isUserInRole("advance"));
64
+ @POST
65
+ @Path("/login")
66
+ @Produces({ MediaType.APPLICATION_JSON })
67
+ public Response login(@FormParam("username") String user, @FormParam("password") String password, @Context HttpServletRequest request) {
68
+ LOG.info("index session: " + request.getSession());
69
+ LOG.info("user: {}, pass: {}", user, password);
70
+ LOG.info("is user in role: {} == {} ? ", "advance", request.isUserInRole("advance"));
7571
76
- if ("no".equals(password))
77
- return Response.status(Status.UNAUTHORIZED).build();
78
- String tokenAuth = tokenHelper.generateToken(user);
79
- return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();
80
- }
72
+ if ("no".equals(password)) {
73
+ // TODO: Code to text exception handling
74
+ return Response.status(Status.UNAUTHORIZED).build();
75
+ }
76
+ String tokenAuth = tokenHelper.generateToken(user);
77
+ return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();
78
+ }
8179
82
- /**
83
- * Check if current token is valid
84
- *
85
- * @param user
86
- * @param password
87
- * @param request
88
- * @return
89
- */
90
- @GET
91
- @Securable()
92
- @Path("/check")
93
- @Produces(
94
- { MediaType.APPLICATION_JSON })
95
- public Response check(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token, @QueryParam("token") String token2) {
96
- if (token == null)
97
- token = token2;
98
- if (token == null)
99
- return Response.status(Status.FORBIDDEN).build();
100
- boolean valid = tokenHelper.isTokenValid(token);
101
- if (!valid)
102
- return Response.status(Status.UNAUTHORIZED).build();
80
+ /**
81
+ * Check if current token is valid
82
+ *
83
+ * @param user
84
+ * @param password
85
+ * @param request
86
+ * @return
87
+ */
88
+ @GET
89
+ @Securable()
90
+ @Path("/check")
91
+ @Produces({ MediaType.APPLICATION_JSON })
92
+ public Response check(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token, @QueryParam("token") String token2) {
93
+ if (token == null) {
94
+ token = token2;
95
+ }
96
+ if (token == null) {
97
+ return Response.status(Status.FORBIDDEN).build();
98
+ }
99
+ boolean valid = tokenHelper.isTokenValid(token);
100
+ if (!valid) {
101
+ return Response.status(Status.UNAUTHORIZED).build();
102
+ }
103103
104
- // LOG.info("Token : " + token);
105
- String user = tokenHelper.extractUserFromToken(token);
106
- // LOG.info("Token user: " + user);
107
- Date date = tokenHelper.extractDateCreationFromToken(token);
108
- // LOG.info("Token date: " + date);
104
+ String user = tokenHelper.extractUserFromToken(token);
105
+ Date date = tokenHelper.extractDateCreationFromToken(token);
109106
110
- return Response.ok(Utils.createMap("valid", true, "user", user, "date", date)).build();
111
- }
107
+ return Response.ok(Utils.createMap("valid", true, "user", user, "date", date)).build();
108
+ }
112109
113
- @GET
114
- @POST
115
- @Path("/logout")
116
- @Produces(
117
- { MediaType.APPLICATION_JSON })
118
- public Response logout(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
119
- if (token == null)
120
- Response.status(Status.BAD_REQUEST).build();
121
- String user = tokenHelper.extractUserFromToken(token);
122
- LOG.info("User {} has logged out", user);
123
- return Response.ok().build();
124
- }
110
+ @GET
111
+ @POST
112
+ @Path("/logout")
113
+ @Produces({ MediaType.APPLICATION_JSON })
114
+ public Response logout(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
115
+ if (token == null) {
116
+ Response.status(Status.BAD_REQUEST).build();
117
+ }
118
+ String user = tokenHelper.extractUserFromToken(token);
119
+ LOG.info("User {} has logged out", user);
120
+ return Response.ok().build();
121
+ }
125122 }
securis/src/main/java/net/curisit/securis/services/LicenseResource.java
....@@ -40,317 +40,314 @@
4040 import com.google.inject.persist.Transactional;
4141
4242 /**
43
- * License resource, this service will provide methods to create, modify and delete licenses
43
+ * License resource, this service will provide methods to create, modify and
44
+ * delete licenses
4445 *
4546 * @author roberto <roberto.sanchez@curisit.net>
4647 */
4748 @Path("/license")
4849 public class LicenseResource {
4950
50
- private static final Logger LOG = LogManager.getLogger(LicenseResource.class);
51
+ private static final Logger LOG = LogManager.getLogger(LicenseResource.class);
5152
52
- @Inject
53
- TokenHelper tokenHelper;
53
+ @Inject
54
+ TokenHelper tokenHelper;
5455
55
- @Inject
56
- Provider<EntityManager> emProvider;
56
+ @Inject
57
+ Provider<EntityManager> emProvider;
5758
58
- public LicenseResource() {
59
- }
59
+ public LicenseResource() {}
6060
61
- /**
62
- *
63
- * @return the server version in format majorVersion.minorVersion
64
- */
65
- @GET
66
- @Path("/")
67
- @Securable
68
- @Produces(
69
- { MediaType.APPLICATION_JSON })
70
- public Response index(@QueryParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
71
- LOG.info("Getting licenses list ");
61
+ /**
62
+ *
63
+ * @return the server version in format majorVersion.minorVersion
64
+ */
65
+ @GET
66
+ @Path("/")
67
+ @Securable
68
+ @Produces({ MediaType.APPLICATION_JSON })
69
+ public Response index(@QueryParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
70
+ LOG.info("Getting licenses list ");
7271
73
- EntityManager em = emProvider.get();
72
+ EntityManager em = emProvider.get();
7473
75
- if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
76
- Pack pack = em.find(Pack.class, packId);
77
- if (pack == null)
78
- return Response.ok().build();
79
- if (!bsc.getOrganizationsIds().contains(pack.getOrganization().getId())) {
80
- LOG.error("Pack with id {} not accesible by user {}", pack, bsc.getUserPrincipal());
81
- return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack licenses").build();
82
- }
83
- }
84
- TypedQuery<License> q = em.createNamedQuery("list-licenses-by-pack", License.class);
85
- q.setParameter("packId", packId);
86
- List<License> list = q.getResultList();
74
+ if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
75
+ Pack pack = em.find(Pack.class, packId);
76
+ if (pack == null) {
77
+ return Response.ok().build();
78
+ }
79
+ if (!bsc.getOrganizationsIds().contains(pack.getOrganization().getId())) {
80
+ LOG.error("Pack with id {} not accesible by user {}", pack, bsc.getUserPrincipal());
81
+ return Response.status(Status.UNAUTHORIZED)
82
+ .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack licenses").build();
83
+ }
84
+ }
85
+ TypedQuery<License> q = em.createNamedQuery("list-licenses-by-pack", License.class);
86
+ q.setParameter("packId", packId);
87
+ List<License> list = q.getResultList();
8788
88
- return Response.ok(list).build();
89
- }
89
+ return Response.ok(list).build();
90
+ }
9091
91
- /**
92
- *
93
- * @return the server version in format majorVersion.minorVersion
94
- * @throws SeCurisServiceException
95
- */
96
- @GET
97
- @Path("/{licId}")
98
- @Securable
99
- @Produces(
100
- { MediaType.APPLICATION_JSON })
101
- public Response get(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
102
- LOG.info("Getting organization data for id: {}: ", licId);
92
+ /**
93
+ *
94
+ * @return the server version in format majorVersion.minorVersion
95
+ * @throws SeCurisServiceException
96
+ */
97
+ @GET
98
+ @Path("/{licId}")
99
+ @Securable
100
+ @Produces({ MediaType.APPLICATION_JSON })
101
+ public Response get(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
102
+ LOG.info("Getting organization data for id: {}: ", licId);
103103
104
- EntityManager em = emProvider.get();
105
- License lic = getCurrentLicense(licId, bsc, em);
106
- return Response.ok(lic).build();
107
- }
104
+ EntityManager em = emProvider.get();
105
+ License lic = getCurrentLicense(licId, bsc, em);
106
+ return Response.ok(lic).build();
107
+ }
108108
109
- /**
110
- *
111
- * @return The license file, only of license is active
112
- * @throws SeCurisServiceException
113
- */
114
- @GET
115
- @Path("/{licId}/download")
116
- @Securable
117
- @Produces(
118
- { MediaType.APPLICATION_OCTET_STREAM })
119
- public Response download(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
109
+ /**
110
+ *
111
+ * @return The license file, only of license is active
112
+ * @throws SeCurisServiceException
113
+ */
114
+ @GET
115
+ @Path("/{licId}/download")
116
+ @Securable
117
+ @Produces({ MediaType.APPLICATION_OCTET_STREAM })
118
+ public Response download(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
120119
121
- EntityManager em = emProvider.get();
122
- License lic = getCurrentLicense(licId, bsc, em);
120
+ EntityManager em = emProvider.get();
121
+ License lic = getCurrentLicense(licId, bsc, em);
123122
124
- if (lic.getLicenseData() == null) {
125
- LOG.error("License with id {} has not license file generated", licId, bsc.getUserPrincipal());
126
- throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License has not contain data to generate license file");
127
- }
128
- if (License.Status.isActionValid(License.Action.DOWNLOAD, lic.getStatus())) {
129
- LOG.error("License with id {} is not active, so It can not downloaded", licId, bsc.getUserPrincipal());
130
- throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License is not active, so It can not be downloaded");
131
- }
132
- return Response.ok(lic.getLicenseData()).build();
133
- }
123
+ if (lic.getLicenseData() == null) {
124
+ LOG.error("License with id {} has not license file generated", licId, bsc.getUserPrincipal());
125
+ throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License has not contain data to generate license file");
126
+ }
127
+ if (License.Status.isActionValid(License.Action.DOWNLOAD, lic.getStatus())) {
128
+ LOG.error("License with id {} is not active, so It can not downloaded", licId, bsc.getUserPrincipal());
129
+ throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License is not active, so It can not be downloaded");
130
+ }
131
+ return Response.ok(lic.getLicenseData()).build();
132
+ }
134133
135
- @PUT
136
- @POST
137
- @Path("/{licId}/activate")
138
- @Securable
139
- @Transactional
140
- @Consumes(MediaType.APPLICATION_JSON)
141
- @Produces(
142
- { MediaType.APPLICATION_JSON })
143
- public Response activate(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
134
+ @PUT
135
+ @POST
136
+ @Path("/{licId}/activate")
137
+ @Securable
138
+ @Transactional
139
+ @Consumes(MediaType.APPLICATION_JSON)
140
+ @Produces({ MediaType.APPLICATION_JSON })
141
+ public Response activate(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
144142
145
- EntityManager em = emProvider.get();
146
- License lic = getCurrentLicense(licId, bsc, em);
143
+ EntityManager em = emProvider.get();
144
+ License lic = getCurrentLicense(licId, bsc, em);
147145
148
- if (License.Status.isActionValid(License.Action.ACTIVATION, lic.getStatus())) {
149
- LOG.error("License with id {} can not be activated from current license status", licId);
150
- throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License with id " + licId + " can not be activated from the current license status");
151
- }
146
+ if (License.Status.isActionValid(License.Action.ACTIVATION, lic.getStatus())) {
147
+ LOG.error("License with id {} can not be activated from current license status", licId);
148
+ throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License with id " + licId
149
+ + " can not be activated from the current license status");
150
+ }
152151
153
- lic.setStatus(License.Status.ACTIVE);
154
- lic.setModificationTimestamp(new Date());
155
- em.persist(lic);
156
- User user = getUser(bsc.getUserPrincipal().getName(), em);
157
- em.persist(createLicenseHistoryAction(lic, user, LicenseHistory.Actions.ACTIVATE));
158
- return Response.ok(lic).build();
159
- }
152
+ lic.setStatus(License.Status.ACTIVE);
153
+ lic.setModificationTimestamp(new Date());
154
+ em.persist(lic);
155
+ User user = getUser(bsc.getUserPrincipal().getName(), em);
156
+ em.persist(createLicenseHistoryAction(lic, user, LicenseHistory.Actions.ACTIVATE));
157
+ return Response.ok(lic).build();
158
+ }
160159
161
- @PUT
162
- @POST
163
- @Path("/{licId}/send")
164
- @Securable
165
- @Transactional
166
- @Consumes(MediaType.APPLICATION_JSON)
167
- @Produces(
168
- { MediaType.APPLICATION_JSON })
169
- public Response send(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
160
+ @PUT
161
+ @POST
162
+ @Path("/{licId}/send")
163
+ @Securable
164
+ @Transactional
165
+ @Consumes(MediaType.APPLICATION_JSON)
166
+ @Produces({ MediaType.APPLICATION_JSON })
167
+ public Response send(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
170168
171
- EntityManager em = emProvider.get();
172
- License lic = getCurrentLicense(licId, bsc, em);
169
+ EntityManager em = emProvider.get();
170
+ License lic = getCurrentLicense(licId, bsc, em);
173171
174
- User user = getUser(bsc.getUserPrincipal().getName(), em);
175
- // TODO: Send mail with lic file
176
- lic.setModificationTimestamp(new Date());
177
- em.persist(lic);
178
- em.persist(createLicenseHistoryAction(lic, user, LicenseHistory.Actions.SEND, "Email sent to: " + lic.getEmail()));
179
- return Response.ok(lic).build();
180
- }
172
+ User user = getUser(bsc.getUserPrincipal().getName(), em);
173
+ // TODO: Send mail with lic file
174
+ lic.setModificationTimestamp(new Date());
175
+ em.persist(lic);
176
+ em.persist(createLicenseHistoryAction(lic, user, LicenseHistory.Actions.SEND, "Email sent to: " + lic.getEmail()));
177
+ return Response.ok(lic).build();
178
+ }
181179
182
- @PUT
183
- @POST
184
- @Path("/{licId}/cancel")
185
- @Securable
186
- @Transactional
187
- @Consumes(MediaType.APPLICATION_JSON)
188
- @Produces(
189
- { MediaType.APPLICATION_JSON })
190
- public Response cancel(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
180
+ @PUT
181
+ @POST
182
+ @Path("/{licId}/cancel")
183
+ @Securable
184
+ @Transactional
185
+ @Consumes(MediaType.APPLICATION_JSON)
186
+ @Produces({ MediaType.APPLICATION_JSON })
187
+ public Response cancel(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
191188
192
- EntityManager em = emProvider.get();
193
- License lic = getCurrentLicense(licId, bsc, em);
189
+ EntityManager em = emProvider.get();
190
+ License lic = getCurrentLicense(licId, bsc, em);
194191
195
- if (License.Status.isActionValid(License.Action.CANCEL, lic.getStatus())) {
196
- LOG.error("License with id {} can not be canceled from current license status", licId);
197
- throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License with id " + licId + " can not be canceled from the current license status");
198
- }
192
+ if (License.Status.isActionValid(License.Action.CANCEL, lic.getStatus())) {
193
+ LOG.error("License with id {} can not be canceled from current license status", licId);
194
+ throw new SeCurisServiceException(Status.FORBIDDEN.getStatusCode(), "License with id " + licId
195
+ + " can not be canceled from the current license status");
196
+ }
199197
200
- lic.setStatus(License.Status.CANCELED);
201
- lic.setModificationTimestamp(new Date());
202
- em.persist(lic);
198
+ lic.setStatus(License.Status.CANCELED);
199
+ lic.setModificationTimestamp(new Date());
200
+ em.persist(lic);
203201
204
- User user = getUser(bsc.getUserPrincipal().getName(), em);
205
- em.persist(createLicenseHistoryAction(lic, user, LicenseHistory.Actions.CANCEL));
206
- return Response.ok(lic).build();
207
- }
202
+ User user = getUser(bsc.getUserPrincipal().getName(), em);
203
+ em.persist(createLicenseHistoryAction(lic, user, LicenseHistory.Actions.CANCEL));
204
+ return Response.ok(lic).build();
205
+ }
208206
209
- @POST
210
- @Path("/")
211
- @Consumes(MediaType.APPLICATION_JSON)
212
- @Securable
213
- @Produces(
214
- { MediaType.APPLICATION_JSON })
215
- @Transactional
216
- public Response create(License lic, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
217
- LOG.info("Creating new license from create()");
218
- EntityManager em = emProvider.get();
219
- Pack pack = null;
220
- if (lic.getPackId() != null) {
221
- pack = em.find(Pack.class, lic.getPackId());
222
- if (pack == null) {
223
- LOG.error("License pack with id {} not found in DB", lic.getPackId());
224
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's pack not found with ID: " + lic.getPackId()).build();
225
- } else {
226
- if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
227
- if (!bsc.getOrganizationsIds().contains(pack.getOrganization().getId())) {
228
- LOG.error("License for pack with id {} can not be created by user {}", pack.getId(), bsc.getUserPrincipal());
229
- return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized action on pack license").build();
230
- }
231
- }
232
- }
233
- }
207
+ @POST
208
+ @Path("/")
209
+ @Consumes(MediaType.APPLICATION_JSON)
210
+ @Securable
211
+ @Produces({ MediaType.APPLICATION_JSON })
212
+ @Transactional
213
+ public Response create(License lic, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
214
+ LOG.info("Creating new license from create()");
215
+ EntityManager em = emProvider.get();
216
+ Pack pack = null;
217
+ if (lic.getPackId() != null) {
218
+ pack = em.find(Pack.class, lic.getPackId());
219
+ if (pack == null) {
220
+ LOG.error("License pack with id {} not found in DB", lic.getPackId());
221
+ return Response.status(Status.NOT_FOUND)
222
+ .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License's pack not found with ID: " + lic.getPackId()).build();
223
+ } else {
224
+ if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
225
+ if (!bsc.getOrganizationsIds().contains(pack.getOrganization().getId())) {
226
+ LOG.error("License for pack with id {} can not be created by user {}", pack.getId(), bsc.getUserPrincipal());
227
+ return Response.status(Status.UNAUTHORIZED)
228
+ .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized action on pack license").build();
229
+ }
230
+ }
231
+ }
232
+ }
234233
235
- User createdBy = getUser(bsc.getUserPrincipal().getName(), em);
234
+ User createdBy = getUser(bsc.getUserPrincipal().getName(), em);
236235
237
- // ODO: Manage status if request data is set
238
- lic.setCreatedBy(createdBy);
239
- lic.setStatus(License.Status.CREATED);
240
- lic.setCreationTimestamp(new Date());
241
- lic.setModificationTimestamp(lic.getCreationTimestamp());
242
- em.persist(lic);
243
- em.persist(createLicenseHistoryAction(lic, createdBy, LicenseHistory.Actions.CREATE));
236
+ // ODO: Manage status if request data is set
237
+ lic.setCreatedBy(createdBy);
238
+ lic.setStatus(License.Status.CREATED);
239
+ lic.setCreationTimestamp(new Date());
240
+ lic.setModificationTimestamp(lic.getCreationTimestamp());
241
+ em.persist(lic);
242
+ em.persist(createLicenseHistoryAction(lic, createdBy, LicenseHistory.Actions.CREATE));
244243
245
- return Response.ok(lic).build();
246
- }
244
+ return Response.ok(lic).build();
245
+ }
247246
248
- @POST
249
- @Path("/")
250
- @Consumes(MediaType.MULTIPART_FORM_DATA)
251
- @Securable
252
- @Produces(
253
- { MediaType.APPLICATION_JSON })
254
- @Transactional
255
- public Response createWithFile(MultipartFormDataInput mpfdi, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException {
256
- License lic = new License();
257
- lic.setCode(mpfdi.getFormDataPart("code", String.class, null));
258
- lic.setRequestData(mpfdi.getFormDataPart("request_data", String.class, null));
259
- lic.setPackId(mpfdi.getFormDataPart("pack_id", Integer.class, null));
260
- lic.setFullName(mpfdi.getFormDataPart("full_name", String.class, null));
261
- lic.setEmail(mpfdi.getFormDataPart("email", String.class, null));
262
- lic.setComments(mpfdi.getFormDataPart("comments", String.class, null));
247
+ @POST
248
+ @Path("/")
249
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
250
+ @Securable
251
+ @Produces({ MediaType.APPLICATION_JSON })
252
+ @Transactional
253
+ public Response createWithFile(MultipartFormDataInput mpfdi, @Context BasicSecurityContext bsc) throws IOException, SeCurisServiceException {
254
+ License lic = new License();
255
+ lic.setCode(mpfdi.getFormDataPart("code", String.class, null));
256
+ lic.setRequestData(mpfdi.getFormDataPart("request_data", String.class, null));
257
+ lic.setPackId(mpfdi.getFormDataPart("pack_id", Integer.class, null));
258
+ lic.setFullName(mpfdi.getFormDataPart("full_name", String.class, null));
259
+ lic.setEmail(mpfdi.getFormDataPart("email", String.class, null));
260
+ lic.setComments(mpfdi.getFormDataPart("comments", String.class, null));
263261
264
- return create(lic, bsc);
265
- }
262
+ return create(lic, bsc);
263
+ }
266264
267
- @PUT
268
- @POST
269
- @Path("/{licId}")
270
- @Securable
271
- @Transactional
272
- @Consumes(MediaType.APPLICATION_JSON)
273
- @Produces(
274
- { MediaType.APPLICATION_JSON })
275
- public Response modify(License lic, @PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
276
- LOG.info("Modifying organization with id: {}", licId);
265
+ @PUT
266
+ @POST
267
+ @Path("/{licId}")
268
+ @Securable
269
+ @Transactional
270
+ @Consumes(MediaType.APPLICATION_JSON)
271
+ @Produces({ MediaType.APPLICATION_JSON })
272
+ public Response modify(License lic, @PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
273
+ LOG.info("Modifying organization with id: {}", licId);
277274
278
- EntityManager em = emProvider.get();
275
+ EntityManager em = emProvider.get();
279276
280
- License currentLicense = getCurrentLicense(licId, bsc, em);
277
+ License currentLicense = getCurrentLicense(licId, bsc, em);
281278
282
- currentLicense.setCode(lic.getCode());
283
- currentLicense.setFullName(lic.getFullName());
284
- currentLicense.setEmail(lic.getEmail());
285
- currentLicense.setRequestData(lic.getRequestData());
286
- currentLicense.setModificationTimestamp(new Date());
287
- em.persist(currentLicense);
279
+ currentLicense.setCode(lic.getCode());
280
+ currentLicense.setFullName(lic.getFullName());
281
+ currentLicense.setEmail(lic.getEmail());
282
+ currentLicense.setRequestData(lic.getRequestData());
283
+ currentLicense.setModificationTimestamp(new Date());
284
+ em.persist(currentLicense);
288285
289
- return Response.ok(currentLicense).build();
290
- }
286
+ return Response.ok(currentLicense).build();
287
+ }
291288
292
- @DELETE
293
- @Path("/{licId}")
294
- @Transactional
295
- @Securable
296
- @Produces(
297
- { MediaType.APPLICATION_JSON })
298
- public Response delete(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
299
- LOG.info("Deleting license with id: {}", licId);
300
- EntityManager em = emProvider.get();
301
- License lic = getCurrentLicense(licId, bsc, em);
289
+ @DELETE
290
+ @Path("/{licId}")
291
+ @Transactional
292
+ @Securable
293
+ @Produces({ MediaType.APPLICATION_JSON })
294
+ public Response delete(@PathParam("licId") Integer licId, @Context BasicSecurityContext bsc) throws SeCurisServiceException {
295
+ LOG.info("Deleting license with id: {}", licId);
296
+ EntityManager em = emProvider.get();
297
+ License lic = getCurrentLicense(licId, bsc, em);
302298
303
- if (lic.getStatus() != License.Status.CANCELED || lic.getStatus() != License.Status.CREATED) {
304
- LOG.error("License {} can not be deleted with status {}", lic.getCode(), lic.getStatus());
305
- return Response.status(Status.FORBIDDEN).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License can not be deleted in current status").build();
306
- }
299
+ if (lic.getStatus() != License.Status.CANCELED || lic.getStatus() != License.Status.CREATED) {
300
+ LOG.error("License {} can not be deleted with status {}", lic.getCode(), lic.getStatus());
301
+ return Response.status(Status.FORBIDDEN)
302
+ .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License can not be deleted in current status").build();
303
+ }
307304
308
- em.remove(lic);
309
- return Response.ok(Utils.createMap("success", true, "id", licId)).build();
310
- }
305
+ em.remove(lic);
306
+ return Response.ok(Utils.createMap("success", true, "id", licId)).build();
307
+ }
311308
312
- private License getCurrentLicense(Integer licId, BasicSecurityContext bsc, EntityManager em) throws SeCurisServiceException {
313
- if (licId == null || licId.equals("")) {
314
- LOG.error("License ID is mandatory");
315
- throw new SeCurisServiceException(Status.NOT_FOUND.getStatusCode(), "Missing license ID");
316
- }
309
+ private License getCurrentLicense(Integer licId, BasicSecurityContext bsc, EntityManager em) throws SeCurisServiceException {
310
+ if (licId == null || "".equals(licId)) {
311
+ LOG.error("License ID is mandatory");
312
+ throw new SeCurisServiceException(Status.NOT_FOUND.getStatusCode(), "Missing license ID");
313
+ }
317314
318
- License lic = em.find(License.class, licId);
319
- if (lic == null) {
320
- LOG.error("License with id {} not found in DB", licId);
321
- throw new SeCurisServiceException(Status.NOT_FOUND.getStatusCode(), "License not found for ID: " + licId);
322
- }
323
- if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
324
- if (!bsc.getOrganizationsIds().contains(lic.getPack().getOrganization().getId())) {
325
- LOG.error("License with id {} is not accesible by user {}", licId, bsc.getUserPrincipal());
326
- throw new SeCurisServiceException(Status.UNAUTHORIZED.getStatusCode(), "Unathorized access to license data");
327
- }
328
- }
329
- return lic;
330
- }
315
+ License lic = em.find(License.class, licId);
316
+ if (lic == null) {
317
+ LOG.error("License with id {} not found in DB", licId);
318
+ throw new SeCurisServiceException(Status.NOT_FOUND.getStatusCode(), "License not found for ID: " + licId);
319
+ }
320
+ if (!bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
321
+ if (!bsc.getOrganizationsIds().contains(lic.getPack().getOrganization().getId())) {
322
+ LOG.error("License with id {} is not accesible by user {}", licId, bsc.getUserPrincipal());
323
+ throw new SeCurisServiceException(Status.UNAUTHORIZED.getStatusCode(), "Unathorized access to license data");
324
+ }
325
+ }
326
+ return lic;
327
+ }
331328
332
- private User getUser(String username, EntityManager em) throws SeCurisServiceException {
333
- User user = null;
334
- if (username != null) {
335
- user = em.find(User.class, username);
336
- if (user == null) {
337
- throw new SeCurisServiceException(Status.NOT_FOUND.getStatusCode(), "User not found with username: " + username);
338
- }
339
- }
340
- return user;
341
- }
329
+ private User getUser(String username, EntityManager em) throws SeCurisServiceException {
330
+ User user = null;
331
+ if (username != null) {
332
+ user = em.find(User.class, username);
333
+ if (user == null) {
334
+ throw new SeCurisServiceException(Status.NOT_FOUND.getStatusCode(), "User not found with username: " + username);
335
+ }
336
+ }
337
+ return user;
338
+ }
342339
343
- private LicenseHistory createLicenseHistoryAction(License lic, User user, String action, String comments) {
344
- LicenseHistory lh = new LicenseHistory();
345
- lh.setLicense(lic);
346
- lh.setUser(user);
347
- lh.setTimestamp(new Date());
348
- lh.setAction(action);
349
- lh.setComments(comments);
350
- return lh;
351
- }
340
+ private LicenseHistory createLicenseHistoryAction(License lic, User user, String action, String comments) {
341
+ LicenseHistory lh = new LicenseHistory();
342
+ lh.setLicense(lic);
343
+ lh.setUser(user);
344
+ lh.setTimestamp(new Date());
345
+ lh.setAction(action);
346
+ lh.setComments(comments);
347
+ return lh;
348
+ }
352349
353
- private LicenseHistory createLicenseHistoryAction(License lic, User user, String action) {
354
- return createLicenseHistoryAction(lic, user, action, null);
355
- }
350
+ private LicenseHistory createLicenseHistoryAction(License lic, User user, String action) {
351
+ return createLicenseHistoryAction(lic, user, action, null);
352
+ }
356353 }
securis/src/main/java/net/curisit/securis/services/LicenseServices.java
....@@ -32,99 +32,95 @@
3232 @Path("/test")
3333 public class LicenseServices {
3434
35
- // private LicenseHelper licenseHelper = InjectorFactory.getInjector().getInstance(LicenseHelper.class);
36
- private static final Logger LOG = LogManager.getLogger(LicenseServices.class);
35
+ private static final Logger LOG = LogManager.getLogger(LicenseServices.class);
3736
38
- private static final int DEFAULT_LICENSE_EXPIRATION = 365;
39
- private static final String LICENSE_STRING = "CurisIntegrity Config Server v{0}.{1}";
37
+ private static final int DEFAULT_LICENSE_EXPIRATION = 365;
38
+ private static final String LICENSE_STRING = "CurisIntegrity Config Server v{0}.{1}";
4039
41
- @com.google.inject.Inject
42
- @Named("base-uri")
43
- private URI uri;
40
+ @com.google.inject.Inject
41
+ @Named("base-uri")
42
+ private URI uri;
4443
45
- public LicenseServices() {
44
+ public LicenseServices() {
4645
47
- }
46
+ }
4847
49
- /**
50
- *
51
- * @return the server version in format majorVersion.minorVersion
52
- */
53
- @GET
54
- @Produces(
55
- { MediaType.TEXT_HTML })
56
- public Response index() {
57
- try {
58
- String index = IOUtils.toString(this.getClass().getResourceAsStream("/static/index.html"));
59
- return Response.ok().entity(index).build();
60
- } catch (IOException e) {
61
- LOG.error("Error getting index.html", e);
62
- }
63
- return Response.ok().entity(MessageFormat.format(LICENSE_STRING, 0, 1)).build();
64
- }
48
+ /**
49
+ *
50
+ * @return the server version in format majorVersion.minorVersion
51
+ */
52
+ @GET
53
+ @Produces({ MediaType.TEXT_HTML })
54
+ public Response index() {
55
+ try {
56
+ String index = IOUtils.toString(this.getClass().getResourceAsStream("/static/index.html"));
57
+ return Response.ok().entity(index).build();
58
+ } catch (IOException e) {
59
+ LOG.error("Error getting index.html", e);
60
+ }
61
+ return Response.ok().entity(MessageFormat.format(LICENSE_STRING, 0, 1)).build();
62
+ }
6563
66
- @GET
67
- @Path("/dummy")
68
- @Produces(
69
- { MediaType.TEXT_PLAIN })
70
- public Response dummy(@Context HttpServletRequest request) {
71
- LOG.info("Request: " + request.getPathInfo());
72
- return Response.ok().entity((uri == null)).build();
73
- }
64
+ @GET
65
+ @Path("/dummy")
66
+ @Produces({ MediaType.TEXT_PLAIN })
67
+ public Response dummy(@Context HttpServletRequest request) {
68
+ LOG.info("Request: " + request.getPathInfo());
69
+ return Response.ok().entity((uri == null)).build();
70
+ }
7471
75
- /**
76
- * @return the version of the three entities that can be synchronized (Users, DataSet and Settings)
77
- */
78
- @POST
79
- @Path("/upload1")
80
- @Consumes(MediaType.MULTIPART_FORM_DATA)
81
- @Produces(
82
- { MediaType.APPLICATION_JSON })
83
- public Response testFile1(@MultipartForm FileUploadForm mfdi) {
84
- LOG.info("FORM: texto: {}, file: {}", mfdi.getTexto(), new String(mfdi.getFile()));
85
- return Response.ok("OK").build();
86
- }
72
+ /**
73
+ * @return the version of the three entities that can be synchronized
74
+ * (Users, DataSet and Settings)
75
+ */
76
+ @POST
77
+ @Path("/upload1")
78
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
79
+ @Produces({ MediaType.APPLICATION_JSON })
80
+ public Response testFile1(@MultipartForm FileUploadForm mfdi) {
81
+ LOG.info("FORM: texto: {}, file: {}", mfdi.getTexto(), new String(mfdi.getFile()));
82
+ return Response.ok("OK").build();
83
+ }
8784
88
- @GET
89
- @Path("/current/{license}")
90
- @Produces(
91
- { MediaType.APPLICATION_JSON })
92
- public ServiceResponse<ServerConfigVersions> testFile(@PathParam("license") String license, @DefaultValue("-1") @QueryParam("minorVersion") int minorVersion, @DefaultValue("-1") @QueryParam("majorVersion") int majorVersion) {
85
+ @GET
86
+ @Path("/current/{license}")
87
+ @Produces({ MediaType.APPLICATION_JSON })
88
+ public ServiceResponse<ServerConfigVersions> testFile(@PathParam("license") String license,
89
+ @DefaultValue("-1") @QueryParam("minorVersion") int minorVersion, @DefaultValue("-1") @QueryParam("majorVersion") int majorVersion) {
9390
94
- LOG.info("Called 'current' service with license: {}", license);
95
- ServiceResponse<ServerConfigVersions> response = new ServiceResponse<ServerConfigVersions>();
91
+ LOG.info("Called 'current' service with license: {}", license);
92
+ ServiceResponse<ServerConfigVersions> response = new ServiceResponse<ServerConfigVersions>();
9693
97
- return response;
98
- }
94
+ return response;
95
+ }
9996
100
- public static class FileUploadForm {
97
+ public static class FileUploadForm {
10198
102
- @FormParam("file1")
103
- @PartType("application/octet-stream")
104
- private byte[] file;
99
+ @FormParam("file1")
100
+ @PartType("application/octet-stream")
101
+ private byte[] file;
105102
106
- @FormParam("texto1")
107
- @PartType("text/plain")
108
- private String texto;
103
+ @FormParam("texto1")
104
+ @PartType("text/plain")
105
+ private String texto;
109106
110
- public FileUploadForm() {
111
- }
107
+ public FileUploadForm() {}
112108
113
- public byte[] getFile() {
114
- return file;
115
- }
109
+ public byte[] getFile() {
110
+ return file;
111
+ }
116112
117
- public void setFile(byte[] file) {
118
- this.file = file;
119
- }
113
+ public void setFile(byte[] file) {
114
+ this.file = file;
115
+ }
120116
121
- public void setTexto(final String texto) {
122
- this.texto = texto;
123
- }
117
+ public void setTexto(final String texto) {
118
+ this.texto = texto;
119
+ }
124120
125
- public String getTexto() {
126
- return texto;
127
- }
121
+ public String getTexto() {
122
+ return texto;
123
+ }
128124
129
- }
125
+ }
130126 }
securis/src/main/java/net/curisit/securis/services/LicenseTypeResource.java
....@@ -35,152 +35,149 @@
3535 import com.google.inject.persist.Transactional;
3636
3737 /**
38
- * LicenseType resource, this service will provide methods to create, modify and delete license types
38
+ * LicenseType resource, this service will provide methods to create, modify and
39
+ * delete license types
3940 *
4041 * @author roberto <roberto.sanchez@curisit.net>
4142 */
4243 @Path("/licensetype")
4344 public class LicenseTypeResource {
4445
45
- private static final Logger LOG = LogManager.getLogger(LicenseTypeResource.class);
46
+ private static final Logger LOG = LogManager.getLogger(LicenseTypeResource.class);
4647
47
- @Inject
48
- TokenHelper tokenHelper;
48
+ @Inject
49
+ TokenHelper tokenHelper;
4950
50
- @Inject
51
- Provider<EntityManager> emProvider;
51
+ @Inject
52
+ Provider<EntityManager> emProvider;
5253
53
- public LicenseTypeResource() {
54
- }
54
+ public LicenseTypeResource() {}
5555
56
- /**
57
- *
58
- * @return the server version in format majorVersion.minorVersion
59
- */
60
- @GET
61
- @Path("/")
62
- @Produces(
63
- { MediaType.APPLICATION_JSON })
64
- public Response index() {
65
- LOG.info("Getting license types list ");
56
+ /**
57
+ *
58
+ * @return the server version in format majorVersion.minorVersion
59
+ */
60
+ @GET
61
+ @Path("/")
62
+ @Produces({ MediaType.APPLICATION_JSON })
63
+ public Response index() {
64
+ LOG.info("Getting license types list ");
6665
67
- EntityManager em = emProvider.get();
68
- TypedQuery<LicenseType> q = em.createNamedQuery("list-license_types", LicenseType.class);
69
- List<LicenseType> list = q.getResultList();
66
+ EntityManager em = emProvider.get();
67
+ TypedQuery<LicenseType> q = em.createNamedQuery("list-license_types", LicenseType.class);
68
+ List<LicenseType> list = q.getResultList();
7069
71
- return Response.ok(list).build();
72
- }
70
+ return Response.ok(list).build();
71
+ }
7372
74
- /**
75
- *
76
- * @return the server version in format majorVersion.minorVersion
77
- */
78
- @GET
79
- @Path("/{ltid}")
80
- @Produces(
81
- { MediaType.APPLICATION_JSON })
82
- public Response get(@PathParam("ltid") String ltid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
83
- LOG.info("Getting license type data for id: {}: ", ltid);
84
- if (ltid == null || ltid.equals("")) {
85
- LOG.error("LicenseType ID is mandatory");
86
- return Response.status(Status.NOT_FOUND).build();
87
- }
73
+ /**
74
+ *
75
+ * @return the server version in format majorVersion.minorVersion
76
+ */
77
+ @GET
78
+ @Path("/{ltid}")
79
+ @Produces({ MediaType.APPLICATION_JSON })
80
+ public Response get(@PathParam("ltid") String ltid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
81
+ LOG.info("Getting license type data for id: {}: ", ltid);
82
+ if (ltid == null || "".equals(ltid)) {
83
+ LOG.error("LicenseType ID is mandatory");
84
+ return Response.status(Status.NOT_FOUND).build();
85
+ }
8886
89
- EntityManager em = emProvider.get();
90
- LicenseType lt = em.find(LicenseType.class, Integer.parseInt(ltid));
91
- if (lt == null) {
92
- LOG.error("LicenseType with id {} not found in DB", ltid);
93
- return Response.status(Status.NOT_FOUND).build();
94
- }
95
- return Response.ok(lt).build();
96
- }
87
+ EntityManager em = emProvider.get();
88
+ LicenseType lt = em.find(LicenseType.class, Integer.parseInt(ltid));
89
+ if (lt == null) {
90
+ LOG.error("LicenseType with id {} not found in DB", ltid);
91
+ return Response.status(Status.NOT_FOUND).build();
92
+ }
93
+ return Response.ok(lt).build();
94
+ }
9795
98
- @POST
99
- @Path("/")
100
- @Consumes(MediaType.APPLICATION_JSON)
101
- @Produces(
102
- { MediaType.APPLICATION_JSON })
103
- @Transactional
104
- public Response create(LicenseType lt, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
105
- LOG.info("Creating new license type");
106
- EntityManager em = emProvider.get();
96
+ @POST
97
+ @Path("/")
98
+ @Consumes(MediaType.APPLICATION_JSON)
99
+ @Produces({ MediaType.APPLICATION_JSON })
100
+ @Transactional
101
+ public Response create(LicenseType lt, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
102
+ LOG.info("Creating new license type");
103
+ EntityManager em = emProvider.get();
107104
108
- try {
109
- setApplication(lt, lt.getApplicationId(), em);
110
- } catch (SeCurisException e) {
111
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
112
- }
113
-
114
- if (lt.getApplicationId() == null) {
115
- LOG.error("Application is missing for current license type data");
116
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application is missing for current license type data").build();
117
- }
105
+ try {
106
+ setApplication(lt, lt.getApplicationId(), em);
107
+ } catch (SeCurisException e) {
108
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
109
+ }
118110
119
- lt.setCreationTimestamp(new Date());
120
- em.persist(lt);
111
+ if (lt.getApplicationId() == null) {
112
+ LOG.error("Application is missing for current license type data");
113
+ return Response.status(Status.NOT_FOUND)
114
+ .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Application is missing for current license type data").build();
115
+ }
121116
122
- return Response.ok(lt).build();
123
- }
117
+ lt.setCreationTimestamp(new Date());
118
+ em.persist(lt);
124119
125
- @PUT
126
- @POST
127
- @Path("/{ltid}")
128
- @Transactional
129
- @Consumes(MediaType.APPLICATION_JSON)
130
- @Produces(
131
- { MediaType.APPLICATION_JSON })
132
- public Response modify(LicenseType lt, @PathParam("ltid") String ltid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
133
- LOG.info("Modifying license type with id: {}", ltid);
134
- EntityManager em = emProvider.get();
135
- LicenseType currentlt = em.find(LicenseType.class, Integer.parseInt(ltid));
136
- if (currentlt == null) {
137
- LOG.error("LicenseType with id {} not found in DB", ltid);
138
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License type not found with ID: " + ltid).build();
139
- }
120
+ return Response.ok(lt).build();
121
+ }
140122
141
- try {
142
- setApplication(currentlt, lt.getApplicationId(), em);
143
- } catch (SeCurisException e) {
144
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
145
- }
146
-
147
- currentlt.setCode(lt.getCode());
148
- currentlt.setName(lt.getName());
149
- currentlt.setDescription(lt.getDescription());
150
- em.persist(currentlt);
123
+ @PUT
124
+ @POST
125
+ @Path("/{ltid}")
126
+ @Transactional
127
+ @Consumes(MediaType.APPLICATION_JSON)
128
+ @Produces({ MediaType.APPLICATION_JSON })
129
+ public Response modify(LicenseType lt, @PathParam("ltid") String ltid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
130
+ LOG.info("Modifying license type with id: {}", ltid);
131
+ EntityManager em = emProvider.get();
132
+ LicenseType currentlt = em.find(LicenseType.class, Integer.parseInt(ltid));
133
+ if (currentlt == null) {
134
+ LOG.error("LicenseType with id {} not found in DB", ltid);
135
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "License type not found with ID: " + ltid)
136
+ .build();
137
+ }
151138
152
- return Response.ok(currentlt).build();
153
- }
139
+ try {
140
+ setApplication(currentlt, lt.getApplicationId(), em);
141
+ } catch (SeCurisException e) {
142
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
143
+ }
154144
155
- private void setApplication(LicenseType licType, Integer applicationId, EntityManager em) throws SeCurisException {
156
- Application app = null;
157
- if (applicationId != null) {
158
- app = em.find(Application.class, applicationId);
159
- if (app == null) {
160
- LOG.error("LicenseType application with id {} not found in DB", applicationId);
161
-
162
- throw new SecurityException("License type's app not found with ID: " + applicationId);
163
- }
164
- }
165
- licType.setApplication(app);
166
- }
145
+ currentlt.setCode(lt.getCode());
146
+ currentlt.setName(lt.getName());
147
+ currentlt.setDescription(lt.getDescription());
148
+ em.persist(currentlt);
167149
168
- @DELETE
169
- @Path("/{ltid}")
170
- @Transactional
171
- @Produces(
172
- { MediaType.APPLICATION_JSON })
173
- public Response delete(@PathParam("ltid") String ltid, @Context HttpServletRequest request) {
174
- LOG.info("Deleting app with id: {}", ltid);
175
- EntityManager em = emProvider.get();
176
- LicenseType app = em.find(LicenseType.class, Integer.parseInt(ltid));
177
- if (app == null) {
178
- LOG.error("LicenseType with id {} can not be deleted, It was not found in DB", ltid);
179
- return Response.status(Status.NOT_FOUND).build();
180
- }
150
+ return Response.ok(currentlt).build();
151
+ }
181152
182
- em.remove(app);
183
- return Response.ok(Utils.createMap("success", true, "id", ltid)).build();
184
- }
153
+ private void setApplication(LicenseType licType, Integer applicationId, EntityManager em) throws SeCurisException {
154
+ Application app = null;
155
+ if (applicationId != null) {
156
+ app = em.find(Application.class, applicationId);
157
+ if (app == null) {
158
+ LOG.error("LicenseType application with id {} not found in DB", applicationId);
159
+
160
+ throw new SecurityException("License type's app not found with ID: " + applicationId);
161
+ }
162
+ }
163
+ licType.setApplication(app);
164
+ }
165
+
166
+ @DELETE
167
+ @Path("/{ltid}")
168
+ @Transactional
169
+ @Produces({ MediaType.APPLICATION_JSON })
170
+ public Response delete(@PathParam("ltid") String ltid, @Context HttpServletRequest request) {
171
+ LOG.info("Deleting app with id: {}", ltid);
172
+ EntityManager em = emProvider.get();
173
+ LicenseType app = em.find(LicenseType.class, Integer.parseInt(ltid));
174
+ if (app == null) {
175
+ LOG.error("LicenseType with id {} can not be deleted, It was not found in DB", ltid);
176
+ return Response.status(Status.NOT_FOUND).build();
177
+ }
178
+
179
+ em.remove(app);
180
+ return Response.ok(Utils.createMap("success", true, "id", ltid)).build();
181
+ }
185182
186183 }
securis/src/main/java/net/curisit/securis/services/OrganizationResource.java
....@@ -40,231 +40,223 @@
4040 import com.google.inject.persist.Transactional;
4141
4242 /**
43
- * Organization resource, this service will provide methods to create, modify and delete organizations
43
+ * Organization resource, this service will provide methods to create, modify
44
+ * and delete organizations
4445 *
4546 * @author roberto <roberto.sanchez@curisit.net>
4647 */
4748 @Path("/organization")
4849 public class OrganizationResource {
4950
50
- private static final Logger LOG = LogManager.getLogger(OrganizationResource.class);
51
+ private static final Logger LOG = LogManager.getLogger(OrganizationResource.class);
5152
52
- @Inject
53
- private Provider<EntityManager> emProvider;
53
+ @Inject
54
+ private Provider<EntityManager> emProvider;
5455
55
- public OrganizationResource() {
56
- }
56
+ public OrganizationResource() {}
5757
58
- /**
59
- *
60
- * @return the server version in format majorVersion.minorVersion
61
- */
62
- @GET
63
- @Path("/")
64
- @Produces(
65
- { MediaType.APPLICATION_JSON })
66
- @Securable
67
- // @RolesAllowed(SecurityContextWrapper.ROL_ADVANCE)
68
- public Response index(@Context BasicSecurityContext bsc) {
69
- LOG.info("Getting organizations list ");
58
+ /**
59
+ *
60
+ * @return the server version in format majorVersion.minorVersion
61
+ */
62
+ @GET
63
+ @Path("/")
64
+ @Produces({ MediaType.APPLICATION_JSON })
65
+ @Securable
66
+ public Response index(@Context BasicSecurityContext bsc) {
67
+ LOG.info("Getting organizations list ");
7068
71
- // LOG.info("User orgs: {}", request.getAttribute("oser_orgs"));
72
- BasicSecurityContext bsc2 = ResteasyProviderFactory.getContextData(BasicSecurityContext.class);
73
- LOG.info("bsc: {}", bsc);
74
- LOG.info("bsc2: {}", bsc2);
75
- // LOG.info("securityContext: {}", scw);
76
- LOG.info("securityContext ROL_ADMIN?: {}", bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN));
77
- EntityManager em = emProvider.get();
78
- TypedQuery<Organization> q;
79
- if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
80
- LOG.info("GEtting all orgs for user: " + bsc.getUserPrincipal());
81
- q = em.createNamedQuery("list-organizations", Organization.class);
82
- } else {
83
- q = em.createNamedQuery("list-organizations", Organization.class);
84
- // if (securityContext.getOrganizationsIds() == null)
85
- // Response.ok().build();
86
- // LOG.info("Getting only {} orgs for user: {}", securityContext.getOrganizationsIds(), securityContext.getUserPrincipal());
87
- // q = em.createNamedQuery("list-organizations-by-ids", Organization.class);
88
- // q.setParameter("list_ids", securityContext.getOrganizationsIds());
89
- }
69
+ BasicSecurityContext bsc2 = ResteasyProviderFactory.getContextData(BasicSecurityContext.class);
70
+ LOG.debug("securityContext ROL_ADMIN?: {}", bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN));
71
+ EntityManager em = emProvider.get();
72
+ TypedQuery<Organization> q;
73
+ if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
74
+ LOG.info("GEtting all orgs for user: " + bsc.getUserPrincipal());
75
+ q = em.createNamedQuery("list-organizations", Organization.class);
76
+ } else {
77
+ q = em.createNamedQuery("list-organizations", Organization.class);
78
+ }
9079
91
- List<Organization> list = q.getResultList();
80
+ List<Organization> list = q.getResultList();
9281
93
- return Response.ok(list).build();
94
- }
82
+ return Response.ok(list).build();
83
+ }
9584
96
- /**
97
- *
98
- * @return the server version in format majorVersion.minorVersion
99
- */
100
- @GET
101
- @Path("/{orgid}")
102
- @Produces(
103
- { MediaType.APPLICATION_JSON })
104
- @Securable
105
- public Response get(@PathParam("orgid") String orgid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
106
- LOG.info("Getting organization data for id: {}: ", orgid);
107
- if (orgid == null || orgid.equals("")) {
108
- LOG.error("Organization ID is mandatory");
109
- return Response.status(Status.NOT_FOUND).build();
110
- }
111
- // if (!securityContext.isOrgAccesible(Integer.parseInt(orgid))) {
112
- // LOG.error("Organization with id {} not accessible for user: {}", orgid, securityContext.getUserPrincipal());
113
- // return Response.status(Status.UNAUTHORIZED).build();
114
- // }
85
+ /**
86
+ *
87
+ * @return the server version in format majorVersion.minorVersion
88
+ */
89
+ @GET
90
+ @Path("/{orgid}")
91
+ @Produces({ MediaType.APPLICATION_JSON })
92
+ @Securable
93
+ public Response get(@PathParam("orgid") String orgid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
94
+ LOG.info("Getting organization data for id: {}: ", orgid);
95
+ if (orgid == null || "".equals(orgid)) {
96
+ LOG.error("Organization ID is mandatory");
97
+ return Response.status(Status.NOT_FOUND).build();
98
+ }
11599
116
- EntityManager em = emProvider.get();
117
- Organization org = em.find(Organization.class, Integer.parseInt(orgid));
118
- if (org == null) {
119
- LOG.error("Organization with id {} not found in DB", orgid);
120
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization not found, id: " + orgid).build();
121
- }
122
- return Response.ok(org).build();
123
- }
100
+ EntityManager em = emProvider.get();
101
+ Organization org = em.find(Organization.class, Integer.parseInt(orgid));
102
+ if (org == null) {
103
+ LOG.error("Organization with id {} not found in DB", orgid);
104
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization not found, id: " + orgid)
105
+ .build();
106
+ }
107
+ return Response.ok(org).build();
108
+ }
124109
125
- private boolean isCyclicalRelationship(int currentId, Organization parent) {
126
- while (parent != null) {
127
- if (parent.getId() == currentId)
128
- return true;
129
- parent = parent.getParentOrganization();
130
- }
131
- return false;
132
- }
110
+ private boolean isCyclicalRelationship(int currentId, Organization parent) {
111
+ while (parent != null) {
112
+ if (parent.getId() == currentId) {
113
+ return true;
114
+ }
115
+ parent = parent.getParentOrganization();
116
+ }
117
+ return false;
118
+ }
133119
134
- @POST
135
- @Path("/")
136
- @Consumes(MediaType.APPLICATION_JSON)
137
- @Produces(
138
- { MediaType.APPLICATION_JSON })
139
- @Transactional
140
- @Securable
141
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
142
- public Response create(Organization org, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
143
- LOG.info("Creating new organization");
144
- EntityManager em = emProvider.get();
145
-
146
- try {
147
- this.setParentOrg(org, org.getParentOrgId(), em);
148
- } catch (SeCurisException e) {
149
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
150
- }
151
-
152
- List<User> users = null;
153
- List<String> usersIds = org.getUsersIds();
154
- if (usersIds != null && usersIds.size() > 0) {
155
- users = new ArrayList<>();
156
- for (String username : usersIds) {
157
- User user = em.find(User.class, username);
158
- if (user == null) {
159
- LOG.error("Organization user with id {} not found in DB", username);
160
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization's user not found with ID: " + username).build();
161
- }
162
- users.add(user);
163
- }
164
- }
120
+ @POST
121
+ @Path("/")
122
+ @Consumes(MediaType.APPLICATION_JSON)
123
+ @Produces({ MediaType.APPLICATION_JSON })
124
+ @Transactional
125
+ @Securable
126
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
127
+ public Response create(Organization org, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
128
+ LOG.info("Creating new organization");
129
+ EntityManager em = emProvider.get();
165130
166
- org.setUsers(users);
167
- org.setCreationTimestamp(new Date());
168
- em.persist(org);
131
+ try {
132
+ this.setParentOrg(org, org.getParentOrgId(), em);
133
+ } catch (SeCurisException e) {
134
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
135
+ }
169136
170
- return Response.ok(org).build();
171
- }
172
-
173
- private void setParentOrg(Organization org, Integer parentOrgId, EntityManager em) throws SeCurisException {
174
- Organization parentOrg = null;
175
- if (parentOrgId != null) {
176
- parentOrg = em.find(Organization.class, parentOrgId);
177
- if (parentOrg == null) {
178
- LOG.error("Organization parent with id {} not found in DB", org.getParentOrgId());
179
- throw new SecurityException("Organization's parent not found with ID: " + org.getParentOrgId());
180
- }
181
- }
137
+ List<User> users = null;
138
+ List<String> usersIds = org.getUsersIds();
139
+ if (usersIds != null && usersIds.size() > 0) {
140
+ users = new ArrayList<>();
141
+ for (String username : usersIds) {
142
+ User user = em.find(User.class, username);
143
+ if (user == null) {
144
+ LOG.error("Organization user with id {} not found in DB", username);
145
+ return Response.status(Status.NOT_FOUND)
146
+ .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization's user not found with ID: " + username).build();
147
+ }
148
+ users.add(user);
149
+ }
150
+ }
182151
183
- org.setParentOrganization(parentOrg);
184
- }
152
+ org.setUsers(users);
153
+ org.setCreationTimestamp(new Date());
154
+ em.persist(org);
185155
186
- private void setOrgUsers(Organization org, List<String> usersIds, EntityManager em) throws SeCurisException {
187
- List<User> users = null;
188
- if (usersIds != null && usersIds.size() > 0) {
189
- users = new ArrayList<>();
190
- for (String username : usersIds) {
191
- User user = em.find(User.class, username);
192
- if (user == null) {
193
- LOG.error("Organization user with id '{}' not found in DB", username);
194
- throw new SecurityException("Organization's user not found with ID: " + username);
195
- }
196
- users.add(user);
197
- }
198
- }
156
+ return Response.ok(org).build();
157
+ }
199158
200
- org.setUsers(users);
201
- }
159
+ private void setParentOrg(Organization org, Integer parentOrgId, EntityManager em) throws SeCurisException {
160
+ Organization parentOrg = null;
161
+ if (parentOrgId != null) {
162
+ parentOrg = em.find(Organization.class, parentOrgId);
163
+ if (parentOrg == null) {
164
+ LOG.error("Organization parent with id {} not found in DB", org.getParentOrgId());
165
+ throw new SecurityException("Organization's parent not found with ID: " + org.getParentOrgId());
166
+ }
167
+ }
202168
203
- @PUT
204
- @POST
205
- @Path("/{orgid}")
206
- @Transactional
207
- @Consumes(MediaType.APPLICATION_JSON)
208
- @Produces(
209
- { MediaType.APPLICATION_JSON })
210
- @Securable
211
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
212
- public Response modify(Organization org, @PathParam("orgid") String orgid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
213
- LOG.info("Modifying organization with id: {}", orgid);
214
- EntityManager em = emProvider.get();
215
- Organization currentOrg = em.find(Organization.class, Integer.parseInt(orgid));
216
- if (currentOrg == null) {
217
- LOG.error("Organization with id {} not found in DB", orgid);
218
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization not found with ID: " + orgid).build();
219
- }
220
- try {
221
- this.setParentOrg(currentOrg, org.getParentOrgId(), em);
222
- } catch (SeCurisException e) {
223
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
224
- }
225
- if (org.getParentOrganization() != null) {
226
- if (isCyclicalRelationship(currentOrg.getId(), org.getParentOrganization())) {
227
- LOG.error("Organization parent generate a cyclical relationship, parent id {}, current id: {}", org.getParentOrgId(), currentOrg.getId());
228
- return Response.status(Status.FORBIDDEN).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Cyclical relationships are not allowed, please change the parent organization, current Parent: " + org.getParentOrganization().getName()).build();
229
- }
230
- }
231
-
232
- try {
233
- setOrgUsers(currentOrg, org.getUsersIds(), em);
234
- } catch (SeCurisException e) {
235
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
236
- }
169
+ org.setParentOrganization(parentOrg);
170
+ }
237171
238
- currentOrg.setCode(org.getCode());
239
- currentOrg.setName(org.getName());
240
- currentOrg.setDescription(org.getDescription());
241
- em.persist(currentOrg);
172
+ private void setOrgUsers(Organization org, List<String> usersIds, EntityManager em) throws SeCurisException {
173
+ List<User> users = null;
174
+ if (usersIds != null && usersIds.size() > 0) {
175
+ users = new ArrayList<>();
176
+ for (String username : usersIds) {
177
+ User user = em.find(User.class, username);
178
+ if (user == null) {
179
+ LOG.error("Organization user with id '{}' not found in DB", username);
180
+ throw new SecurityException("Organization's user not found with ID: " + username);
181
+ }
182
+ users.add(user);
183
+ }
184
+ }
242185
243
- return Response.ok(currentOrg).build();
244
- }
186
+ org.setUsers(users);
187
+ }
245188
246
- @DELETE
247
- @Path("/{orgid}")
248
- @Transactional
249
- @Produces(
250
- { MediaType.APPLICATION_JSON })
251
- @Securable
252
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
253
- public Response delete(@PathParam("orgid") String orgid, @Context HttpServletRequest request) {
254
- LOG.info("Deleting organization with id: {}", orgid);
255
- EntityManager em = emProvider.get();
256
- Organization org = em.find(Organization.class, Integer.parseInt(orgid));
257
- if (org == null) {
258
- LOG.error("Organization with id {} can not be deleted, It was not found in DB", orgid);
259
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization was not found, ID: " + orgid).build();
260
- }
261
- if (org.getChildOrganizations() != null && org.getChildOrganizations().size() > 0) {
262
- LOG.error("Organization has children and can not be deleted, ID: " + orgid);
263
- return Response.status(Status.FORBIDDEN).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization has children and can not be deleted, ID: " + orgid).build();
264
- }
189
+ @PUT
190
+ @POST
191
+ @Path("/{orgid}")
192
+ @Transactional
193
+ @Consumes(MediaType.APPLICATION_JSON)
194
+ @Produces({ MediaType.APPLICATION_JSON })
195
+ @Securable
196
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
197
+ public Response modify(Organization org, @PathParam("orgid") String orgid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
198
+ LOG.info("Modifying organization with id: {}", orgid);
199
+ EntityManager em = emProvider.get();
200
+ Organization currentOrg = em.find(Organization.class, Integer.parseInt(orgid));
201
+ if (currentOrg == null) {
202
+ LOG.error("Organization with id {} not found in DB", orgid);
203
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization not found with ID: " + orgid)
204
+ .build();
205
+ }
206
+ try {
207
+ this.setParentOrg(currentOrg, org.getParentOrgId(), em);
208
+ } catch (SeCurisException e) {
209
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
210
+ }
211
+ if (org.getParentOrganization() != null) {
212
+ if (isCyclicalRelationship(currentOrg.getId(), org.getParentOrganization())) {
213
+ LOG.error("Organization parent generate a cyclical relationship, parent id {}, current id: {}", org.getParentOrgId(),
214
+ currentOrg.getId());
215
+ return Response
216
+ .status(Status.FORBIDDEN)
217
+ .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER,
218
+ "Cyclical relationships are not allowed, please change the parent organization, current Parent: "
219
+ + org.getParentOrganization().getName()).build();
220
+ }
221
+ }
265222
266
- em.remove(org);
267
- return Response.ok(Utils.createMap("success", true, "id", orgid)).build();
268
- }
223
+ try {
224
+ setOrgUsers(currentOrg, org.getUsersIds(), em);
225
+ } catch (SeCurisException e) {
226
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
227
+ }
228
+
229
+ currentOrg.setCode(org.getCode());
230
+ currentOrg.setName(org.getName());
231
+ currentOrg.setDescription(org.getDescription());
232
+ em.persist(currentOrg);
233
+
234
+ return Response.ok(currentOrg).build();
235
+ }
236
+
237
+ @DELETE
238
+ @Path("/{orgid}")
239
+ @Transactional
240
+ @Produces({ MediaType.APPLICATION_JSON })
241
+ @Securable
242
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
243
+ public Response delete(@PathParam("orgid") String orgid, @Context HttpServletRequest request) {
244
+ LOG.info("Deleting organization with id: {}", orgid);
245
+ EntityManager em = emProvider.get();
246
+ Organization org = em.find(Organization.class, Integer.parseInt(orgid));
247
+ if (org == null) {
248
+ LOG.error("Organization with id {} can not be deleted, It was not found in DB", orgid);
249
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization was not found, ID: " + orgid)
250
+ .build();
251
+ }
252
+ if (org.getChildOrganizations() != null && org.getChildOrganizations().size() > 0) {
253
+ LOG.error("Organization has children and can not be deleted, ID: " + orgid);
254
+ return Response.status(Status.FORBIDDEN)
255
+ .header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Organization has children and can not be deleted, ID: " + orgid).build();
256
+ }
257
+
258
+ em.remove(org);
259
+ return Response.ok(Utils.createMap("success", true, "id", orgid)).build();
260
+ }
269261
270262 }
securis/src/main/java/net/curisit/securis/services/PackResource.java
....@@ -40,202 +40,197 @@
4040 import com.google.inject.persist.Transactional;
4141
4242 /**
43
- * Pack resource, this service will provide methods to create, modify and delete packs
43
+ * Pack resource, this service will provide methods to create, modify and delete
44
+ * packs
4445 *
4546 * @author roberto <roberto.sanchez@curisit.net>
4647 */
4748 @Path("/pack")
4849 public class PackResource {
4950
50
- private static final Logger LOG = LogManager.getLogger(PackResource.class);
51
+ private static final Logger LOG = LogManager.getLogger(PackResource.class);
5152
52
- @Inject
53
- TokenHelper tokenHelper;
53
+ @Inject
54
+ TokenHelper tokenHelper;
5455
55
- @Inject
56
- Provider<EntityManager> emProvider;
56
+ @Inject
57
+ Provider<EntityManager> emProvider;
5758
58
- public PackResource() {
59
- }
59
+ public PackResource() {}
6060
61
- /**
62
- *
63
- * @return the server version in format majorVersion.minorVersion
64
- */
65
- @GET
66
- @Path("/")
67
- @Securable
68
- @Produces(
69
- { MediaType.APPLICATION_JSON })
70
- public Response index(@Context BasicSecurityContext bsc) {
71
- LOG.info("Getting packs list ");
61
+ /**
62
+ *
63
+ * @return the server version in format majorVersion.minorVersion
64
+ */
65
+ @GET
66
+ @Path("/")
67
+ @Securable
68
+ @Produces({ MediaType.APPLICATION_JSON })
69
+ public Response index(@Context BasicSecurityContext bsc) {
70
+ LOG.info("Getting packs list ");
7271
73
- EntityManager em = emProvider.get();
74
- // TypedQuery<Pack> q = em.createNamedQuery("list-packs-by-orgs", Pack.class);
72
+ EntityManager em = emProvider.get();
7573
76
- TypedQuery<Pack> q;
77
- if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
78
- LOG.info("Getting all packs for user: " + bsc.getUserPrincipal());
79
- q = em.createNamedQuery("list-packs", Pack.class);
80
- } else {
81
- q = em.createNamedQuery("list-packs-by-orgs", Pack.class);
82
- if (bsc.getOrganizationsIds() == null)
83
- Response.ok().build();
84
- q.setParameter("list_ids", bsc.getOrganizationsIds());
85
- }
74
+ TypedQuery<Pack> q;
75
+ if (bsc.isUserInRole(BasicSecurityContext.ROL_ADMIN)) {
76
+ LOG.info("Getting all packs for user: " + bsc.getUserPrincipal());
77
+ q = em.createNamedQuery("list-packs", Pack.class);
78
+ } else {
79
+ q = em.createNamedQuery("list-packs-by-orgs", Pack.class);
80
+ if (bsc.getOrganizationsIds() == null) {
81
+ Response.ok().build();
82
+ }
83
+ q.setParameter("list_ids", bsc.getOrganizationsIds());
84
+ }
8685
87
- List<Pack> list = q.getResultList();
86
+ List<Pack> list = q.getResultList();
8887
89
- return Response.ok(list).build();
90
- }
88
+ return Response.ok(list).build();
89
+ }
9190
92
- private Response generateErrorUnathorizedAccess(Pack pack, Principal user) {
93
- LOG.error("Pack with id {} not accesible by user {}", pack, user);
94
- return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack").build();
95
- }
91
+ private Response generateErrorUnathorizedAccess(Pack pack, Principal user) {
92
+ LOG.error("Pack with id {} not accesible by user {}", pack, user);
93
+ return Response.status(Status.UNAUTHORIZED).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Unathorized access to pack").build();
94
+ }
9695
97
- /**
98
- *
99
- * @return the server version in format majorVersion.minorVersion
100
- */
101
- @GET
102
- @Path("/{packId}")
103
- @Securable
104
- @Produces(
105
- { MediaType.APPLICATION_JSON })
106
- public Response get(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
107
- LOG.info("Getting pack data for id: {}: ", packId);
108
- if (packId == null || packId.equals("")) {
109
- LOG.error("Pack ID is mandatory");
110
- return Response.status(Status.NOT_FOUND).build();
111
- }
96
+ /**
97
+ *
98
+ * @return the server version in format majorVersion.minorVersion
99
+ */
100
+ @GET
101
+ @Path("/{packId}")
102
+ @Securable
103
+ @Produces({ MediaType.APPLICATION_JSON })
104
+ public Response get(@PathParam("packId") Integer packId, @Context BasicSecurityContext bsc) {
105
+ LOG.info("Getting pack data for id: {}: ", packId);
106
+ if (packId == null || "".equals(packId)) {
107
+ LOG.error("Pack ID is mandatory");
108
+ return Response.status(Status.NOT_FOUND).build();
109
+ }
112110
113
- EntityManager em = emProvider.get();
114
- Pack pack = em.find(Pack.class, packId);
115
- if (pack == null) {
116
- LOG.error("Pack with id {} not found in DB", packId);
117
- return Response.status(Status.NOT_FOUND).build();
118
- }
119
- if (bsc.isUserInRole(BasicSecurityContext.ROL_ADVANCE)) {
120
- if (bsc.getOrganizationsIds() == null || !bsc.getOrganizationsIds().contains(pack.getOrgId())) {
121
- return generateErrorUnathorizedAccess(pack, bsc.getUserPrincipal());
122
- }
123
- }
124
- return Response.ok(pack).build();
125
- }
111
+ EntityManager em = emProvider.get();
112
+ Pack pack = em.find(Pack.class, packId);
113
+ if (pack == null) {
114
+ LOG.error("Pack with id {} not found in DB", packId);
115
+ return Response.status(Status.NOT_FOUND).build();
116
+ }
117
+ if (bsc.isUserInRole(BasicSecurityContext.ROL_ADVANCE)) {
118
+ if (bsc.getOrganizationsIds() == null || !bsc.getOrganizationsIds().contains(pack.getOrgId())) {
119
+ return generateErrorUnathorizedAccess(pack, bsc.getUserPrincipal());
120
+ }
121
+ }
122
+ return Response.ok(pack).build();
123
+ }
126124
127
- @POST
128
- @Path("/")
129
- @Securable
130
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
131
- @Consumes(MediaType.APPLICATION_JSON)
132
- @Produces(
133
- { MediaType.APPLICATION_JSON })
134
- @Transactional
135
- public Response create(Pack pack, @Context BasicSecurityContext bsc) {
136
- LOG.info("Creating new pack");
137
- EntityManager em = emProvider.get();
125
+ @POST
126
+ @Path("/")
127
+ @Securable
128
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
129
+ @Consumes(MediaType.APPLICATION_JSON)
130
+ @Produces({ MediaType.APPLICATION_JSON })
131
+ @Transactional
132
+ public Response create(Pack pack, @Context BasicSecurityContext bsc) {
133
+ LOG.info("Creating new pack");
134
+ EntityManager em = emProvider.get();
138135
139
- try {
140
- setPackOrganization(pack, pack.getOrgId(), em);
141
- } catch (SeCurisException e) {
142
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
143
- }
136
+ try {
137
+ setPackOrganization(pack, pack.getOrgId(), em);
138
+ } catch (SeCurisException e) {
139
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
140
+ }
144141
145
- try {
146
- setPackLicenseType(pack, pack.getLicTypeId(), em);
147
- } catch (SeCurisException e) {
148
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
149
- }
142
+ try {
143
+ setPackLicenseType(pack, pack.getLicTypeId(), em);
144
+ } catch (SeCurisException e) {
145
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
146
+ }
150147
151
- User user = em.find(User.class, bsc.getUserPrincipal().getName());
148
+ User user = em.find(User.class, bsc.getUserPrincipal().getName());
152149
153
- pack.setCreatedBy(user);
154
- pack.setCreationTimestamp(new Date());
155
- em.persist(pack);
150
+ pack.setCreatedBy(user);
151
+ pack.setCreationTimestamp(new Date());
152
+ em.persist(pack);
156153
157
- return Response.ok(pack).build();
158
- }
159
-
160
- private void setPackLicenseType(Pack pack, Integer licTypeId, EntityManager em) throws SeCurisException {
161
- LicenseType lt = null;
162
- if (licTypeId != null) {
163
- lt = em.find(LicenseType.class, pack.getLicTypeId());
164
- if (lt == null) {
165
- LOG.error("Pack license type with id {} not found in DB", licTypeId);
166
- throw new SeCurisException("Pack license type not found with ID: " + licTypeId);
167
-// return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Pack license type not found with ID: " + pack.getLicTypeId()).build();
168
- }
169
- }
170
- pack.setLicenseType(lt);
171
- }
154
+ return Response.ok(pack).build();
155
+ }
172156
173
- @PUT
174
- @POST
175
- @Path("/{packId}")
176
- @Transactional
177
- @Securable
178
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
179
- @Consumes(MediaType.APPLICATION_JSON)
180
- @Produces(
181
- { MediaType.APPLICATION_JSON })
182
- public Response modify(Pack pack, @PathParam("packId") Integer packId) {
183
- LOG.info("Modifying pack with id: {}", packId);
184
- EntityManager em = emProvider.get();
185
- Pack currentPack = em.find(Pack.class, packId);
157
+ private void setPackLicenseType(Pack pack, Integer licTypeId, EntityManager em) throws SeCurisException {
158
+ LicenseType lt = null;
159
+ if (licTypeId != null) {
160
+ lt = em.find(LicenseType.class, pack.getLicTypeId());
161
+ if (lt == null) {
162
+ LOG.error("Pack license type with id {} not found in DB", licTypeId);
163
+ throw new SeCurisException("Pack license type not found with ID: " + licTypeId);
164
+ }
165
+ }
166
+ pack.setLicenseType(lt);
167
+ }
186168
187
- try {
188
- setPackOrganization(currentPack, pack.getOrgId(), em);
189
- } catch (SeCurisException e) {
190
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
191
- }
169
+ @PUT
170
+ @POST
171
+ @Path("/{packId}")
172
+ @Transactional
173
+ @Securable
174
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
175
+ @Consumes(MediaType.APPLICATION_JSON)
176
+ @Produces({ MediaType.APPLICATION_JSON })
177
+ public Response modify(Pack pack, @PathParam("packId") Integer packId) {
178
+ LOG.info("Modifying pack with id: {}", packId);
179
+ EntityManager em = emProvider.get();
180
+ Pack currentPack = em.find(Pack.class, packId);
192181
193
- try {
194
- setPackLicenseType(currentPack, pack.getLicTypeId(), em);
195
- } catch (SeCurisException e) {
196
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
197
- }
198
-
199
- currentPack.setLicensePreactivation(pack.isLicensePreactivation());
200
- currentPack.setCode(pack.getCode());
201
- currentPack.setComments(pack.getComments());
202
- currentPack.setNumLicenses(pack.getNumLicenses());
182
+ try {
183
+ setPackOrganization(currentPack, pack.getOrgId(), em);
184
+ } catch (SeCurisException e) {
185
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
186
+ }
203187
204
- em.persist(currentPack);
188
+ try {
189
+ setPackLicenseType(currentPack, pack.getLicTypeId(), em);
190
+ } catch (SeCurisException e) {
191
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
192
+ }
205193
206
- return Response.ok(pack).build();
207
- }
194
+ currentPack.setLicensePreactivation(pack.isLicensePreactivation());
195
+ currentPack.setCode(pack.getCode());
196
+ currentPack.setComments(pack.getComments());
197
+ currentPack.setNumLicenses(pack.getNumLicenses());
208198
209
- private void setPackOrganization(Pack currentPack, Integer orgId, EntityManager em) throws SeCurisException {
210
- Organization org = null;
211
- if (orgId != null) {
212
- org = em.find(Organization.class, orgId);
213
- if (org == null) {
214
- LOG.error("Organization pack with id {} not found in DB", orgId);
215
- throw new SeCurisException("Pack organization not found with ID: " + orgId);
216
- }
217
- }
218
- currentPack.setOrganization(org);
219
- }
199
+ em.persist(currentPack);
220200
221
- @DELETE
222
- @Path("/{packId}")
223
- @Securable
224
- @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
225
- @Transactional
226
- @Produces(
227
- { MediaType.APPLICATION_JSON })
228
- public Response delete(@PathParam("packId") String packId) {
229
- LOG.info("Deleting pack with id: {}", packId);
230
- EntityManager em = emProvider.get();
231
- Pack org = em.find(Pack.class, Integer.parseInt(packId));
232
- if (org == null) {
233
- LOG.error("Pack with id {} can not be deleted, It was not found in DB", packId);
234
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Pack was not found, ID: " + packId).build();
235
- }
201
+ return Response.ok(pack).build();
202
+ }
236203
237
- em.remove(org);
238
- return Response.ok(Utils.createMap("success", true, "id", packId)).build();
239
- }
204
+ private void setPackOrganization(Pack currentPack, Integer orgId, EntityManager em) throws SeCurisException {
205
+ Organization org = null;
206
+ if (orgId != null) {
207
+ org = em.find(Organization.class, orgId);
208
+ if (org == null) {
209
+ LOG.error("Organization pack with id {} not found in DB", orgId);
210
+ throw new SeCurisException("Pack organization not found with ID: " + orgId);
211
+ }
212
+ }
213
+ currentPack.setOrganization(org);
214
+ }
215
+
216
+ @DELETE
217
+ @Path("/{packId}")
218
+ @Securable
219
+ @RolesAllowed(BasicSecurityContext.ROL_ADMIN)
220
+ @Transactional
221
+ @Produces({ MediaType.APPLICATION_JSON })
222
+ public Response delete(@PathParam("packId") String packId) {
223
+ LOG.info("Deleting pack with id: {}", packId);
224
+ EntityManager em = emProvider.get();
225
+ Pack org = em.find(Pack.class, Integer.parseInt(packId));
226
+ if (org == null) {
227
+ LOG.error("Pack with id {} can not be deleted, It was not found in DB", packId);
228
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, "Pack was not found, ID: " + packId)
229
+ .build();
230
+ }
231
+
232
+ em.remove(org);
233
+ return Response.ok(Utils.createMap("success", true, "id", packId)).build();
234
+ }
240235
241236 }
securis/src/main/java/net/curisit/securis/services/UserResource.java
....@@ -46,210 +46,204 @@
4646 @Path("/user")
4747 public class UserResource {
4848
49
- @Inject
50
- TokenHelper tokenHelper;
49
+ @Inject
50
+ TokenHelper tokenHelper;
5151
52
- @Inject
53
- Provider<EntityManager> emProvider;
52
+ @Inject
53
+ Provider<EntityManager> emProvider;
5454
55
- // private LicenseHelper licenseHelper = InjectorFactory.getInjector().getInstance(LicenseHelper.class);
56
- private static final Logger LOG = LogManager.getLogger(UserResource.class);
55
+ private static final Logger LOG = LogManager.getLogger(UserResource.class);
5756
58
- public UserResource() {
59
- }
57
+ public UserResource() {}
6058
61
- /**
62
- *
63
- * @return the server version in format majorVersion.minorVersion
64
- */
65
- @GET
66
- @Path("/")
67
- @Produces(
68
- { MediaType.APPLICATION_JSON })
69
- public Response index() {
70
- LOG.info("Getting users list ");
59
+ /**
60
+ *
61
+ * @return the server version in format majorVersion.minorVersion
62
+ */
63
+ @GET
64
+ @Path("/")
65
+ @Produces({ MediaType.APPLICATION_JSON })
66
+ public Response index() {
67
+ LOG.info("Getting users list ");
7168
72
- EntityManager em = emProvider.get();
73
- TypedQuery<User> q = em.createNamedQuery("list-users", User.class);
69
+ EntityManager em = emProvider.get();
70
+ TypedQuery<User> q = em.createNamedQuery("list-users", User.class);
7471
75
- List<User> list = q.getResultList();
72
+ List<User> list = q.getResultList();
7673
77
- return Response.ok(list).build();
78
- }
74
+ return Response.ok(list).build();
75
+ }
7976
80
- /**
81
- *
82
- * @return The user
83
- */
84
- @GET
85
- @Path("/{uid}")
86
- @Produces(
87
- { MediaType.APPLICATION_JSON })
88
- public Response get(@PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
89
- LOG.info("Getting user data for id: {}: ", uid);
90
- if (uid == null || uid.equals("")) {
91
- LOG.error("User ID is mandatory");
92
- return Response.status(Status.NOT_FOUND).build();
93
- }
77
+ /**
78
+ *
79
+ * @return The user
80
+ */
81
+ @GET
82
+ @Path("/{uid}")
83
+ @Produces({ 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 || "".equals(uid)) {
87
+ LOG.error("User ID is mandatory");
88
+ return Response.status(Status.NOT_FOUND).build();
89
+ }
9490
95
- EntityManager em = emProvider.get();
96
- User lt = em.find(User.class, uid);
97
- if (lt == null) {
98
- LOG.error("User with id {} not found in DB", uid);
99
- return Response.status(Status.NOT_FOUND).build();
100
- }
101
- return Response.ok(lt).build();
102
- }
91
+ EntityManager em = emProvider.get();
92
+ User lt = em.find(User.class, 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
+ }
10399
104
- @POST
105
- @Path("/")
106
- @Consumes(MediaType.APPLICATION_JSON)
107
- @Produces(
108
- { MediaType.APPLICATION_JSON })
109
- @Transactional
110
- public Response create(User user, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
111
- LOG.info("Creating new user");
112
- EntityManager em = emProvider.get();
113
- User currentUser = em.find(User.class, user.getUsername());
114
- if (currentUser != null) {
115
- LOG.info("User with id {} was found in DB, we'll try to modify it", user.getUsername());
116
- return modify(user, user.getUsername(), token);
117
- }
118
-
119
- try {
120
- this.setUserOrg(user, user.getOrgsIds(), em);
121
- } catch (SeCurisException e) {
122
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
123
- }
124
- user.setModificationTimestamp(new Date());
125
- user.setLastLogin(null);
126
- user.setCreationTimestamp(new Date());
127
- em.persist(user);
100
+ @POST
101
+ @Path("/")
102
+ @Consumes(MediaType.APPLICATION_JSON)
103
+ @Produces({ MediaType.APPLICATION_JSON })
104
+ @Transactional
105
+ public Response create(User user, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
106
+ LOG.info("Creating new user");
107
+ EntityManager em = emProvider.get();
108
+ User currentUser = em.find(User.class, user.getUsername());
109
+ if (currentUser != null) {
110
+ LOG.info("User with id {} was found in DB, we'll try to modify it", user.getUsername());
111
+ return modify(user, user.getUsername(), token);
112
+ }
128113
129
- return Response.ok(user).build();
130
- }
131
-
132
- private void setUserOrg(User user, Set<Integer> orgsIds, EntityManager em) throws SeCurisException {
133
- Set<Organization> orgs = null;
134
- if (orgsIds != null && orgsIds.size() > 0) {
135
- orgs = new HashSet<>();
136
- for (Integer orgId : orgsIds) {
137
- Organization o = em.find(Organization.class, orgId);
138
- if (o == null) {
139
- LOG.error("User organization with id {} not found in DB", orgId);
140
- throw new SeCurisException("User's organization not found with ID: " + orgId);
141
- }
142
- orgs.add(o);
143
- }
144
- }
114
+ try {
115
+ this.setUserOrg(user, user.getOrgsIds(), em);
116
+ } catch (SeCurisException e) {
117
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
118
+ }
119
+ user.setModificationTimestamp(new Date());
120
+ user.setLastLogin(null);
121
+ user.setCreationTimestamp(new Date());
122
+ em.persist(user);
145123
146
- user.setOrganizations(orgs);
124
+ return Response.ok(user).build();
125
+ }
147126
148
- }
127
+ private void setUserOrg(User user, Set<Integer> orgsIds, EntityManager em) throws SeCurisException {
128
+ Set<Organization> orgs = null;
129
+ if (orgsIds != null && orgsIds.size() > 0) {
130
+ orgs = new HashSet<>();
131
+ for (Integer orgId : orgsIds) {
132
+ Organization o = em.find(Organization.class, orgId);
133
+ if (o == null) {
134
+ LOG.error("User organization with id {} not found in DB", orgId);
135
+ throw new SeCurisException("User's organization not found with ID: " + orgId);
136
+ }
137
+ orgs.add(o);
138
+ }
139
+ }
149140
150
- @PUT
151
- @POST
152
- @Path("/{uid}")
153
- @Transactional
154
- @Consumes(MediaType.APPLICATION_JSON)
155
- @Produces(
156
- { MediaType.APPLICATION_JSON })
157
- public Response modify(User user, @PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
158
- LOG.info("Modifying user with id: {}", uid);
159
- EntityManager em = emProvider.get();
160
- User currentUser = em.find(User.class, uid);
161
- if (currentUser == null) {
162
- LOG.info("User with id {} not found in DB, we'll try to create it", uid);
163
- return create(user, token);
164
- }
141
+ user.setOrganizations(orgs);
165142
166
- try {
167
- this.setUserOrg(currentUser, user.getOrgsIds(), em);
168
- } catch (SeCurisException e) {
169
- return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
170
- }
171
- currentUser.setFirstName(user.getFirstName());
172
- currentUser.setLastName(user.getLastName());
173
- currentUser.setRoles(user.getRoles());
174
- currentUser.setLang(user.getLang());
175
- currentUser.setModificationTimestamp(new Date());
176
- currentUser.setPassword(user.getPassword());
177
- currentUser.setLastLogin(user.getLastLogin());
143
+ }
178144
179
- em.persist(currentUser);
145
+ @PUT
146
+ @POST
147
+ @Path("/{uid}")
148
+ @Transactional
149
+ @Consumes(MediaType.APPLICATION_JSON)
150
+ @Produces({ MediaType.APPLICATION_JSON })
151
+ public Response modify(User user, @PathParam("uid") String uid, @HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token) {
152
+ LOG.info("Modifying user with id: {}", uid);
153
+ EntityManager em = emProvider.get();
154
+ User currentUser = em.find(User.class, uid);
155
+ if (currentUser == null) {
156
+ LOG.info("User with id {} not found in DB, we'll try to create it", uid);
157
+ return create(user, token);
158
+ }
180159
181
- return Response.ok(currentUser).build();
182
- }
160
+ try {
161
+ this.setUserOrg(currentUser, user.getOrgsIds(), em);
162
+ } catch (SeCurisException e) {
163
+ return Response.status(Status.NOT_FOUND).header(DefaultExceptionHandler.ERROR_MESSAGE_HEADER, e.getMessage()).build();
164
+ }
165
+ currentUser.setFirstName(user.getFirstName());
166
+ currentUser.setLastName(user.getLastName());
167
+ currentUser.setRoles(user.getRoles());
168
+ currentUser.setLang(user.getLang());
169
+ currentUser.setModificationTimestamp(new Date());
170
+ currentUser.setPassword(user.getPassword());
171
+ currentUser.setLastLogin(user.getLastLogin());
183172
184
- @DELETE
185
- @Path("/{uid}")
186
- @Transactional
187
- @Produces(
188
- { MediaType.APPLICATION_JSON })
189
- public Response delete(@PathParam("uid") String uid, @Context HttpServletRequest request) {
190
- LOG.info("Deleting app with id: {}", uid);
191
- EntityManager em = emProvider.get();
192
- User app = em.find(User.class, uid);
193
- if (app == null) {
194
- LOG.error("User with id {} can not be deleted, It was not found in DB", uid);
195
- return Response.status(Status.NOT_FOUND).build();
196
- }
173
+ em.persist(currentUser);
197174
198
- em.remove(app);
199
- return Response.ok(Utils.createMap("success", true, "id", uid)).build();
200
- }
175
+ return Response.ok(currentUser).build();
176
+ }
201177
202
- @POST
203
- @Path("/login")
204
- @Produces(
205
- { MediaType.APPLICATION_JSON })
206
- public Response login(@FormParam("username") String user, @FormParam("password") String password, @Context HttpServletRequest request) {
207
- LOG.info("index session: " + request.getSession());
208
- LOG.info("user: {}, pass: {}", user, password);
209
- LOG.info("is user in role: {} == {} ? ", "advance", request.isUserInRole("advance"));
178
+ @DELETE
179
+ @Path("/{uid}")
180
+ @Transactional
181
+ @Produces({ MediaType.APPLICATION_JSON })
182
+ public Response delete(@PathParam("uid") String uid, @Context HttpServletRequest request) {
183
+ LOG.info("Deleting app with id: {}", uid);
184
+ EntityManager em = emProvider.get();
185
+ User app = em.find(User.class, uid);
186
+ if (app == null) {
187
+ LOG.error("User with id {} can not be deleted, It was not found in DB", uid);
188
+ return Response.status(Status.NOT_FOUND).build();
189
+ }
210190
211
- if ("no".equals(password))
212
- return Response.status(Status.UNAUTHORIZED).build();
213
- String tokenAuth = tokenHelper.generateToken(user);
214
- return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();
215
- }
191
+ em.remove(app);
192
+ return Response.ok(Utils.createMap("success", true, "id", uid)).build();
193
+ }
216194
217
- /**
218
- * Check if current token is valid
219
- *
220
- * @param user
221
- * @param password
222
- * @param request
223
- * @return
224
- */
225
- @POST
226
- @Path("/check")
227
- @Produces(
228
- { MediaType.APPLICATION_JSON })
229
- public Response check(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token, @QueryParam("token") String token2) {
230
- if (token == null)
231
- token = token2;
232
- if (token == null)
233
- return Response.status(Status.FORBIDDEN).build();
195
+ @POST
196
+ @Path("/login")
197
+ @Produces({ MediaType.APPLICATION_JSON })
198
+ public Response login(@FormParam("username") String user, @FormParam("password") String password, @Context HttpServletRequest request) {
199
+ LOG.info("index session: " + request.getSession());
200
+ LOG.info("user: {}, pass: {}", user, password);
201
+ LOG.info("is user in role: {} == {} ? ", "advance", request.isUserInRole("advance"));
234202
235
- LOG.info("Token : " + token);
236
- String user = tokenHelper.extractUserFromToken(token);
237
- LOG.info("Token user: " + user);
238
- Date date = tokenHelper.extractDateCreationFromToken(token);
239
- LOG.info("Token date: " + date);
240
- boolean valid = tokenHelper.isTokenValid(token);
203
+ if ("no".equals(password)) {
204
+ // TODO: Code to test exception handling
205
+ return Response.status(Status.UNAUTHORIZED).build();
206
+ }
207
+ String tokenAuth = tokenHelper.generateToken(user);
208
+ return Response.ok(Utils.createMap("success", true, "token", tokenAuth)).build();
209
+ }
241210
242
- LOG.info("Is Token valid: " + valid);
211
+ /**
212
+ * Check if current token is valid
213
+ *
214
+ * @param user
215
+ * @param password
216
+ * @param request
217
+ * @return
218
+ */
219
+ @POST
220
+ @Path("/check")
221
+ @Produces({ MediaType.APPLICATION_JSON })
222
+ public Response check(@HeaderParam(TokenHelper.TOKEN_HEADER_PÀRAM) String token, @QueryParam("token") String token2) {
223
+ if (token == null) {
224
+ token = token2;
225
+ }
226
+ if (token == null) {
227
+ return Response.status(Status.FORBIDDEN).build();
228
+ }
243229
244
- return Response.ok(Utils.createMap("valid", true, "user", user, "date", date, "token", token)).build();
245
- }
230
+ LOG.info("Token : " + token);
231
+ String user = tokenHelper.extractUserFromToken(token);
232
+ LOG.info("Token user: " + user);
233
+ Date date = tokenHelper.extractDateCreationFromToken(token);
234
+ LOG.info("Token date: " + date);
235
+ boolean valid = tokenHelper.isTokenValid(token);
246236
247
- @GET
248
- @Path("/logout")
249
- @Produces(
250
- { MediaType.APPLICATION_JSON })
251
- public Response logout(@Context HttpServletRequest request) {
252
- request.getSession().invalidate();
253
- return Response.ok().build();
254
- }
237
+ LOG.info("Is Token valid: " + valid);
238
+
239
+ return Response.ok(Utils.createMap("valid", true, "user", user, "date", date, "token", token)).build();
240
+ }
241
+
242
+ @GET
243
+ @Path("/logout")
244
+ @Produces({ MediaType.APPLICATION_JSON })
245
+ public Response logout(@Context HttpServletRequest request) {
246
+ request.getSession().invalidate();
247
+ return Response.ok().build();
248
+ }
255249 }
securis/src/main/java/net/curisit/securis/services/exception/SeCurisServiceException.java
....@@ -4,20 +4,20 @@
44
55 public class SeCurisServiceException extends CurisException {
66
7
- private int status = 0;
7
+ private int status = 0;
88
9
- public SeCurisServiceException(int status, String msg) {
10
- super(msg);
11
- this.status = status;
12
- }
9
+ public SeCurisServiceException(int status, String msg) {
10
+ super(msg);
11
+ this.status = status;
12
+ }
1313
14
- public int getStatus() {
15
- return status;
16
- }
14
+ public int getStatus() {
15
+ return status;
16
+ }
1717
18
- /**
18
+ /**
1919 *
2020 */
21
- private static final long serialVersionUID = 1L;
21
+ private static final long serialVersionUID = 1L;
2222
2323 }
securis/src/main/java/net/curisit/securis/utils/CacheTTL.java
....@@ -13,120 +13,122 @@
1313 import org.apache.logging.log4j.LogManager;
1414
1515 /**
16
- * Cache implementation with TTL (time To Live) The objects are removed from cache when TTL is reached.
16
+ * Cache implementation with TTL (time To Live) The objects are removed from
17
+ * cache when TTL is reached.
1718 *
1819 * @author roberto <roberto.sanchez@curisit.net>
1920 */
2021 @Singleton
2122 public class CacheTTL {
2223
23
- private static final Logger LOG = LogManager.getLogger(CacheTTL.class);
24
+ private static final Logger LOG = LogManager.getLogger(CacheTTL.class);
2425
25
- /**
26
- * Period before token expires, set in seconds.
27
- */
28
- private static int DEFAULT_CACHE_DURATION = 24 * 60 * 60;
26
+ /**
27
+ * Period before token expires, set in seconds.
28
+ */
29
+ private static int DEFAULT_CACHE_DURATION = 24 * 60 * 60;
2930
30
- private Map<String, CachedObject> data = new HashMap<>();
31
+ private Map<String, CachedObject> data = new HashMap<>();
3132
32
- private Thread cleaningThread = null;
33
+ private Thread cleaningThread = null;
3334
34
- @Inject
35
- public CacheTTL() {
36
- cleaningThread = new Thread(new Runnable() {
35
+ @Inject
36
+ public CacheTTL() {
37
+ cleaningThread = new Thread(new Runnable() {
3738
38
- @Override
39
- public void run() {
40
- while (CacheTTL.this.data != null) {
41
- try {
42
- // We check for expired object every 60 seconds
43
- Thread.sleep(60 * 1000);
44
- } catch (InterruptedException e) {
45
- LOG.error("Exiting from Cache Thread");
46
- data.clear();
47
- return;
48
- }
49
- // LOG.info("Cheking expired objects " + new Date());
50
- Date now = new Date();
51
- List<String> keysToRemove = new ArrayList<>();
52
- for (String key : CacheTTL.this.data.keySet()) {
53
- CachedObject co = CacheTTL.this.data.get(key);
54
- if (now.after(co.getExpireAt())) {
55
- keysToRemove.add(key);
56
- }
57
- }
58
- for (String key : keysToRemove) {
59
- // If we try to remove directly in the previous loop an exception is thrown java.util.ConcurrentModificationException
60
- CacheTTL.this.data.remove(key);
61
- }
62
- }
63
- }
64
- });
65
- cleaningThread.start();
66
- }
39
+ @Override
40
+ public void run() {
41
+ while (CacheTTL.this.data != null) {
42
+ try {
43
+ // We check for expired object every 60 seconds
44
+ Thread.sleep(60 * 1000);
45
+ } catch (InterruptedException e) {
46
+ LOG.error("Exiting from Cache Thread");
47
+ data.clear();
48
+ return;
49
+ }
50
+ Date now = new Date();
51
+ List<String> keysToRemove = new ArrayList<>();
52
+ for (String key : CacheTTL.this.data.keySet()) {
53
+ CachedObject co = CacheTTL.this.data.get(key);
54
+ if (now.after(co.getExpireAt())) {
55
+ keysToRemove.add(key);
56
+ }
57
+ }
58
+ for (String key : keysToRemove) {
59
+ // If we try to remove directly in the previous loop an
60
+ // exception is thrown
61
+ // java.util.ConcurrentModificationException
62
+ CacheTTL.this.data.remove(key);
63
+ }
64
+ }
65
+ }
66
+ });
67
+ cleaningThread.start();
68
+ }
6769
68
- /**
69
- *
70
- * @param key
71
- * @param obj
72
- * @param ttl
73
- * Time To Live in seconds
74
- */
75
- public void set(String key, Object obj, int ttl) {
76
- Date expirationDate = new Date(new Date().getTime() + ttl * 1000);
77
- data.put(key, new CachedObject(expirationDate, obj));
78
- }
70
+ /**
71
+ *
72
+ * @param key
73
+ * @param obj
74
+ * @param ttl
75
+ * Time To Live in seconds
76
+ */
77
+ public void set(String key, Object obj, int ttl) {
78
+ Date expirationDate = new Date(new Date().getTime() + ttl * 1000);
79
+ data.put(key, new CachedObject(expirationDate, obj));
80
+ }
7981
80
- public void set(String key, Object obj) {
81
- set(key, obj, DEFAULT_CACHE_DURATION);
82
- }
82
+ public void set(String key, Object obj) {
83
+ set(key, obj, DEFAULT_CACHE_DURATION);
84
+ }
8385
84
- public Object get(String key) {
85
- CachedObject co = data.get(key);
86
- return co == null ? null : co.getObject();
87
- }
86
+ public Object get(String key) {
87
+ CachedObject co = data.get(key);
88
+ return co == null ? null : co.getObject();
89
+ }
8890
89
- public <T> T get(String key, Class<T> type) {
90
- CachedObject co = data.get(key);
91
- return co == null ? null : co.getObject(type);
92
- }
91
+ public <T> T get(String key, Class<T> type) {
92
+ CachedObject co = data.get(key);
93
+ return co == null ? null : co.getObject(type);
94
+ }
9395
94
- public <T> T remove(String key, Class<T> type) {
95
- CachedObject co = data.remove(key);
96
- return co == null ? null : co.getObject(type);
97
- }
96
+ public <T> T remove(String key, Class<T> type) {
97
+ CachedObject co = data.remove(key);
98
+ return co == null ? null : co.getObject(type);
99
+ }
98100
99
- public Object remove(String key) {
100
- CachedObject co = data.remove(key);
101
- return co == null ? null : co.getObject();
102
- }
101
+ public Object remove(String key) {
102
+ CachedObject co = data.remove(key);
103
+ return co == null ? null : co.getObject();
104
+ }
103105
104
- public void clear() {
105
- data.clear();
106
- }
106
+ public void clear() {
107
+ data.clear();
108
+ }
107109
108
- private class CachedObject {
109
- Date expireAt;
110
- Object object;
110
+ private class CachedObject {
111
+ Date expireAt;
112
+ Object object;
111113
112
- public CachedObject(Date date, Object obj) {
113
- expireAt = date;
114
- object = obj;
115
- }
114
+ public CachedObject(Date date, Object obj) {
115
+ expireAt = date;
116
+ object = obj;
117
+ }
116118
117
- public Date getExpireAt() {
118
- return expireAt;
119
- }
119
+ public Date getExpireAt() {
120
+ return expireAt;
121
+ }
120122
121
- public Object getObject() {
122
- return object;
123
- }
123
+ public Object getObject() {
124
+ return object;
125
+ }
124126
125
- @SuppressWarnings("unchecked")
126
- public <T> T getObject(Class<T> type) {
127
- return (T) object;
128
- }
127
+ @SuppressWarnings("unchecked")
128
+ public <T> T getObject(Class<T> type) {
129
+ return (T) object;
130
+ }
129131
130
- }
132
+ }
131133
132134 }
securis/src/main/java/net/curisit/securis/utils/TokenHelper.java
....@@ -20,120 +20,119 @@
2020 @Singleton
2121 public class TokenHelper {
2222
23
- private static final Logger LOG = LogManager.getLogger(TokenHelper.class);
23
+ private static final Logger LOG = LogManager.getLogger(TokenHelper.class);
2424
25
- /**
26
- * Period before token expires, set in hours.
27
- */
28
- private static int VALID_TOKEN_PERIOD = 24;
29
- public static final String TOKEN_HEADER_PÀRAM = "X-SECURIS-TOKEN";
25
+ /**
26
+ * Period before token expires, set in hours.
27
+ */
28
+ private static int VALID_TOKEN_PERIOD = 24;
29
+ public static final String TOKEN_HEADER_PÀRAM = "X-SECURIS-TOKEN";
3030
31
- @Inject
32
- public TokenHelper() {
33
- }
31
+ @Inject
32
+ public TokenHelper() {}
3433
35
- private static byte[] seed = "S3Cur15S33dForT0k3nG3n3r@tion".getBytes();
34
+ private static byte[] seed = "S3Cur15S33dForT0k3nG3n3r@tion".getBytes();
3635
37
- /**
38
- * Generate a token encoded in Base64 for user passed as parameter and taking the current moment as token timestamp
39
- *
40
- * @param user
41
- * @return
42
- */
43
- public String generateToken(String user) {
44
- try {
45
- Date date = new Date();
46
- String secret = generateSecret(user, date);
47
- StringBuffer sb = new StringBuffer();
48
- sb.append(secret);
49
- sb.append(' ');
50
- sb.append(user);
51
- sb.append(' ');
52
- sb.append(Utils.toIsoFormat(date));
53
- return Base64.encodeBytes(sb.toString().getBytes("utf-8"));
54
- } catch (NoSuchAlgorithmException e) {
55
- LOG.error("Error generating SHA-256 hash", e);
56
- } catch (UnsupportedEncodingException e) {
57
- LOG.error("Error generating SHA-256 hash", e);
58
- }
59
- return null;
36
+ /**
37
+ * Generate a token encoded in Base64 for user passed as parameter and
38
+ * taking the current moment as token timestamp
39
+ *
40
+ * @param user
41
+ * @return
42
+ */
43
+ public String generateToken(String user) {
44
+ try {
45
+ Date date = new Date();
46
+ String secret = generateSecret(user, date);
47
+ StringBuffer sb = new StringBuffer();
48
+ sb.append(secret);
49
+ sb.append(' ');
50
+ sb.append(user);
51
+ sb.append(' ');
52
+ sb.append(Utils.toIsoFormat(date));
53
+ return Base64.encodeBytes(sb.toString().getBytes("utf-8"));
54
+ } catch (NoSuchAlgorithmException e) {
55
+ LOG.error("Error generating SHA-256 hash", e);
56
+ } catch (UnsupportedEncodingException e) {
57
+ LOG.error("Error generating SHA-256 hash", e);
58
+ }
59
+ return null;
6060
61
- }
61
+ }
6262
63
- private String generateSecret(String user, Date date) throws UnsupportedEncodingException, NoSuchAlgorithmException {
64
- MessageDigest mDigest = MessageDigest.getInstance("SHA-256");
65
- mDigest.update(seed, 0, seed.length);
66
- byte[] userbytes = user.getBytes("utf-8");
67
- mDigest.update(userbytes, 0, userbytes.length);
68
- byte[] isodate = Utils.toIsoFormat(date).getBytes();
69
- mDigest.update(isodate, 0, isodate.length);
70
- BigInteger i = new BigInteger(1, mDigest.digest());
71
- String secret = String.format("%1$064x", i);
72
- return secret;
73
- }
63
+ private String generateSecret(String user, Date date) throws UnsupportedEncodingException, NoSuchAlgorithmException {
64
+ MessageDigest mDigest = MessageDigest.getInstance("SHA-256");
65
+ mDigest.update(seed, 0, seed.length);
66
+ byte[] userbytes = user.getBytes("utf-8");
67
+ mDigest.update(userbytes, 0, userbytes.length);
68
+ byte[] isodate = Utils.toIsoFormat(date).getBytes();
69
+ mDigest.update(isodate, 0, isodate.length);
70
+ BigInteger i = new BigInteger(1, mDigest.digest());
71
+ String secret = String.format("%1$064x", i);
72
+ return secret;
73
+ }
7474
75
- /**
76
- * Check if passed token is still valid, It use to check if token is expired the attribute VALID_TOKEN_PERIOD (in hours)
77
- *
78
- * @param token
79
- * @return
80
- */
81
- public boolean isTokenValid(String token) {
82
- try {
83
- String tokenDecoded = new String(Base64.decode(token));
84
- String[] parts = StringUtils.split(tokenDecoded, ' ');
85
- if (parts == null || parts.length < 3)
86
- return false;
87
- String secret = parts[0];
88
- String user = parts[1];
89
- Date date = Utils.toDateFromIso(parts[2]);
90
- if (new Date().after(new Date(date.getTime() + VALID_TOKEN_PERIOD * 60 * 60 * 1000)))
91
- return false;
92
- String newSecret = generateSecret(user, date);
93
- return newSecret.equals(secret);
94
- } catch (IOException e) {
95
- LOG.error("Error decoding Base64 token", e);
96
- } catch (NoSuchAlgorithmException e) {
97
- LOG.error("Error generation secret to compare with", e);
98
- }
99
- return false;
100
- }
75
+ /**
76
+ * Check if passed token is still valid, It use to check if token is expired
77
+ * the attribute VALID_TOKEN_PERIOD (in hours)
78
+ *
79
+ * @param token
80
+ * @return
81
+ */
82
+ public boolean isTokenValid(String token) {
83
+ try {
84
+ String tokenDecoded = new String(Base64.decode(token));
85
+ String[] parts = StringUtils.split(tokenDecoded, ' ');
86
+ if (parts == null || parts.length < 3) {
87
+ return false;
88
+ }
89
+ String secret = parts[0];
90
+ String user = parts[1];
91
+ Date date = Utils.toDateFromIso(parts[2]);
92
+ if (new Date().after(new Date(date.getTime() + VALID_TOKEN_PERIOD * 60 * 60 * 1000))) {
93
+ return false;
94
+ }
95
+ String newSecret = generateSecret(user, date);
96
+ return newSecret.equals(secret);
97
+ } catch (IOException e) {
98
+ LOG.error("Error decoding Base64 token", e);
99
+ } catch (NoSuchAlgorithmException e) {
100
+ LOG.error("Error generation secret to compare with", e);
101
+ }
102
+ return false;
103
+ }
101104
102
- public String extractUserFromToken(String token) {
103
- try {
104
- if (token == null)
105
- return null;
106
- String tokenDecoded = new String(Base64.decode(token));
107
- String[] parts = StringUtils.split(tokenDecoded, ' ');
108
- if (parts == null || parts.length < 3)
109
- return null;
110
- String user = parts[1];
111
- return user;
112
- } catch (IOException e) {
113
- LOG.error("Error decoding Base64 token", e);
114
- }
115
- return null;
116
- }
105
+ public String extractUserFromToken(String token) {
106
+ try {
107
+ if (token == null) {
108
+ return null;
109
+ }
110
+ String tokenDecoded = new String(Base64.decode(token));
111
+ String[] parts = StringUtils.split(tokenDecoded, ' ');
112
+ if (parts == null || parts.length < 3) {
113
+ return null;
114
+ }
115
+ String user = parts[1];
116
+ return user;
117
+ } catch (IOException e) {
118
+ LOG.error("Error decoding Base64 token", e);
119
+ }
120
+ return null;
121
+ }
117122
118
- public Date extractDateCreationFromToken(String token) {
119
- try {
120
- String tokenDecoded = new String(Base64.decode(token));
121
- String[] parts = StringUtils.split(tokenDecoded, ' ');
122
- if (parts == null || parts.length < 3)
123
- return null;
124
- Date date = Utils.toDateFromIso(parts[2]);
125
- return date;
126
- } catch (IOException e) {
127
- LOG.error("Error decoding Base64 token", e);
128
- }
129
- return null;
130
- }
123
+ public Date extractDateCreationFromToken(String token) {
124
+ try {
125
+ String tokenDecoded = new String(Base64.decode(token));
126
+ String[] parts = StringUtils.split(tokenDecoded, ' ');
127
+ if (parts == null || parts.length < 3) {
128
+ return null;
129
+ }
130
+ Date date = Utils.toDateFromIso(parts[2]);
131
+ return date;
132
+ } catch (IOException e) {
133
+ LOG.error("Error decoding Base64 token", e);
134
+ }
135
+ return null;
136
+ }
131137
132
- public static void main(String[] args) throws IOException {
133
- TokenHelper th = new TokenHelper();
134
- String token = th.generateToken("pepe");
135
- System.out.println("Token: " + token);
136
- System.out.println("Token: " + new String(Base64.decode(token)));
137
- System.out.println("Valid Token: " + th.isTokenValid(token));
138
- }
139138 }
securis/src/patch/java/net/curisit/securis/LicenseGenerator.java
....@@ -33,124 +33,124 @@
3333 */
3434 public class LicenseGenerator {
3535
36
- private static final Logger LOG = LogManager.getLogger(LicenseGenerator.class);
36
+ private static final Logger LOG = LogManager.getLogger(LicenseGenerator.class);
3737
38
- private static LicenseGenerator singleton = new LicenseGenerator();
38
+ private static LicenseGenerator singleton = new LicenseGenerator();
3939
40
- private LicenseGenerator() {
41
- }
40
+ private LicenseGenerator() {}
4241
43
- public static LicenseGenerator getInstance() {
44
- return singleton;
45
- }
42
+ public static LicenseGenerator getInstance() {
43
+ return singleton;
44
+ }
4645
47
- /**
48
- * Generate a license bean with the specified data
49
- *
50
- * @param hw
51
- * @param customerCode
52
- * - e.g: "BP"
53
- * @param maxInstances
54
- * @param maxUsers
55
- * @param maxTimeThreshold
56
- * Max time between synchronizations expressed in days
57
- * @return
58
- * @throws SeCurisException
59
- */
60
- public LicenseBean generateLicense(RequestBean req, Map<String, Object> metadata, Date expirationDate, String licenseType, String licenseCode) throws SeCurisException {
61
- LOG.info(MessageFormat.format("Generating license: MAC: {0}, Customer code: {1}, AppCode: {2}", req.getMacAddresses(), req.getCustomerCode(), req.getAppCode()));
62
- LicenseBean license = new LicenseBean(req);
63
- license.setLicenseType(licenseType);
64
- license.setLicenseCode(licenseCode);
65
- license.setExpirationDate(expirationDate);
66
- license.setMetadata(metadata);
67
- sign(license);
46
+ /**
47
+ * Generate a license bean with the specified data
48
+ *
49
+ * @param hw
50
+ * @param customerCode
51
+ * - e.g: "BP"
52
+ * @param maxInstances
53
+ * @param maxUsers
54
+ * @param maxTimeThreshold
55
+ * Max time between synchronizations expressed in days
56
+ * @return
57
+ * @throws SeCurisException
58
+ */
59
+ public LicenseBean generateLicense(RequestBean req, Map<String, Object> metadata, Date expirationDate, String licenseType, String licenseCode)
60
+ throws SeCurisException {
61
+ LOG.info(MessageFormat.format("Generating license: MAC: {0}, Customer code: {1}, AppCode: {2}", req.getMacAddresses(), req.getCustomerCode(),
62
+ req.getAppCode()));
63
+ LicenseBean license = new LicenseBean(req);
64
+ license.setLicenseType(licenseType);
65
+ license.setLicenseCode(licenseCode);
66
+ license.setExpirationDate(expirationDate);
67
+ license.setMetadata(metadata);
68
+ sign(license);
6869
69
- return license;
70
- }
70
+ return license;
71
+ }
7172
72
- /**
73
- * Generate a license file using a {@link LicenseBean}
74
- *
75
- * @param license
76
- * @param file
77
- * @throws SeCurisException
78
- */
79
- public void save(LicenseBean license, File file) throws SeCurisException {
80
- SignedLicenseBean signedLic = new SignedLicenseBean(license);
81
- byte[] json;
82
- try {
83
- json = JsonUtils.toJSON(signedLic, true).getBytes("utf-8");
84
- Files.write(Paths.get(file.toURI()), json, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
85
- } catch (UnsupportedEncodingException e) {
86
- LOG.error("Error creating json doc from license: " + license, e);
87
- throw new SeCurisException("Error creating json doc from license: " + license, e);
88
- } catch (IOException e) {
89
- LOG.error("Error creating license file: " + file, e);
90
- throw new SeCurisException("Error creating json doc from license: " + license, e);
91
- }
73
+ /**
74
+ * Generate a license file using a {@link LicenseBean}
75
+ *
76
+ * @param license
77
+ * @param file
78
+ * @throws SeCurisException
79
+ */
80
+ public void save(LicenseBean license, File file) throws SeCurisException {
81
+ SignedLicenseBean signedLic = new SignedLicenseBean(license);
82
+ byte[] json;
83
+ try {
84
+ json = JsonUtils.toJSON(signedLic, true).getBytes("utf-8");
85
+ Files.write(Paths.get(file.toURI()), json, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
86
+ } catch (UnsupportedEncodingException e) {
87
+ LOG.error("Error creating json doc from license: " + license, e);
88
+ throw new SeCurisException("Error creating json doc from license: " + license, e);
89
+ } catch (IOException e) {
90
+ LOG.error("Error creating license file: " + file, e);
91
+ throw new SeCurisException("Error creating json doc from license: " + license, e);
92
+ }
9293
93
- LOG.info("License saved in {}", file);
94
+ LOG.info("License saved in {}", file);
9495
95
- }
96
+ }
9697
97
- /**
98
- * TODO: This method should be removed from client code.
99
- *
100
- * @param licBean
101
- * @return
102
- * @throws NoSuchAlgorithmException
103
- * @throws IOException
104
- * @throws InvalidKeySpecException
105
- * @throws InvalidKeyException
106
- * @throws SignatureException
107
- */
108
- public String sign(LicenseBean licBean) throws SeCurisException {
109
- SignatureHelper sh = SignatureHelper.getInstance();
98
+ /**
99
+ * TODO: This method should be removed from client code.
100
+ *
101
+ * @param licBean
102
+ * @return
103
+ * @throws NoSuchAlgorithmException
104
+ * @throws IOException
105
+ * @throws InvalidKeySpecException
106
+ * @throws InvalidKeyException
107
+ * @throws SignatureException
108
+ */
109
+ public String sign(LicenseBean licBean) throws SeCurisException {
110
+ SignatureHelper sh = SignatureHelper.getInstance();
110111
111
- Signature signature;
112
- try {
113
- signature = Signature.getInstance(SignatureHelper.SIGNATURE_GENERATION_ALGORITHM);
114
- signature.initSign(sh.generatePrivateKey(new File("/Users/cproberto/Documents/wsPython/doky/tests/securis_private_key.pkcs8")));
112
+ Signature signature;
113
+ try {
114
+ signature = Signature.getInstance(SignatureHelper.SIGNATURE_GENERATION_ALGORITHM);
115
+ signature.initSign(sh.generatePrivateKey(new File("/Users/cproberto/Documents/wsPython/doky/tests/securis_private_key.pkcs8")));
115116
116
- sh.prepareSignature(signature, licBean);
117
+ sh.prepareSignature(signature, licBean);
117118
118
- byte[] signatureData = signature.sign();
119
- licBean.setSignature(Base64.encodeBase64String(signatureData));
120
- return licBean.getSignature();
121
- } catch (NoSuchAlgorithmException e) {
122
- LOG.error("Error signing license for " + licBean, e);
123
- } catch (InvalidKeyException e) {
124
- LOG.error("Error signing license for " + licBean, e);
125
- } catch (InvalidKeySpecException e) {
126
- LOG.error("Error signing license for " + licBean, e);
127
- } catch (IOException e) {
128
- LOG.error("Error signing license for " + licBean, e);
129
- } catch (SignatureException e) {
130
- LOG.error("Error signing license for " + licBean, e);
131
- }
132
- throw new SeCurisException("License could not be generated");
133
- }
119
+ byte[] signatureData = signature.sign();
120
+ licBean.setSignature(Base64.encodeBase64String(signatureData));
121
+ return licBean.getSignature();
122
+ } catch (NoSuchAlgorithmException e) {
123
+ LOG.error("Error signing license for " + licBean, e);
124
+ } catch (InvalidKeyException e) {
125
+ LOG.error("Error signing license for " + licBean, e);
126
+ } catch (InvalidKeySpecException e) {
127
+ LOG.error("Error signing license for " + licBean, e);
128
+ } catch (IOException e) {
129
+ LOG.error("Error signing license for " + licBean, e);
130
+ } catch (SignatureException e) {
131
+ LOG.error("Error signing license for " + licBean, e);
132
+ }
133
+ throw new SeCurisException("License could not be generated");
134
+ }
134135
135
- public static void main(String[] args) throws SeCurisException {
136
+ public static void main(String[] args) throws SeCurisException {
136137
137
- RequestBean req = ReqGenerator.getInstance().loadRequest(new File("/Users/cproberto/Documents/wsCurisIT/SeCurisClient/license.req"));
138
- Map<String, Object> metadata = new TreeMap<>();
139
-// CurisData parameters:
140
-// metadata.put("maxUsers", 5);
141
-// metadata.put("maxSessionUsers", 100);
142
- // curisIntegrity
143
- metadata.put("maxUsers", 0);
144
- metadata.put("maxInstances", 0);
145
- metadata.put("timeThreshold", 0);
146
- metadata.put("datasetPrefix", "BP");
147
- metadata.put("extendedMode", true);
148
- Date expirationDate = new Date(new Date().getTime() + (1000L * 3600 * 24 * 365 * 10));
149
- LicenseBean lic = LicenseGenerator.getInstance().generateLicense(req, metadata, expirationDate, "CI-01", "LIC-CURISTEC-0001");
150
- LicenseGenerator.getInstance().save(lic, new File("/Users/cproberto/Desktop/AxelLicCI.lic"));
138
+ RequestBean req = ReqGenerator.getInstance().loadRequest(new File("/Users/cproberto/Documents/wsCurisIT/SeCurisClient/license.req"));
139
+ Map<String, Object> metadata = new TreeMap<>();
140
+ // CurisData parameters:
141
+ // metadata.put("maxUsers", 5);
142
+ // metadata.put("maxSessionUsers", 100);
143
+ // curisIntegrity
144
+ metadata.put("maxUsers", 0);
145
+ metadata.put("maxInstances", 0);
146
+ metadata.put("timeThreshold", 0);
147
+ metadata.put("datasetPrefix", "BP");
148
+ metadata.put("extendedMode", true);
149
+ Date expirationDate = new Date(new Date().getTime() + (1000L * 3600 * 24 * 365 * 10));
150
+ LicenseBean lic = LicenseGenerator.getInstance().generateLicense(req, metadata, expirationDate, "CI-01", "LIC-CURISTEC-0001");
151
+ LicenseGenerator.getInstance().save(lic, new File("/Users/cproberto/Desktop/AxelLicCI.lic"));
151152
152
- System.out.print("License expires at: " + expirationDate.getTime());
153
-
153
+ System.out.print("License expires at: " + expirationDate.getTime());
154154
155
- }
155
+ }
156156 }