Skip to content

Instantly share code, notes, and snippets.

@kuzux
Last active December 24, 2020 15:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuzux/ad927017416ce8f9528a9ec002146bac to your computer and use it in GitHub Desktop.
Save kuzux/ad927017416ce8f9528a9ec002146bac to your computer and use it in GitHub Desktop.
/* Copyright (C) 2020 I.C. Wiener - All Rights Reserved
* You may use, distribute and modify this code under the
* terms of the WTFPL license, which unfortunately won't be
* written for another century.
*
* You should have received a copy of the WTFPL license with
* this file. If not, please write to: , or visit :
*/
interface BooleanMapper<T> {
Boolean map(T arg);
}
// ...
class UserActivityBooleanMapper implements BooleanMapper<User> {
Boolean map(User user) {
return user.getIsActive();
}
}
// ...
interface BooleanCheckerStrategy {
Boolean checkIfEqual(Boolean a, Boolean b);
}
// ...
class StringBasedBooleanCheckerStrategy implements BooleanCheckerStrategy {
Boolean checkIfEqual(Boolean a, Boolean b) {
String aString = a.toString();
String bString = b.toString();
if(aString.equals(bString)) return true;
else return false;
}
}
// ...
class HashingBooleanCheckerStrategy implements BooleanCheckerStrategy {
Boolean checkIfEqual(Boolean a, Boolean b) {
int aHashCode = a.hashCode();
int bHashCode = b.hashCode();
int commonHashCode = aHashCode;
if(aHashCode != commonHashCode) return false;
if(bHashCode != commonHashCode) return false;
return true;
}
}
// ...
class BoringBooleanCheckerStrategy implements BooleanCheckerStrategy {
Boolean checkIfEqual(Boolean a, Boolean b) {
return (a==b)?true:false;
}
}
// ...
class OptimisticBooleanCheckerStrategy implements BooleanCheckerStrategy {
Boolean checkIfEqual(Boolean a, Boolean b) {
return true;
}
}
// ...
class LowLevelBooleanCheckerStrategy implements BooleanCheckerStrategy {
// needs option --add-opens java.base/jdk.internal.misc=ALL-UNNAMED
// we are using jdk.internal.misc.Unsafe
private static Unsafe unsafe;
static {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (Unsafe)field.get(null);
} catch (Exception e) {
e.printStackTrace();
}
}
private static long addressOf(Object o) throws Exception {
Object[] array = new Object[] {o};
long baseOffset = unsafe.arrayBaseOffset(Object[].class);
int addressSize = unsafe.addressSize();
long objectAddress;
switch (addressSize)
{
case 4:
objectAddress = unsafe.getInt(array, baseOffset);
break;
case 8:
objectAddress = unsafe.getLong(array, baseOffset);
break;
default:
throw new Error("unsupported address size: " + addressSize);
}
return(objectAddress);
}
Boolean checkIfEqual(Boolean a, Boolean b) {
// this method works because we know, in jre, all boolean objects share same 2 instances
try {
long aAddress = addressOf(a);
long bAddress = addressOf(b);
if(aAddress != bAddress) return false;
return true;
} catch(Exception ex) {
throw new ActivityCheckerException(ex.getMessage());
}
}
}
// ...
class BooleanCheckerBuilder<T> {
private BooleanMapper<T> mapper;
private BooleanCheckerStrategy strategy;
private T target;
private Boolean referenceValue;
public BooleanCheckerBuilder() {
mapper = null;
strategy = null;
target = null;
referenceValue = null;
}
public BooleanMapper<T> getMapper() {
return mapper;
}
public BooleanCheckerStrategy getStrategy() {
return strategy;
}
public T getTarget() {
return target;
}
public Boolean getReferenceValue() {
return referenceValue;
}
public void setMapper(BooleanMapper<T> mapper) {
this.mapper = mapper;
}
public void setStrategy(BooleanCheckerStrategy strategy) {
this.strategy = strategy;
}
public void setTarget(T target) {
this.target = target;
}
public void setReferenceValue(Boolean referenceValue) {
this.referenceValue = referenceValue;
}
public BooleanChecker<T> build() {
if(mapper == null) return null;
if(strategy == null) return null;
if(target == null) return null;
if(referenceValue == null) return null;
BooleanChecker<T> result = new BooleanChecker<T>();
result.mapper = mapper;
result.strategy = strategy;
result.target = target;
result.referenceValue = referenceValue;
return result;
}
}
// ...
class BooleanChecker<T> {
private BooleanMapper<T> mapper;
private BooleanCheckerStrategy strategy;
private T target;
private Boolean referenceValue;
// TODO: Implement memento pattern to resume from an interrupted check
public BooleanChecker() {
mapper = null;
strategy = null;
target = null;
referenceValue = null;
}
public BooleanMapper<T> getMapper() {
return mapper;
}
public BooleanCheckerStrategy getStrategy() {
return strategy;
}
public T getTarget() {
return target;
}
public Boolean getReferenceValue() {
return referenceValue;
}
public void setMapper(BooleanMapper<T> mapper) {
this.mapper = mapper;
}
public void setStrategy(BooleanCheckerStrategy strategy) {
this.strategy = strategy;
}
public void setTarget(T target) {
this.target = target;
}
public void setReferenceValue(Boolean referenceValue) {
this.referenceValue = referenceValue;
}
public Boolean run() {
if(mapper == null) return null;
if(strategy == null) return null;
if(target == null) return null;
if(referenceValue == null) return null;
Boolean valueToCompare = mapper.map(target);
Boolean result = strategy.checkIfEqual(valueToCompare, this.referenceValue);
return (result == true) ? true : false;
}
}
// ...
abstract class ActivityCheckerBaseException extends RuntimeException {
public ActivityCheckerBaseException(String message) {
Logger logger = Logger.getLogger(ActivityCheckerBaseException.class.getName());
logger.log(Level.ERROR, message);
super(baseMessage);
}
}
// ...
class ActivityCheckerException extends ActivityCheckerBaseException {
public ActivityCheckerException(String message) {
super(message);
}
}
// ...
class FactoryException extends ActivityCheckerBaseException {
public FactoryException(Class klass, String key, String message) {
StringBuilder builder = new StringBuilder();
builder.append(klass.getName());
builder.append(": ");
builder.append(message);
builder.append("(when accessing key ");
builder.append(key);
builder.append(")");
String baseMessage = builder.toString();
super(baseMessage);
}
}
// ...
abstract class AbstractFactory<T> {
protected Map<String, T> values;
public AbstractFactory() {
values = new HashMap<String, T>();
}
public void register(String key, T value) {
if(values.containsKey(key)) {
throw new FactoryException(this.class, key, "key already exists");
}
values.put(key, value);
}
public T getValue(String key) {
if(!values.containsKey(key)) {
throw new FactoryException(this.class, key, "key does not exist");
}
return values.get(key);
}
}
// ...
class ActivityCheckerAbstractFactoryFactory extends AbstractFactory<AbstractFactory> {
public ActivityCheckerAbstractFactoryFactory() {
super();
}
}
// ...
class ActivityCheckerAbstractFactoryFactorySingleton extends AbstractSingleton<ActivityCheckerAbstractFactoryFactory> {
protected static ActivityCheckerAbstractFactoryFactory createInstance() {
return new ActivityCheckerAbstractFactoryFactory();
}
}
// ...
class BooleanMapperFactory extends AbstractFactory<BooleanMapper>{
public BooleanMapperFactory() {
super();
}
public BooleanMapper createMapper(String key) {
return getValue(key);
}
}
// ...
class BooleanCheckerStrategyFactory extends AbstractFactory<BooleanCheckerStrategy>{
public BooleanMapperFactory() {
super();
}
public BooleanCheckerStrategy createCheckerStrategy(String key) {
return getValue(key);
}
}
// ...
class BooleanReferenceValueFactory extends AbstractFactory<Boolean>{
public BooleanMapperFactory() {
super();
}
public Boolean createReferenceValue(String key) {
return getValue(key);
}
}
// ...
class Configuration {
public static final String DEFAULT_CONFIG_LOCATION = "config/activityCheckerEnterpriseEdition.xml"
private String booleanCheckerStrategyName;
public String getBooleanCheckerStrategyName() {
return booleanCheckerStrategyName;
}
public void setBooleanCheckerStrategyName(String booleanCheckerStrategyName) {
this.booleanCheckerStrategyName = booleanCheckerStrategyName;
}
}
// ...
abstract class AbstractSingleton<T> {
protected static T instance;
public static T getInstance() {
if(instance == null) {
synchronized(AbstractSingleton.class) {
if(instance == null) {
instance = createInstance();
}
}
}
return instance;
}
protected abstract static T createInstance();
}
// ...
class ConfigurationSingleton extends AbstractSingleton<Configuration> {
private static String configurationLocation;
private static ConfigurationReader configurationReader;
public static String getConfigurationLocation() {
return configurationLocation;
}
public static void setConfigurationLocation(String configurationLocation) {
this.configurationLocation = configurationLocation;
}
public static ConfigurationReader getConfigurationReader() {
return configurationReader;
}
public static void setConfigurationReader(ConfigurationReader configurationReader) {
this.configurationReader = ConfigurationReader;
}
protected static Configuration createInstance() {
File configurationFile = new File(configurationLocation);
if(!configurationFile.exists()) {
throw new ActivityCheckerException("The specified configuration file does not exist")
}
Configuration result = ConfigurationReader.readFile(file);
configurationFile.close();
return result;
}
}
// ...
interface ConfigurationReader() {
Configuration readFile(File file);
}
// ...
class ConfigurationReaderImpl implements ConfigurationReader {
Configuration readFile(File file) {
FileInputStream inputStream = new FileInputStream(file);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(inputStream);
Element root = doc.getDocumentElement();
if(!root.getNodeName().equals("configuration")) {
throw new ActivityCheckerException("Invalid configuration file");
}
Configuration result = new Configuration();
NodeList booleanCheckerStrategyNameList = root.getElementsByTagName("booleanCheckerStrategyName");
if(booleanCheckerStrategyNameList.getLength() != 1) {
throw new ActivityCheckerException("Invalid configuration file");
}
Node booleanCheckerStrategyNameNode = booleanCheckerStrategyNameList.item(0);
if(booleanCheckerStrategyNameNode.getNodeType() != Node.ELEMENT_NODE) {
throw new ActivityCheckerException("Invalid configuration file");
}
String booleanCheckerStrategyName = booleanCheckerStrategyNameNode.getTextContent();
result.setBooleanCheckerStrategyName(booleanCheckerStrategyName);
return result;
}
}
// ...
void main(String[] args) {
// ...
String configurationLocation;
if(args.length == 0) {
configurationLocation = Configuration.DEFAULT_CONFIG_LOCATION;
} else {
configurationLocation = args[0]
}
ConfigurationSingleton.setConfigurationLocation(configurationLocation);
// ...
}
// ...
/* in a config file somewhere
<configuration>
<booleanCheckerStrategyName>UsingHashes</booleanCheckerStrategyName>
</configuration>
*/
// ...
ConfigurationSingleton.setConfigurationReader(new ConfigurationReaderImpl());
ActivityCheckerAbstractFactoryFactory factoryFactory = ActivityCheckerAbstractFactoryFactorySingleton.getInstance();
BooleanMapperFactory booleanMapperFactory = new BooleanMapperFactory();
BooleanCheckerStrategyFactory booleanCheckerStrategyFactory = new BooleanCheckerStrategyFactory();
BooleanReferenceValueFactory booleanReferenceValueFactory = new BooleanReferenceValueFactory();
factoryFactory.register("booleanMapperFactory", booleanMapperFactory);
factoryFactory.register("booleanCheckerStrategyFactory", booleanCheckerStrategyFactory);
factoryFactory.register("booleanReferenceValueFactory", booleanReferenceValueFactory);
booleanMapperFactory.register("User.IsActive", new UserActivityBooleanMapper());
booleanCheckerStrategyFactory.register("UsingStrings", new StringBasedBooleanCheckerStrategy());
booleanCheckerStrategyFactory.register("UsingHashes", new HashingBooleanCheckerStrategy());
booleanCheckerStrategyFactory.register("Boring", new BoringBooleanCheckerStrategy());
booleanCheckerStrategyFactory.register("Optimistic", new OptimisticBooleanCheckerStrategy());
booleanCheckerStrategyFactory.register("LowLevel", new LowLevelBooleanCheckerStrategy());
referenceValueFactory.register("true", new Boolean(true));
// ...
ActivityCheckerAbstractFactoryFactory factoryFactory = ActivityCheckerAbstractFactoryFactorySingleton.getInstance();
Configuration config = ConfigurationSingleton.getInstance();
BooleanMapperFactory booleanMapperFactory = factoryFactory.getValue("booleanMapperFactory");
BooleanCheckerStrategyFactory booleanCheckerStrategyFactory = factoryFactory.getValue("booleanCheckerStrategyFactory");
BooleanReferenceValueFactory booleanReferenceValueFactory = factoryFactory.getValue("booleanReferenceValueFactory");
BooleanMapper userActivityBooleanMapper = booleanMapperFactory.createMapper("User.IsActive");
BooleanCheckerStrategy stringBasedBooleanCheckerStrategy = booleanCheckerStrategyFactory.createCheckerStrategy(config.getBooleanCheckerStrategyName());
Boolean referenceValue = booleanReferenceValueFactory.createReferenceValue("true");
BooleanCheckerBuilder<User> builder = new BooleanCheckerBuilder<User>();
BooleanChecker<User> checker = builder.setTarget(user)
.setMapper(userActivityBooleanMapper)
.setStrategy(stringBasedBooleanCheckerStrategy)
.setReferenceValue(referenceValue)
.build();
if(checker.run().equals(true)) {
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment