accounting-lib/src/main/java/org/gcube/accounting/datamodel/AggregationStrategy.java

82 lines
2.1 KiB
Java

/**
*
*/
package org.gcube.accounting.datamodel;
import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Set;
import org.gcube.accounting.exception.NotAggregatableRecordsExceptions;
/**
* @author Luca Frosini (ISTI - CNR) http://www.lucafrosini.com/
*
*/
public abstract class AggregationStrategy<T extends AggregatedUsageRecord<T, B>, B extends SingleUsageRecord> {
protected T t;
protected Set<String> aggregationField;
public AggregationStrategy(T t){
this.t = t;
this.aggregationField = new HashSet<String>();
this.aggregationField.add(BasicUsageRecord.USAGE_RECORD_TYPE);
this.aggregationField.add(BasicUsageRecord.SCOPE);
}
protected String commonFieldHash(B record) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
String concatenation = "";
for(String field : aggregationField){
concatenation = concatenation + record.getResourceProperty(field).toString();
}
messageDigest.update(concatenation.getBytes());
return new String(messageDigest.digest());
}catch(NoSuchAlgorithmException e){
throw new UnsupportedOperationException(e.getCause());
}
}
protected boolean isAggregable(UsageRecord record) {
for(String field : aggregationField){
Serializable recordValue = record.getResourceProperty(field);
Serializable thisValue = t.getResourceProperty(field);
// TODO Check THIS
if(!recordValue.equals(thisValue)){
return false;
}
}
return true;
}
protected abstract T reallyAggregate(T t) throws NotAggregatableRecordsExceptions;
public T aggregate(B record) throws NotAggregatableRecordsExceptions {
try{
if(isAggregable(record)){
throw new NotAggregatableRecordsExceptions("The Record provided as argument has different values for field wich must be common to be aggragatable");
}
t.getAggregatedUsageRecord(record);
t = reallyAggregate(t);
return t;
}catch(NotAggregatableRecordsExceptions e){
throw e;
}catch(Exception ex){
throw new NotAggregatableRecordsExceptions(ex.getCause());
}
}
}