001 002package io.vrap.rmf.base.client; 003 004import java.util.function.Supplier; 005 006import io.vrap.rmf.base.client.http.InternalLogger; 007 008public abstract class AutoCloseableService extends Base implements AutoCloseable { 009 private boolean closed = false; 010 011 protected AutoCloseableService() { 012 log(() -> "Creating " + getLogName()); 013 } 014 015 private void log(final Supplier<Object> message) { 016 InternalLogger.getLogger(this.getClass()).trace(message); 017 } 018 019 private String getLogName() { 020 return this.getClass().getCanonicalName(); 021 } 022 023 @Override 024 public final synchronized void close() { 025 try { 026 internalClose(); 027 } 028 finally { 029 closed = true; 030 log(() -> "Closing " + getLogName()); 031 } 032 } 033 034 protected abstract void internalClose(); 035 036 protected final boolean isClosed() { 037 return closed; 038 } 039 040 protected void rejectExecutionIfClosed(final String message) { 041 if (isClosed()) { 042 throw new IllegalStateException(message);//rejection for execution so the exception will not be in the CompletionStage 043 } 044 } 045 046 public static void closeQuietly(final AutoCloseable closeable) { 047 try { 048 if (closeable != null) { 049 closeable.close(); 050 } 051 } 052 catch (final Exception e) { 053 InternalLogger.getLogger(AutoCloseableService.class).error(() -> "Error on closing resource.", e); 054 } 055 } 056 057 @Override 058 public boolean equals(final Object o) { 059 return reflectionEquals(o); 060 } 061 062 @Override 063 public int hashCode() { 064 return reflectionHashCode(); 065 } 066}