This repository was archived by the owner on Jul 13, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathListingHandler.java
More file actions
322 lines (304 loc) · 13 KB
/
Copy pathListingHandler.java
File metadata and controls
322 lines (304 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* Listing handler to manage the listings in the application
* CWE-1080: Source Code File with Excessive Number of Lines of Code
* This file should stay below 1000 lines of code or be split into multiple files
* CWE-366: All methods that access the shared database connection are synchronized to prevent
* concurrent threads from reading/modifying data in an inconsistent state.
*/
public class ListingHandler extends DatabaseHandler {
/**
* Constructor for the ListingHandler class
*
* @param databaseName The name of the database
*/
public ListingHandler(String databaseName) {
super(databaseName);
}
/**
* Create the table if it doesn't exist
*/
@Override
public void createTable() {
// CWE-459: Incomplete Cleanup
try (Statement statement = this.connection.createStatement()) {
statement.setQueryTimeout(30);
statement.executeUpdate(
"create table if not exists listing (id string, userId string, title string, description string, price float)");
// CWE-778: Insufficient Logging
logger.info("Listing table created");
} catch (SQLException e) {
// CWE-778: Insufficient Logging
logger.severe("Error creating table: " + e.getMessage());
}
}
/**
* Initialize the logger for the listing handler
*
* @return the logger for the listing handler
*/
@Override
public Logger initLogger() {
try {
Logger logger = Logger.getLogger("ListingLogger");
File logDirectory = new File("./logs/");
if (!logDirectory.exists()) {
logDirectory.mkdirs();
}
// CWE-779: Logging of Excessive Data
FileHandler fileHandler = new FileHandler("./logs/ListingLogger.log", 1000000, 1, true);
SimpleFormatter simpleFormatter = new SimpleFormatter();
fileHandler.setFormatter(simpleFormatter);
logger.addHandler(fileHandler);
logger.setUseParentHandlers(false);
// CWE-778: Insufficient Logging
logger.info("Listing logger initialized");
return logger;
} catch (IOException e) {
// CWE-778: Insufficient Logging
System.err.println("Error initializing logger: " + e.getMessage());
}
return null;
}
/**
* Get the listings for a user
*
* @param user The user to get the listings for
* @return The listings for the user
*/
public synchronized List<Listing> getUserListings(User user) {
List<Listing> listings = new ArrayList<>();
UUID userId = user.getId();
String getUserListingsQuery = "SELECT * FROM listing WHERE userId = ?";
// CWE-459: Incomplete Cleanup
try (PreparedStatement preparedStatement = this.connection.prepareStatement(getUserListingsQuery)) {
preparedStatement.setString(1, userId.toString());
preparedStatement.setQueryTimeout(30);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
UUID id = UUID.fromString(resultSet.getString("id"));
String title = resultSet.getString("title");
String description = resultSet.getString("description");
float price = resultSet.getFloat("price");
listings.add(new Listing(id, userId, title, description, price));
}
} catch (SQLException e) {
// CWE-778: Insufficient Logging
logger.severe("Error getting user listings: " + e.getMessage());
}
return listings;
}
/**
* Create a new listing
*
* @param user The user to create the listing for
* @param title The title of the listing
* @param description The description of the listing
* @param price The price of the listing
* @return The new listing
*/
public synchronized Listing createListing(User user, String title, String description, float price) {
//CWE-770 Adding a check to see if the user has reached the max amount of listings
try{
if(isListingLimitReached(user)){
System.out.println("Listing limit reached. Remove an exisiting limit first.");
logger.warning("Listing limit reached for user: " + user.getUsername());
return null;
}
}
catch (SQLException e) {
logger.severe("Error counting user listings: " + e.getMessage());
return null;
}
Listing listing = null;
String createListingQuery = "INSERT INTO listing (id, userId, title, description, price) VALUES (?, ?, ?, ?, ?)";
// CWE-459: Incomplete Cleanup
try (PreparedStatement preparedStatement = this.connection.prepareStatement(createListingQuery)) {
// CWE-334: Small Space of Random Values
UUID id = UUID.randomUUID();
preparedStatement.setString(1, id.toString());
preparedStatement.setString(2, user.getId().toString());
preparedStatement.setString(3, title);
preparedStatement.setString(4, description);
preparedStatement.setFloat(5, price);
preparedStatement.setQueryTimeout(30);
preparedStatement.executeUpdate();
listing = new Listing(id, user.getId(), title, description, price);
// CWE-778: Insufficient Logging
logger.info("Listing " + id + " created");
} catch (SQLException e) {
// CWE-778: Insufficient Logging
logger.severe("Error creating listing: " + e.getMessage());
}
return listing;
}
/**
* Get all the listings
*
* @return All the listings
*/
public synchronized List<Listing> getListings() {
List<Listing> listings = new ArrayList<>();
String getListingsQuery = "SELECT * FROM listing";
// CWE-459: Incomplete Cleanup
try (PreparedStatement preparedStatement = this.connection.prepareStatement(getListingsQuery)) {
preparedStatement.setQueryTimeout(30);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
UUID id = UUID.fromString(resultSet.getString("id"));
UUID listingUserId = UUID.fromString(resultSet.getString("userId"));
String title = resultSet.getString("title");
String description = resultSet.getString("description");
float price = resultSet.getFloat("price");
listings.add(new Listing(id, listingUserId, title, description, price));
}
} catch (SQLException e) {
// CWE-778: Insufficient Logging
logger.severe("Error getting listings: " + e.getMessage());
}
return listings;
}
/**
* Remove a listing
*
* @param listing The listing to remove
*/
public synchronized void removeListing(Listing listing) {
UUID listingId = listing.getId();
String deleteListingQuery = "DELETE FROM listing WHERE id = ?";
// CWE-459: Incomplete Cleanup
try (PreparedStatement preparedStatement = this.connection.prepareStatement(deleteListingQuery)) {
preparedStatement.setString(1, listingId.toString());
preparedStatement.setQueryTimeout(30);
preparedStatement.executeUpdate();
// CWE-778: Insufficient Logging
logger.info("Listing " + listingId + " removed");
} catch (SQLException e) {
// CWE-778: Insufficient Logging
logger.severe("Error removing listing: " + e.getMessage());
}
}
/**
* Get a listing by ID
*
* @param listingId The ID of the listing to get
* @return The listing
*/
public synchronized Listing getListing(UUID listingId) {
Listing listing = null;
String getListingQuery = "SELECT * FROM listing WHERE id = ?";
// CWE-459: Incomplete Cleanup
try (PreparedStatement preparedStatement = this.connection.prepareStatement(getListingQuery)) {
preparedStatement.setString(1, listingId.toString());
preparedStatement.setQueryTimeout(30);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
UUID userId = UUID.fromString(resultSet.getString("userId"));
String title = resultSet.getString("title");
String description = resultSet.getString("description");
float price = resultSet.getFloat("price");
listing = new Listing(listingId, userId, title, description, price);
}
} catch (SQLException e) {
// CWE-778: Insufficient Logging
logger.severe("Error getting listing: " + e.getMessage());
}
return listing;
}
/**
* Delete all the listings for a user
*
* @param username The username of the user to delete the listings for
* @throws SQLException If there is an error deleting the listings
*/
public synchronized void deleteUserListings(String username) throws SQLException {
String deleteUserListingsQuery = "DELETE FROM listing WHERE username = ?";
// CWE-459: Incomplete Cleanup
try (PreparedStatement preparedStatement = this.connection.prepareStatement(deleteUserListingsQuery)) {
preparedStatement.setString(1, username);
preparedStatement.setQueryTimeout(30);
preparedStatement.executeUpdate();
// CWE-778: Insufficient Logging
logger.info("User " + username + " listings deleted");
} catch (SQLException e) {
// CWE-778: Insufficient Logging
logger.severe("Error deleting user listings: " + e.getMessage());
}
}
/**
* Search for listings by title
*
* @param listingTitle the name of the listing
* @throws SQLException if there is an error connecting to the database
* @throws IllegalArgumentException if the listingTitle is not correct format
* @return a list of listings with the given title
*/
public synchronized List<Listing> searchListingsByTitle(String listingTitle) throws SQLException {
if (listingTitle == null || listingTitle.isEmpty()) {
throw new IllegalArgumentException();
}
String searchListingsByTitleString = "SELECT * FROM listing WHERE title = ?";
PreparedStatement searchListingsByTitlePS = this.connection.prepareStatement(searchListingsByTitleString);
try {
searchListingsByTitlePS.setString(1, listingTitle);
List<Listing> listings = new ArrayList<>();
ResultSet resultSet = searchListingsByTitlePS.executeQuery();
while (resultSet.next()) {
Listing currentListing = new Listing(
UUID.fromString(resultSet.getString(1)),
UUID.fromString(resultSet.getString(2)),
resultSet.getString(3),
resultSet.getString(4),
resultSet.getFloat(5));
listings.add(currentListing);
}
return listings;
} finally {
try {
searchListingsByTitlePS.close();
} catch (SQLException e) {
System.out.println("SQLException caught.");
}
}
}
private static final int MAX_LISTING_PER_USER = 10;
/**
* CWE-770: Allocation of Resources Without Limits or Throttling
* Check to see if the user has reached the max amount of item listings
* @param user the current user creating the listing
* @return if the user is allowed to make a listing
* @throws SQLException if an error occurs when accessing data from the SQL database
*/
private synchronized boolean isListingLimitReached(User user) throws SQLException {
String query = "SELECT COUNT(*) FROM listing WHERE userId = ?";
try (PreparedStatement ps = this.connection.prepareStatement(query)) {
ps.setString(1, user.getId().toString());
ps.setQueryTimeout(30);
return ps.executeQuery().getInt(1) >= MAX_LISTING_PER_USER;
}
}
/**
* Clean up the database connection and the handlers for the listing handler
*/
@Override
public void cleanUp() {
super.cleanUp();
Handler[] handlers = logger.getHandlers();
for (Handler handler : handlers) {
handler.close();
logger.removeHandler(handler);
}
}
}