[cleanup] prefer immutable data. Make sure streams are always closed. Refactored code to remove PMD and FindBugs errors