1
\$\begingroup\$

I am enapsulating my license backup to disk, using an interface ILicenseProvider and the implementation is DiskLicenseProvider. Also i am throwing an unchecked exception LicenseProviderException which wraps the checked exceptions in order to enable a central point of exception handling. Kindly review my code. What changes should I make?

public class LicenseProviderException extends RuntimeException {
    public LicenseProviderException(String message) {
        super(message);
    }
}
public class DiskLicenseProvider implements ILicenseProvider {

    private static final String APP_DIRECTORY = "test";
    private static final String LICENSE_FILENAME = "license.txt";
    private static final String TAG = DiskLicenseProvider.class.getSimpleName();
    private File appDirectory = new File(Environment.getExternalStorageDirectory(), APP_DIRECTORY);
    private File licenseFile = new File(appDirectory, LICENSE_FILENAME);


    @Override
    public boolean licenseExists() {
        return (appDirectory.exists() && licenseFile.exists() && licenseFile.length() > 0);
    }

    @Override
    public String getLicense() throws LicenseProviderException {
        StringBuilder builder = new StringBuilder();
        if (licenseExists()) {
            BufferedReader bufferedReader;
            try {
                bufferedReader = new BufferedReader(new FileReader(licenseFile));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    builder.append(line);
                }
                bufferedReader.close();
            } catch (FileNotFoundException e) {
                Log.d(TAG, "getLicense() called");
                throw new LicenseProviderException("Unable to find license file");
            } catch (IOException e) {
                Log.d(TAG, "getLicense() called");
                throw new LicenseProviderException("Unable to read license file");
            }

        }
        return builder.toString();
    }

    @Override
    public void saveLicense(String license) throws LicenseProviderException{
        if (!appDirectory.exists()) {
            if (!appDirectory.mkdirs()) {
                throw new LicenseProviderException("Unable to create application directory");
            }
        }

        try {
            FileWriter fileWriter = new FileWriter(licenseFile);
            fileWriter.write(license);
            fileWriter.close();
        } catch (IOException e) {
            Log.d(TAG, "saveLicense() called with: license = [" + license + "]");
            throw new LicenseProviderException("Unable to save license");
        }

    }

}
public interface ILicenseProvider {
    boolean licenseExists();

    String getLicense();

    void saveLicense(String license);

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.