019-005-007
Resource Management: Chained Cleanup
Hard
Problem Description
Resource Management: Chained Cleanup with Validation
In this problem, you will create DatabaseConnection and FileWriterSim classes implementing AutoCloseable, adding input validation to their constructors and methods. For invalid arguments, throw IllegalArgumentException; for valid arguments, return the result string. The processQuery and processWrite methods in the Main class manage resources using try-with-resources.
Learning Objective: Implement input validation in AutoCloseable resources and understand exception propagation through try-with-resources
Specifications
DatabaseConnection class
- Implements
AutoCloseable - Constructor
DatabaseConnection(String host):- If
hostisnullor empty, throwIllegalArgumentException("Host cannot be null or empty") - Otherwise store the host in a field
- If
query(String sql)method:- If
sqlisnullor empty, throwIllegalArgumentException("SQL cannot be null or empty") - Otherwise return
"Result of [" + sql + "] on " + host
- If
close()method: resource cleanup (no output required)
FileWriterSim class
- Implements
AutoCloseable - Constructor
FileWriterSim(String filename):- If
filenameisnullor empty, throwIllegalArgumentException("Filename cannot be null or empty") - Otherwise store the filename in a field
- If
write(String data)method:- If
dataisnull, throwIllegalArgumentException("Data cannot be null") - Otherwise return
"Written [" + data + "] to " + filename
- If
close()method: resource cleanup (no output required)
Main class
processQuery(String host, String sql)static method:- Create a
DatabaseConnectionusing try-with-resources - Return the result of
db.query(sql) - Let exceptions propagate to the caller
- Create a
processWrite(String filename, String data)static method:- Create a
FileWriterSimusing try-with-resources - Return the result of
writer.write(data) - Let exceptions propagate to the caller
- Create a
main(String[] args)method: program entry point
Test Examples
| Call | Result |
|---|---|
processQuery("localhost", "SELECT * FROM users") |
"Result of [SELECT * FROM users] on localhost" |
processWrite("output.txt", "query result") |
"Written [query result] to output.txt" |
processQuery(null, "SELECT * FROM users") |
IllegalArgumentException: Host cannot be null or empty |
processQuery("localhost", "") |
IllegalArgumentException: SQL cannot be null or empty |
processWrite(null, "data") |
IllegalArgumentException: Filename cannot be null or empty |
processWrite("output.txt", null) |
IllegalArgumentException: Data cannot be null |
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up