Skip to content

Commit 471e1dd

Browse files
committed
Corrected usage of hibernate and jpa
1 parent 1c6afff commit 471e1dd

File tree

17 files changed

+220
-182
lines changed

17 files changed

+220
-182
lines changed

src/main/java/com/sage/Main.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ public void start(Stage stage) {
3030
WebEngine webEngine = webView.getEngine();
3131

3232
webEngine.setOnError(event -> LOGGER.warning("[Frontend] An error occured on the frontend: " + event.getMessage()));
33-
3433
File htmlFile = new File(getClass().getResource("/html/index.html").getFile());
3534
webEngine.load(htmlFile.toURI().toString());
3635
webEngine.setJavaScriptEnabled(true);
@@ -43,8 +42,9 @@ public void start(Stage stage) {
4342
window.setMember("weaknessController", WeaknessController.getInstance());
4443
window.setMember("vulnerabilityController", VulnerabilityController.getInstance());
4544
window.setMember("fileReader", FileReaderUtility.getInstance());
46-
window.setMember("javaConsole", new JSConsoleBridge());
4745

46+
// TODO: remove later - just for debugging purposes
47+
window.setMember("javaConsole", new JSConsoleBridge());
4848
webEngine.executeScript("""
4949
console.log = function(msg) {
5050
javaConsole.log(msg);

src/main/java/com/sage/controller/FileController.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.sage.controller;
22

33
import java.util.HashMap;
4+
import java.util.Map;
45
import java.util.logging.Logger;
56

67
import com.sage.service.FileService;
@@ -26,13 +27,18 @@ public static FileController getInstance() {
2627
}
2728

2829
public String process(String filePath) {
29-
if (fileService.processFile(filePath))
30+
if (fileService.processFile(filePath)) {
3031
return JsonParser.asJsonString(vulnerabilityService.getStatistics());
32+
}
3133
LOGGER.severe(String.format("[FileController] Failed to process SAST-Report-File: %s", filePath));
3234
throw new InternalError("File: " + filePath + " could not be processed\n");
3335
}
3436

3537
public void fetchAllVulnerabilities() {
3638
vulnerabilityService.getAll();
3739
}
40+
41+
public String info() {
42+
return "FileController instance: " + getInstance() + "\nClass: " + FileController.class.getName();
43+
}
3844
}

src/main/java/com/sage/dao/Dao.java

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,6 @@
99
abstract class Dao<T, K> {
1010
protected static final Logger LOGGER = Logger.getLogger(Dao.class.getName());
1111

12-
protected EntityManager em;
13-
protected EntityTransaction tx;
14-
15-
protected Dao() {
16-
em = JPAManager.getEntityManager();
17-
tx = em.getTransaction();
18-
}
19-
2012
abstract boolean create(T entity);
2113

2214
abstract T read(K key);
Lines changed: 63 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package com.sage.dao;
22

33
import com.sage.model.vulnerability.VulnerabilityModel;
4+
import com.sage.utility.JPAManager;
5+
import jakarta.persistence.EntityManager;
6+
import jakarta.persistence.EntityTransaction;
47

58
import java.sql.Clob;
69
import java.util.ArrayList;
@@ -24,46 +27,60 @@ public static VulnerabilityDao instance() {
2427

2528
@Override
2629
public boolean create(VulnerabilityModel entity) {
30+
EntityManager entityManager = JPAManager.getEntityManager();
31+
EntityTransaction transaction = entityManager.getTransaction();
2732
try {
28-
tx.begin();
29-
em.persist(entity);
30-
tx.commit();
33+
transaction.begin();
34+
entityManager.persist(entity);
35+
transaction.commit();
3136
return true;
3237
} catch (Exception e) {
33-
if (tx.isActive())
34-
tx.rollback();
38+
if (transaction.isActive())
39+
transaction.rollback();
3540

3641
LOGGER.severe("[VulnerabilityDao] Error while inserting new vulnerability entity into database: " + e.getMessage());
3742
return false;
43+
} finally {
44+
entityManager.close();
3845
}
3946
}
4047

4148
@Override
4249
public VulnerabilityModel read(Integer key) {
50+
EntityManager entityManager = JPAManager.getEntityManager();
51+
EntityTransaction transaction = entityManager.getTransaction();
4352
try {
44-
tx.begin();
45-
VulnerabilityModel vulnerabilityModel = em.find(VulnerabilityModel.class, key);
46-
tx.commit();
53+
transaction.begin();
54+
VulnerabilityModel vulnerabilityModel = entityManager.find(VulnerabilityModel.class, key);
55+
transaction.commit();
4756
return vulnerabilityModel;
4857
} catch (Exception e) {
4958
LOGGER.warning("[VulnerabilityDao] Error while trying to fetch entity with (id)=" + key);
5059
return null;
60+
} finally {
61+
entityManager.close();
5162
}
5263

5364
}
5465

5566
@Override
5667
VulnerabilityModel update(Integer key, VulnerabilityModel newEntity) {
57-
tx.begin();
58-
VulnerabilityModel entity = em.find(VulnerabilityModel.class, key);
59-
if (entity == null) {
60-
LOGGER.warning(String.format("[VulnerabilityDao] Error while updating entity. Entity with id=(%d) could not be found.", key));
61-
return null;
62-
} else {
63-
// update (actually not even necessary for this project :P
64-
}
68+
EntityManager entityManager = JPAManager.getEntityManager();
69+
EntityTransaction transaction = entityManager.getTransaction();
6570

66-
throw new UnsupportedOperationException("Unimplemented method 'update'");
71+
try {
72+
transaction.begin();
73+
VulnerabilityModel entity = entityManager.find(VulnerabilityModel.class, key);
74+
if (entity == null) {
75+
LOGGER.warning(String.format("[VulnerabilityDao] Error while updating entity. Entity with id=(%d) could not be found.", key));
76+
return null;
77+
} else {
78+
return null;
79+
// update (actually not even necessary for this project :P
80+
}
81+
} finally {
82+
entityManager.close();
83+
}
6784
}
6885

6986
@Override
@@ -74,41 +91,43 @@ boolean delete(Integer key) {
7491
}
7592

7693
public List<VulnerabilityModel> readAll() {
77-
String query = "SELECT * FROM vulnerabilities;";
78-
79-
List<Object[]> results = em.createNativeQuery(query).getResultList();
80-
List<VulnerabilityModel> vulnerabilityModels = new ArrayList<>();
81-
82-
for (Object[] row : results) {
83-
VulnerabilityModel vulnerabilityModel = new VulnerabilityModel(
84-
((Number) row[0]).intValue(),
85-
(String) row[1],
86-
(String) row[2],
87-
((Clob) row[3]).toString(),
88-
(String) row[4],
89-
(String) row[5],
90-
(String) row[6],
91-
(String) row[7]
92-
);
93-
vulnerabilityModels.add(vulnerabilityModel);
94-
}
94+
EntityManager entityManager = JPAManager.getEntityManager();
95+
96+
String query = "SELECT v FROM VulnerabilityModel v";
9597

96-
return vulnerabilityModels;
98+
try {
99+
List<VulnerabilityModel> vulnerabilityModels = entityManager.createQuery(query, VulnerabilityModel.class).getResultList();
100+
return vulnerabilityModels;
101+
} catch (Exception e) {
102+
LOGGER.warning("Error occured while fetching all vulnerabilities from database: " + e.getMessage());
103+
return new ArrayList<>();
104+
} finally {
105+
entityManager.close();
106+
}
97107
}
98108

99109
public HashMap<String, Integer> getSeverities() {
110+
EntityManager entityManager = JPAManager.getEntityManager();
111+
100112
String query = "SELECT severity, COUNT(*) AS count FROM vulnerabilities GROUP BY severity";
101113

102-
List<Object[]> results = em.createNativeQuery(query).getResultList();
103-
HashMap<String, Integer> severities = new HashMap<>();
114+
try {
115+
List<Object[]> results = entityManager.createNativeQuery(query).getResultList();
116+
HashMap<String, Integer> severities = new HashMap<>();
104117

105-
for (Object[] row : results) {
106-
String severity = (String) row[0];
107-
Number count = (Number) row[1];
108-
severities.put(severity, count.intValue());
109-
}
118+
for (Object[] row : results) {
119+
String severity = (String) row[0];
120+
Number count = (Number) row[1];
121+
severities.put(severity, count.intValue());
122+
}
110123

111-
return severities;
124+
return severities;
125+
} catch (Exception e) {
126+
LOGGER.warning("Error occured while fetching severities from database: " + e.getMessage());
127+
return new HashMap<>();
128+
} finally {
129+
entityManager.close();
130+
}
112131
}
113132

114133
}
Lines changed: 48 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package com.sage.dao;
22

3+
import com.sage.model.vulnerability.VulnerabilityModel;
34
import com.sage.model.weakness.WeaknessModel;
5+
import com.sage.utility.JPAManager;
6+
import jakarta.persistence.EntityManager;
7+
import jakarta.persistence.EntityTransaction;
48

59
import java.util.ArrayList;
610
import java.util.List;
@@ -21,31 +25,41 @@ public static WeaknessDao getInstance() {
2125

2226
@Override
2327
public boolean create(WeaknessModel entity) {
28+
EntityManager entityManager = JPAManager.getEntityManager();
29+
EntityTransaction transaction = entityManager.getTransaction();
30+
2431
try {
25-
tx.begin();
26-
em.persist(entity);
27-
tx.commit();
32+
transaction.begin();
33+
entityManager.persist(entity);
34+
transaction.commit();
2835
return true;
2936
} catch (Exception e) {
30-
if (tx.isActive())
31-
tx.rollback();
37+
if (transaction.isActive())
38+
transaction.rollback();
3239

3340
LOGGER.severe(
3441
"[WeaknessDao] Error while trying to persist entity: " + entity.toString() + "\nRolling back: " + e.getMessage());
3542
return false;
43+
} finally {
44+
entityManager.close();
3645
}
3746
}
3847

3948
@Override
4049
public WeaknessModel read(Integer key) {
50+
EntityManager entityManager = JPAManager.getEntityManager();
51+
EntityTransaction transaction = entityManager.getTransaction();
52+
4153
try {
42-
tx.begin();
43-
WeaknessModel weaknessModel = em.find(WeaknessModel.class, key);
44-
tx.commit();
54+
transaction.begin();
55+
WeaknessModel weaknessModel = entityManager.find(WeaknessModel.class, key);
56+
transaction.commit();
4557
return weaknessModel;
4658
} catch (Exception e) {
4759
LOGGER.severe("[WeaknessDao] Error while trying to fetch entity with (id)=" + key);
4860
return null;
61+
} finally {
62+
entityManager.close();
4963
}
5064
}
5165

@@ -62,43 +76,37 @@ boolean delete(Integer key) {
6276
}
6377

6478
public List<WeaknessModel> readAll() {
65-
String query = "SELECT * FROM weaknesses;";
66-
67-
List<Object[]> results = em.createQuery(query).getResultList();
68-
List<WeaknessModel> weaknessModels = new ArrayList<>();
69-
70-
for (Object[] row : results) {
71-
WeaknessModel weaknessModel = new WeaknessModel(
72-
((Number) row[0]).intValue(),
73-
((Number) row[1]).intValue(),
74-
(String) row[2],
75-
(String) row[3],
76-
(String) row[4],
77-
(String) row[5]
78-
);
79-
weaknessModels.add(weaknessModel);
79+
EntityManager entityManager = JPAManager.getEntityManager();
80+
81+
String query = "SELECT w FROM WeaknessModel w";
82+
83+
try {
84+
List<WeaknessModel> weaknessModels = entityManager.createQuery(query, WeaknessModel.class).getResultList();
85+
return weaknessModels;
86+
} catch (Exception e) {
87+
LOGGER.warning("An error occured while trying to fetch all weaknesses: " + e.getMessage());
88+
return new ArrayList<>();
89+
} finally {
90+
entityManager.close();
8091
}
8192

82-
return weaknessModels;
8393
}
8494

8595
public List<WeaknessModel> fetchAllByVulnerabilityId(Integer vulnerabilityId) {
86-
String query = "SELECT * FROM weaknesses WHERE vulnerability_id = " + vulnerabilityId + ";";
87-
88-
List<Object[]> results = em.createQuery(query).getResultList();
89-
List<WeaknessModel> weaknessModels = new ArrayList<>();
90-
91-
for (Object[] row : results) {
92-
WeaknessModel weaknessModel = new WeaknessModel(
93-
((Number) row[0]).intValue(),
94-
((Number) row[1]).intValue(),
95-
(String) row[2],
96-
(String) row[3],
97-
(String) row[4],
98-
(String) row[5]
99-
);
100-
weaknessModels.add(weaknessModel);
96+
EntityManager entityManager = JPAManager.getEntityManager();
97+
98+
String query = "SELECT w FROM WeaknessModel WHERE w.vulnerability_id = :vulnerabilityId";
99+
100+
try {
101+
List<WeaknessModel> weaknessModels = entityManager.createQuery(query, WeaknessModel.class)
102+
.setParameter("vulnerabilityId", vulnerabilityId)
103+
.getResultList();
104+
return weaknessModels;
105+
} catch (Exception e) {
106+
LOGGER.warning("An error occured while trying to fetch weaknesses: " + e.getMessage());
107+
return new ArrayList<>();
108+
} finally {
109+
entityManager.close();
101110
}
102-
return weaknessModels;
103111
}
104112
}

src/main/java/com/sage/dto/VulnerabilityDto.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,12 @@ public class VulnerabilityDto extends VulnerabilityModel {
99
private List<WeaknessModel> weaknesses;
1010

1111
public VulnerabilityDto(Integer id, String category, String name, String description, String cve, String severity, String locationFile, String locationLineStart, List<WeaknessModel> weaknesses) {
12-
super(id, category, name, description, cve, severity, locationFile, locationLineStart);
12+
super(category, name, description, cve, severity, locationFile, locationLineStart);
1313
this.weaknesses = weaknesses;
1414
}
1515

1616
public VulnerabilityDto(VulnerabilityModel vulnerability, List<WeaknessModel> weaknesses) {
1717
super(
18-
vulnerability.getId(),
1918
vulnerability.getCategory(),
2019
vulnerability.getName(),
2120
vulnerability.getDescription(),
@@ -33,7 +32,6 @@ public List<WeaknessModel> getWeaknesses() {
3332

3433
public VulnerabilityModel toModel() {
3534
return new VulnerabilityModel(
36-
this.getId(),
3735
this.getCategory(),
3836
this.getName(),
3937
this.getDescription(),

0 commit comments

Comments
 (0)