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 host is null or empty, throw IllegalArgumentException("Host cannot be null or empty")
    • Otherwise store the host in a field
  • query(String sql) method:
    • If sql is null or empty, throw IllegalArgumentException("SQL cannot be null or empty")
    • Otherwise return "Result of [" + sql + "] on " + host
  • close() method: resource cleanup (no output required)

FileWriterSim class

  • Implements AutoCloseable
  • Constructor FileWriterSim(String filename):
    • If filename is null or empty, throw IllegalArgumentException("Filename cannot be null or empty")
    • Otherwise store the filename in a field
  • write(String data) method:
    • If data is null, throw IllegalArgumentException("Data cannot be null")
    • Otherwise return "Written [" + data + "] to " + filename
  • close() method: resource cleanup (no output required)

Main class

  • processQuery(String host, String sql) static method:
    • Create a DatabaseConnection using try-with-resources
    • Return the result of db.query(sql)
    • Let exceptions propagate to the caller
  • processWrite(String filename, String data) static method:
    • Create a FileWriterSim using try-with-resources
    • Return the result of writer.write(data)
    • Let exceptions propagate to the caller
  • 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